text
stringlengths
3.07k
12.6k
#First draw the graph (let's consider the generic tree to be an undirected graph with no loops) #Store as an adjacency list and do a BFS and find the minimum distance among all nodes(Count the number of edges) #Store that information in an array of [spot,dictionary]-arrays import queue, json # Function for finding m...
import sys import tempfile import pytest from packaging.specifiers import Specifier from .minimum_dependency_generator import ( find_min_requirement, write_min_requirements ) @pytest.fixture(scope='session', autouse=True) def pandas_dep(): return 'pandas>=0.24.1,<2.0.0,!=1.1.0,!=1.1.1' @pytest.fixture...
######## User configuration #################################################################### # For purposes of reproducing experiments, this section is the only one that needs configuration # USERHOST must be of the form username@hostname; if empty, will access path locally USERHOST = "" PATH = "../output" # Ou...
load( ":poms_for_testing.bzl", "COMPLEX_POM", "GRANDPARENT_POM", "MERGED_EXPECTED_POM", "PARENT_POM", ) load(":testing.bzl", "asserts", "test_suite") load("//maven:poms.bzl", "poms") load("//maven:xml.bzl", "xml") def merge_properties_test(env): parent = """<project><properties> <foo>fo...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Dec 11 13:58:12 2017 @author: CW """ import numpy as np import torch import torch.nn as nn from torch.nn import Module import torchkit.nn as nn_ from functools import reduce # aliasing N_ = None delta = 1e-6 softplus_ = nn.Softplus() softplus =...
from quart import request, Request, jsonify, exceptions from functools import wraps import typing request: Request def find_excess(valid_keys: typing.Iterable[str], data: dict) -> typing.List[str]: """ Finds excess data in the json `data` provided. Returns any found arguments. """ return [key fo...
#!/usr/bin/env python """Application controller and utility functions for MSMS (molecular surface calculation).""" import os import tempfile from cogent.app.util import CommandLineApplication, ResultPath from cogent.app.parameters import FlagParameter, ValuedParameter from cogent.format.xyzrn import XYZRNWriter from c...
import os import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score class KMeans: def __init__(self, eps=1, max_iters=30): self.eps = eps self.max_iters = max_i...
""" 使用inception计算图片特征,比对1008个值的前10,相似度度量分为两步: 1、比对索引的相似度,索引值相等的个数越多,图片越相似 2、比对索引值的差值,差值越小,图片越相似 """ import os from glob import glob import numpy as np import tensorflow as tf flags = tf.app.flags flags.DEFINE_string("model_dir", "model", "model directory") flags.DEFINE_string("model_file", "classify_image_graph_def...
import json from datetime import datetime from finalization.runtime import get_all_final_data_as_dicts from processing.constants import EBAS_REPORTING_COMPOUNDS from settings import CORE_DIR, JSON_PUBLIC_DIR from plotting import create_monthly_ticks, MixingRatioPlot from analyses.JFJ_overlays.parsers import read_jfj_...
# -*- coding: utf-8 -*- """Console script for geotiff_reprojector.""" import sys import os import click import numpy as np import rasterio import rasterio.features from PIL import Image import PIL from osgeo import gdal from tqdm import trange, tqdm import geopandas as gpd import pandas as pd # disable pixel size che...
import sys from datetime import datetime, timedelta from typing import Any, Dict import click from flask import Flask, current_app from flask.cli import FlaskGroup, ScriptInfo, with_appcontext from alerta.app import config, create_app, db, key_helper, qb from alerta.auth.utils import generate_password_hash from alert...
# adapted from: # https://github.com/pytorch/tutorials/blob/master/intermediate_source/reinforcement_q_learning.py # date accessed: 2021.06.30 import os from collections import namedtuple from itertools import count import gym import neptune.new as neptune import numpy as np import torch import torch.nn as nn import ...
# ------------------------------ # # Routines to work with Genesis lattices. # C # #------------------------------------------------- # Helper functions def ele_types(eles): """ Returns a list of unique types in eles """ return list(set([e['type'] for e in eles] )) def eles_by_type(eles): """ ...
from .download import download from bs4 import BeautifulSoup from builtins import bytes from itertools import islice import json import re import requests import sys if sys.version_info.major < 3: from pathlib2 import Path else: from pathlib import Path client = requests.session() folders_url = "https://drive...
import time import txaio from datetime import datetime, timezone from influxdb import InfluxDBClient from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError from requests.exceptions import ConnectionError as RequestsConnectionError # For logging txaio.use_twisted() LOG = txaio.make_logger() def tim...
#!/usr/bin/python3 import os, sys from typing import * from argparse import ArgumentParser import mne from mne import Epochs, Evoked from mne.cov import compute_covariance, compute_raw_covariance from mne.io import Raw from mne.epochs import read_epochs from mne.evoked import read_evokeds from mne.minimum_norm import...
import os, glob import pandas as pd import numpy as np import torch from itertools import compress def imorphics_info(): df = pd.read_excel(os.getenv("HOME") + '/Dropbox/Z_DL/OAIDataBase/oai_active_contour_parameters.xlsx') df['subject_id'] = df['subject_id'].values.astype(np.int32) return df def moaks0...
""" Benchmark Operator Class to run various workloads, performance and scale tests previously known as Ripsaw and implemented from : https://github.com/cloud-bulldozer/benchmark-operator This operator can be used as an object or as a fixture """ # Internal modules import logging import tempfile import ti...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import utils import nn import time import argparse import wandb @tf.function def train_step(x, pen_lifts, text, style_vectors, glob_args): model, alpha_set, bce, train_loss, optimizer = glob_args alphas = utils.get_alphas(len(x), alpha_...
"""Test of Funsies user routines.""" # std import json import tempfile from typing import Tuple # external import pytest # funsies from funsies import _context, _graph, fp, Fun, options, ui from funsies._run import run_op from funsies.config import MockServer from funsies.types import Encoding, UnwrapError def test...
import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import cm import subprocess import sys from mpl_toolkits.mplot3d import axes3d, Axes3D def getDefName(definition): if definition == 1: return "NCD(x,y) = max {C(x|y*),C(y|x*)} / max{C(x), C(y)}" elif definition == 2: retu...
import ravop.core as R import sys from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from ravcom import inform_server class Node: def __init__(self, predicted_class, depth=None): self.predicted_class = predicted_class sel...
from tkinter import * def toggle_eyes(): current_color = c.itemcget(eye_left, 'fill') new_color = c.body_color if current_color == 'white' else 'white' current_state = c.itemcget(pupil_left, 'state') new_state = NORMAL if current_state == HIDDEN else HIDDEN c.itemconfigure(pupil_left, state=new_st...
###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
import struct import sys import argparse import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import classification_report from os.path import exists # assuming MNIST dataset file format (big endian) def dataset_reader(path): f = open(path, 'rb') magic, size, rows, cols = struct.unpack(">II...
from detectron2.utils.logger import setup_logger import pandas as pd import numpy as np import cv2 import random import matplotlib.pyplot as plt from PIL import Image import os import numpy as np import json from detectron2 import model_zoo from detectron2.engine import DefaultPredictor, DefaultTrainer from detectron2....
# -*- coding: utf-8 -*- import os import json import datetime from functools import wraps from flask import render_template, session, redirect, url_for, current_app, \ abort, flash, request, make_response, g from flask_login import login_required, login_user, logout_user, current_user from wtforms import HiddenFiel...
"""Deep Q model The functions in this model: ======= step ======== Function to chose an action given an observation Parameters ---------- observation: tensor Observation that can be feed into the output of make_obs_ph stochastic: bool if set to False all the actions are always de...
import ctypes from pyglet.gl import * from util import Vector3 class Renderer: # sets up the openGL enable/disables def __init__(self): self.currData = None # used to reduce state changes self.currTexture = None # used to reduce state changes self.fogEnabled = False glEnable(GL_DEPTH_TEST) # E...
''' BSD Licence Copyright (c) 2016, Science & Technology Facilities Council (STFC) All rights reserved. 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 no...
import os def print_head(): print("=======================================================================") print("Gestión de notas - \"<NAME> - Desarrollo / Formación\"") print("=======================================================================") print("\n\t\t\tDATOS GENERALES") print("=====...
# coding:utf-8 import argparse import sys from commands import Commands from . import __version__ def build_parser(): parser = argparse.ArgumentParser( description='ExactTarget Command Line Interface Tool.') parser.add_argument( '-v', '--version', action='version', version='%(prog)s ' ...
# -*- coding: utf-8 -*- # Builtin Modules import os import sys import socket import simplejson as json import logging import time import ssl # 3rd-party Modules from celery import Celery, signals import redis import psutil # Project Modules from worker.utils import yaml_resources, toolkit # Configure print_detail =...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 根据count表达式动态生成新的变量 """ import base64 from threathunter_common.util import binary_data from nebula_meta.variable_filter import Filter from nebula_meta.variable_model import VariableModel, add_variable_to_registry from nebula_meta.variable_function import Function from...
import functional as F import math import copy from sympy import Symbol, pprint, solve def shape(matrix): if not F.is_sequence(matrix): return None shapes = [] acc_matrix = matrix while True: matrix_length = len(acc_matrix) shapes.append(matrix_length) if not F.is_sequence(ac...
import json import urllib import sys from httplib import HTTPConnection from pyld import jsonld class Entity(object): """Represents and entity in the ontology, created from its expanded JSON-LD representation. Attributes: jsonld: the expanded JSON-LD representation of the entity. """ def...
# pylint: skip-file import logging from inspect import signature from collections import OrderedDict as odict from recipes.caches import to_file, Cache, CacheEncoder, CacheDecoder from recipes.caches.decor import check_hashable_defaults from pathlib import Path import pickle import tempfile import pytest import itertoo...
import pathlib import sys from typing import List, Tuple, Dict, Any import matplotlib.colors as mcolors import matplotlib.pyplot as plt from hcb.artifacts.make_lambda_plots import DesiredLineFit, project_intersection_of_both_observables from hcb.tools.analysis.collecting import MultiStats from hcb.tools.analysis.plot...
""" owtf.managers.config_manager ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Manage configuration methods. """ import logging import os import yaml from owtf.config import config_handler from owtf.lib.exceptions import InvalidConfigurationReference from owtf.models.config import Config from owtf.utils.error import abort_framework fr...
import sys import os import subprocess import shutil INPUT_DIR = sys.argv[1] OUTPUT_DIR = sys.argv[2] SOOT_JAR = sys.argv[3] def compile(classpath, package, java_file, dest_dir): classes_dir = os.path.join(dest_dir, 'build', 'classes') java_file_path = os.path.join(package, java_file) src_dir = os.path.j...
""" This module is highly inspired by: https://github.com/pytorch/tnt BSD 3-Clause License Copyright (c) 2017- <NAME>, Copyright (c) 2017- <NAME>, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Re...
import logging from django.conf import settings from django.contrib import messages, auth from django.contrib.auth import login from django.contrib.auth.models import User from django.contrib.auth import views from django.db.models import Q from django.shortcuts import redirect, get_object_or_404 from django.template....
# # eMammal_helpers.py # # Support functions for processing eMammal metadata # #%% Constants and imports from PIL import Image, ImageDraw import matplotlib.pyplot as plt import operator from datetime import datetime #%% Support functions def clean_species_name(common_name): """ Converts various forms of "h...
# The MIT License (MIT) # # Copyright (c) 2017 <NAME> for Adafruit Industries LLC # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the right...
""" MIT License Copyright (c) 2021 Standby Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dist...
# The MIT License (MIT) # # Copyright (c) 2017-2018 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modif...
import numpy as np import pandas as pd from tqdm import tqdm from numpy.matlib import repmat def raised_cosine(duration, nbases, binfun): nbins = binfun(duration) ttb = repmat(np.arange(1, nbins + 1).reshape(-1, 1), 1, nbases) dbcenter = nbins / nbases cwidth = 4 * dbcenter bcenters = 0.5 * dbcent...
import torch import torch.nn as nn import math from ltr.models.backbone.resnet import BasicBlock from ltr.models.layers.blocks import conv_block from ltr.models.lwl.utils import interpolate class ResidualDS16SW(nn.Module): """ Outputs the few-shot learner label and spatial importance weights given the se...
#!/usr/bin/env python # # # netid2fasta.py <species>_[meta|prio]AggNet.hdf5 <species>_info.csv <uniprot-all.fasta> # # "EntrezID","EnsemblID","GeneSymbol","LocusTag","Synonyms","dbXrefs", # "Chromosome","Type","UniProtID","UniProtID2","OrthoID","NetworkIDs" ## # # >sp|Q8CJG1|AGO1_MOUSE Protein argon...
"""ResNet model for CIFAR-10 dataset """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import models def update_argparser(parser): models.update_argparser(parser) args, _ = parser.parse_known_args() if args.dataset == 'cif...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
# Copyright (c) 2018 HarryR. # License: LGPL-3.0+ import json import ctypes from functools import reduce from binascii import unhexlify from collections import namedtuple from py_ecc import bn128 from py_ecc.bn128 import pairing, FQ, FQ2, FQ12, neg, multiply, add _VerifyingKeyStruct = namedtuple('_VerifyingKeyStru...
from math import sqrt, log def log_loss(results): predicted = [min([max([x, 1e-15]), 1-1e-15]) for x in map(lambda x: float(x[0]), results)] target = [min([max([x, 1e-15]), 1-1e-15]) for x in map(lambda x: float(x[1]), results)] return -(1.0 / len(target)) * sum([target[i] * log(predicted[i]) + (1.0 - t...
# Python Build for training, testing and exporting model import ast import json import logging # Importing Libraries import os import pickle from enum import Enum from pathlib import Path import joblib import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler...
"""Given a CSV file of variable information defining the regions of interest along with input and output fasta file paths, write a file that contains a fasta-formatted representation of these regions.""" import sys import click as cli import csv from collections import namedtuple import textwrap as tw from pyfaidx i...
import torch import torch.nn as nn import numpy as np import glob import logging from pyro.distributions import TransformedDistribution from models.layers.CondIAF import CondInverseAutoregressiveFlowStable from Translator import lookup_words def init_logger(fn=None, cont=False): # !!! here from imp import re...
""" THis module contains widgets used for error reporting. The report backed is sentry_. .. _sentry: https://sentry.io """ import getpass import re import sys import traceback import typing import requests import sentry_sdk from qtpy.QtWidgets import ( QDialog, QHBoxLayout, QLabel, QLineEdit, QLis...
import os import ctypes import shutil import platform import hashlib import time, datetime from getpass import getpass dicts = dict() def WriteFile(filename,content): with open(filename,'a', encoding = "UTF-8") as fw: fw.write(str(content)+'\n') def BUG(): os.system("cls") print("请按照提示进行操作:") problem ...
import ptypes from ptypes import ptype,parray,pstruct,pint,pstr,dyn,pbinary ptypes.setbyteorder(ptypes.config.byteorder.littleendian) ### header markers class ElfXX_File(ptype.boundary): pass class ElfXX_Header(ptype.boundary): pass class ElfXX_Ehdr(ElfXX_Header): pass ### base class uchar(pint.uint8_t): pass class E...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os.path import configparser import pandas as pd from tqdm import tqdm from tsfresh.utilities.dataframe_functions import impute from tsfresh.feature_extraction import feature_calculators def main(): if len(sys.argv) < 2: print('Usage: ./extract_best_...
# from pathlib import Path # import numpy as np import torch import torch.nn as nn from collections import OrderedDict from typing import List from goodok_mlu.utils import rgetattr params_aliases = [ {"old_key_starts": 'surfacepred.p1.', "new_key_starts": "surfacepred.fcn.block.1."}, {"old_key_starts": 's...
""" Copyright 2012-2019 <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 di...
from os import path, makedirs from assetsy.assets import FileAsset, GlobAsset, AssetCollection from glob import has_magic from assetsy.processors import ProcessorManager from assetsy.exceptions import BuildError import types from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler fro...
import copy import os import warnings import numpy as np import torch from sympy import N, lambdify from . import test_points from .get_pareto import Point from .RPN_to_eq import RPN_to_eq from .S_get_expr_complexity import get_expr_complexity warnings.filterwarnings("ignore") is_cuda = torch.cuda.is_available() #...
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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 agre...
import json from django.utils import timezone from datetime import datetime from django.templatetags.tz import localtime from django.shortcuts import render, get_object_or_404, redirect from django.utils.translation import ugettext_lazy as _ from django.http import Http404 from django.core.management import call_comma...
""" This module handles the communication with EVE SSO """ from base64 import urlsafe_b64encode import logging from typing import List from urllib.parse import urljoin from pydantic.error_wrappers import ValidationError from requests.exceptions import HTTPError import jwt import pydantic as pdt import requests from ...
import rlp from ethereum.transactions import Transaction, UnsignedTransaction from ethereum.utils import ( big_endian_to_int, int_to_big_endian, safe_ord, sha3 ) from .utils import data_decoder, data_encoder # TODO: do these make sense? (they were taken from geth, so i hope so!) DEFAULT_STARTGAS = 21000 DEFAULT_G...
import json import pandas as pd import os import shutil from datetime import date import urllib.request from bs4 import BeautifulSoup DATA_DIR = "../data" DATA_FILE = os.path.join(DATA_DIR, "data.json") DUMP_FILE = os.path.join(DATA_DIR, "dump.pkl") store_columns = ( "id", # 음식점 고유번호 "store_name", # 음식점 이름 ...
from django.http import HttpResponse import json from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required ...
import logging import numpy as np from scipy.signal import find_peaks, fftconvolve from scipy.io import wavfile from m2.rec2taps import errors from m2.rec2taps.defaults import DEFAULT_DISTANCE, DEFAULT_PROMINENCE CAN_DEBUG_PLOT = False try: import matplotlib import matplotlib.pyplot as plt matplotlib.use('...
""" Implementation borrowed from transformers package and extended to support multiple prediction heads: https://github.com/huggingface/transformers/blob/master/src/transformers/models/bert/modeling_bert.py """ import math import torch import torch.utils.checkpoint from packaging import version from torch import nn ...
import csv from matplotlib.pyplot import text import tweepy import ssl import config import logging import random import gift_axie_lib as gift import re import gift_axie_ocv_lib as decocv import json import requests ssl._create_default_https_context = ssl._create_unverified_context # Oauth keys consumer_key = "XXX" ...
#!/usr/bin/env python3 """Interactive interface to full DrQA pipeline.""" import argparse import logging import json import torch from functools import partial from multiprocessing.pool import ThreadPool from smart_open import smart_open from drqa import pipeline from drqa.retriever import utils logger = logging.g...
""" Token. """ import re import unicodedata import emoji from emoji import EMOJI_ALIAS_UNICODE_ENGLISH, UNICODE_EMOJI_ENGLISH from tweet_nlp_toolkit.constants import ( MENTION_TAG, HASHTAG_TAG, URL_TAG, DIGIT_TAG, EMOJI_TAG, EMOTICON_TAG, PUNCTUATION_TAG, EMAIL_TAG, UNKNOWN_LANGUAG...
from attrbench.lib.masking import Masker from attrbench.lib import segment_attributions from typing import List, Union, Optional import numpy as np import torch class ImageMasker(Masker): def __init__(self, feature_level): if feature_level not in ("channel", "pixel"): raise ValueError(f"featur...
""" This file contains functions returning specific values for the given project "self-driving_car". """ import numpy as np import cv2 def camera(): """ Camera with the calibration used in Udacity self-driving-car nanodegree :return: Camera """ from lane_lines_finder.camera import Camera cam ...
from .common import * from partname_resolver.components.resistor import Resistor from partname_resolver.units.resistanceTolerance import Tolerance from ..units.temperature import TemperatureRange import re from decimal import Decimal series = {'RL': 'Thick Film Chip Resistor'} resistor_type = {'RL': Resistor.Type.Thi...
import random as r from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render from .forms import PaladinForm, WarriorForm, DruidForm, ThingsForm from .models import * def put_on_inventory(request, hero_id, thing_id): person = get_object_or_404(Heroes, id=hero_id...
# Divides the data into train, validation and test sets, or determines the cross-validation splits. # The indexes of the splits are stored so experiments can be reproduced. from . import load_restore as lr import csv import random import math import sys def split_train_validation(train, validation, act_values): '''...
import tensorflow as tf from openpose.core.backbone import VGG from configuration import OpenPoseCfg as cfg class ConvBlock(tf.keras.layers.Layer): def __init__(self, filters): super(ConvBlock, self).__init__() self.bns = list() self.convs = list() self.acts = list() for ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import h5py import argparse from tqdm import tqdm def merge(config): dir_name = os.path.join('datasets/', config.dir_name) check_path(dir_name) f = h5py.File(os.path.join(dir_name, 'da...
import os, argparse, glob import numpy as np import cv2 from scipy.misc import imread, imsave from skimage.measure import compare_ssim import psnr import fastaniso import py_utils as utils parser = argparse.ArgumentParser() parser.add_argument('--input_root', default='') parser.add_argument('--dir_list', default='di...
"""Implementation module of Pesel Class""" import random import time import calendar from datetime import date, datetime from typing import Union, Optional from enum import Enum class PeselConst(Enum): """PeselConst Class contains magic numbers for Pesel Class""" YEAR_BASE = 1900 YEAR_MIN = 1800 YEAR...
import turtle import time u_door = None n = 100 print("You are stuck in an infinite loop! You need to find your way out! Wait! \ I smell a break around here! Go find it before you go insane in this horrible\ place!You can start by choosing one of these three doors i guess?") screen = turtle.Screen() clock = turtle.Tur...
# pylint: disable=no-member, invalid-name """ generate basic shapes, anomaly patterns for meshpy """ # Copyright (c) <NAME>. All rights reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np def throx(num_poly): """ draw 'throx' outline (points) codes copie...
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 12:49:11 2018 @author: Zhang """ import feather import pandas as pd import numpy as np import math import os import datetime def findtimebound(filepath): filenamelist = os.listdir(filepath) starttime = [] endtime = [] count = 0 ...
import torch import torchvision from torch import nn class double_conv(nn.Module): def __init__(self, inchannel, outchannel): super(double_conv, self).__init__() self.layers = nn.Sequential( nn.Conv2d(inchannel, outchannel, 3, padding=1, bias=False), nn.InstanceNorm2d(outcha...
# 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 app...
from datetime import datetime import django.utils.timezone as timezone from django.db import models # Create your models here. class ItemAnalysis(models.Model): ITEM_TYPE = ( (1, 'movie'), (2, 'book'), ) dad_id = models.CharField(max_length=20, null=False, blank=False) dad_type = mode...
#!/usr/bin/env python3 """SOURCE: CPsridharCP on github. https://github.com/CPsridharCP/MistySkills/blob/master/Apps/Teleop/02_pythonTeleop/findMisty.py""" from gevent import monkey monkey.patch_all() import socket import grequests import requests import json import PySimpleGUI as sg import pyperclip # SCANS NETWOR...
import json import pandas as pd import numpy as np from functools import reduce from PyQt5.QtGui import QColor from logger import log from api.algorithm import AbstractAlgorithm from api import TextProcessor from models import TextNode __all__ = ['Describer', 'encapsulate_html'] def random_color(): return QCol...
import os, sys from functools import partial from nnodes import Node from functions.utils import optimdir, removedir from functions.make_data import make_data, get_NM from functions.forward import forward from functions.kernel import frechet from functions.cost import cost from functions.gradient import gradient from f...
#! /usr/bin/env python import rospy import random from math import sqrt, atan2, floor, cos, sin from scipy.spatial import KDTree max_iter = 10000 goal_sample_rate = 30 lethal_cost = 150 path_resolution = 1 def index_to_world(index, resolution, origin, width): """ Convert index to world coordinates """ x = int(in...
import click import pygame from ouroboros.input import decode_input, Selected, check_for_selection, check_for_override from ouroboros.display import Display from ouroboros.food import Food from ouroboros.snake import Snake from ouroboros.sounds import Sounds from ouroboros.sprite_images import SpriteImages from ourobo...
from pyspark import since, keyword_only, SparkContext from pyspark.ml.param import Param, Params, TypeConverters from pyspark.ml.param.shared import HasInputCol, HasOutputCol, HasHandleInvalid from pyspark.ml.util import JavaMLReadable, JavaMLWritable from pyspark.ml.wrapper import _jvm from pyspark.ml.wrapper import J...
# Copyright (C) 2019 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
# Copyright 2017 AT&T Intellectual Property. All other 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...
#!/usr/bin/env python import pytest from dsviz import DoublyLinkedList ## Fixtures @pytest.fixture def empty_int_dll(): return DoublyLinkedList('', int) @pytest.fixture def empty_str_dll(): return DoublyLinkedList('', str) @pytest.fixture def int_dll(): dll = DoublyLinkedList('', int) dll.appe...