text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # Copyright (C) 2014 <NAME> <<EMAIL>> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type # Updated 2016 by <NAME> <<EMAIL>> # # Added support for Proxmox VE 4.x #...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import numpy as np dot = np.dot norm = np.linalg.norm mass_dict = {'H': 1.0, 'C': 12.0, 'O': 16.0, \ 'Pt': 195.0, 'Ag': 107.9} def read_poscar(poscar='POSCAR', format='vasp5'): """read POSCAR""" with open(poscar, 'r') as reader: ...
from envinorma.from_legifrance.legifrance_to_am import ( ArticleStatus, LegifranceArticle, LegifranceSection, _extract_sections, _structure_text, extract_table, ) from envinorma.io.markdown import ( DataFormat, Link, _extract_sorted_links_to_display, _insert_links, extract_ma...
# Copyright (c) 2021 China Unicom Cloud Data Co.,Ltd. # Copyright (c) 2019 - 2020 China Telecom Corporation # 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 # #...
# -*- coding: utf-8 -*- import sys, os from argparse import ArgumentParser from sklearn.decomposition import PCA from scipy.stats import gaussian_kde import numpy as np sys.path.insert(1, os.path.join(sys.path[0], os.path.pardir)) from json_utils import load_json_file, load_json_stream def extract_mat(langs): # i...
# 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...
import tensorflow as tf import numpy from scipy import misc import models def optimistic_restore(session, save_file): reader = tf.train.NewCheckpointReader(save_file) saved_shapes = reader.get_variable_to_shape_map() var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables() if var...
"""Provides API for legacy user sessions.""" import ipaddress import json from datetime import datetime, timedelta from pytz import timezone import hashlib from base64 import b64encode, b64decode from typing import Optional, Generator, Tuple, List from sqlalchemy import create_engine from sqlalchemy.exc import SQLAl...
from flask import request, url_for, redirect, abort, flash from flask_login import login_required, current_user from typing import List from app import db from app.main.views.utils import render_template_with_nav_info from app.models import Corpus, User, Role, ControlLists, CorpusUser, ControlListsUser, WordToken from...
""" Unit Tests for searching """ import unittest from ..searching import binary_search, kmp_search, rabinkarp_search, bmh_search, depth_first_search class TestBinarySearch(unittest.TestCase): """ Tests Binary Search on a small range from 0-9 """ def test_binarysearch(self): self.seq = range(1...
import numpy as np import pytest from kickscore.fitter import BatchFitter, RecursiveFitter from kickscore.kernel import Matern32 from math import log, pi KERNEL = Matern32(var=2.0, lscale=1.0) # GPy code used to generate the ground-truth values. # # kernel = GPy.kern.Matern32( # input_dim=1, varianc...
import base64 from datetime import datetime import os class Boss: def __init__(self, parent, level, options=None): self.level = level self.parent = parent self.boss_list = { '1':["FBI Cybercrimes Unit",2,os.path.join("assets", "art", "fbi.gif")], '2':["PLA Unit 6139...
#!/usr/bin/env python # Filename: pre_yolo_data """ introduction: conver training data for semantic to yolo objection. authors: <NAME> email:<EMAIL> add time: 04 April, 2021 """ import os,sys from optparse import OptionParser code_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') sys.path.insert(...
import numpy from hashlib import sha256 from src.configurations import CACHE_FOLDER, SAMPLES_PER_SECOND, APPEARANCES_OUTFILE, SCORE_THRESHOLD DEBUG = True if DEBUG: all_scores = [] passed_scores = [] all_scores_mean_n_std = lambda: (numpy.mean(all_scores), numpy.std(all_scores)) passed_scores_mean_n_...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Program entry point""" import json import os.path import subprocess import sys import icoextract from PyQt5 import QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def get_styles(filename): file = f"resources/styles/{fi...
import requests import psycopg2 from psycopg2 import Error import re import urllib.parse import copy import json from datetime import datetime from dateutil.parser import parse def is_date(string, fuzzy=False): """ Return whether the string can be interpreted as a date. :param string: str, string to check...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018 <NAME> <<EMAIL>> # License: MIT import re import sys parse_re = re.compile(r"([xy])=(\d+), ([xy])=(\d+)..(\d+)") def claycoordinates(lines): for line in lines: match = parse_re.match(line) coord1 = match.group(1) coord1val =...
# Copyright 2018 Amazon.com, Inc. or its 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
# # Copyright (c) 2021, NVIDIA CORPORATION. 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 appl...
from namsa import SupercellBuilder, MSAGPU from utils import * import numpy as np from time import time import sys, os, re import h5py from mpi4py import MPI from itertools import chain, product import tensorflow as tf import lmdb comm = MPI.COMM_WORLD comm_size = comm.Get_size() comm_rank = comm.Get_rank() def sim...
"""Selecting simulations from a scan based on parameters. """ import os import pickle from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union import numpy from tqdm import tqdm from mlxtk.cwd import WorkingDir from mlxtk.log import get_log...
import requests from urllib.parse import quote from urllib.parse import urlencode import csv import Scripts.Dependencies as Dependencies # OAuth credential placeholders that must be filled in by users. # You can find them ons # https://www.yelp.com/developers/v3/manage_app # API constants, you shouldn...
# # # # # # network.py # # University of Illinois/NCSA Open Source License # Copyright (c) 2015 Information Trust Institute # All rights reserved. # # Developed by: # # Information Trust Institute # University of Illinois # http://www.iti.illinois.edu # # Permission is hereby granted, free of charge, to any person obta...
__author__ = ["<NAME>"] __copyright__ = u"Copyright 2020, The Pagral Project" __credits__ = [u"<NAME>"] __version__ = u"0.1.2" __maintainer__ = u"<NAME>" __email__ = "<EMAIL>" __status__ = u"Development" __date__ = u"12/09/2020" __license__ = u""" Copyright (C) 2016-2020 <NAME> <<EMAIL>> <NAME> 261, 00198 Rome, It...
#!/usr/bin/env python from bs4 import BeautifulSoup from bs4.diagnose import diagnose from Crypto.Hash import SHA256 from simhash import Simhash from dataclasses import dataclass from dataclasses import field from pathlib import Path @dataclass class Node: name: str = field(default="") attributes: list[str] =...
import scipy.constants from scipy.signal import fftconvolve, oaconvolve import scipy.fft as sp_fft import numpy as np from numpy import sqrt, arctan ,arctanh, arctan2, log def lafun(x,y,z): """ Indefinite integral for the Coulomb potential \int 1/r dx dy dz """ r=sqrt(x**2+y**2+z**2) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import argparse import datetime import hashlib import json import os import platform import pprint import re import requests import string import sys import yaml from collections import defaultdict ###################################...
import concurrent.futures import json import logging import re from datetime import datetime from time import sleep import pytz from faunadb import query as q from faunadb.client import FaunaClient from faunadb.objects import Ref from telegram import ( InlineKeyboardButton, InlineKeyboardMarkup, KeyboardBu...
from collections import OrderedDict import pandas as pd import torch from utils.data import BanditData from config.constants import EVAL_DISPLAY_BATCH import os class Evaluator(object): def __init__(self, file_dir, method="Default", dataset="Default"): is_exists = os.path.exists(file_dir) if not ...
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. 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 array import array import wx import numpy as np from numpy.random import default_rng def _lerp(x, y, alpha): return x + (y - x) * alpha def _lerp_color(x: wx.Colour, y: wx.Colour, alpha): return wx.Colour( _lerp(x.red, y.red, alpha), _lerp(x.green, y.green, alpha), _lerp(x.blue, ...
# This software is distributed under the 3-clause BSD License. # TBD: put in more options: threads, mipgaps for spokes # There is manipulation of the mip gap, # so we need modifications of the vanilla dicts. # Notice also that this uses MutliExtensions import sys import json import uc_funcs as uc from mpisppy.util...
from datetime import datetime, date, timedelta def chinweekday2int(chin_weekday): '''中文數字轉阿拉伯數字 Args: (string)chin_weekday: 中文數字 Returns: (int)阿拉伯數字 ''' if chin_weekday == '一': return 1 elif chin_weekday == '二': return 2 elif chin_weekday == '三': retu...
import pytest import math import torch import torch.nn as nn import torch.nn.functional as F from einops import repeat, rearrange from src.models.modules.masking import LengthMask, TriangularCausalMask from src.models.attention.full_attention import FullAttention from src.models.attention.sblocal_attention import S...
import tensorflow as tf def get_activation_fn(type='relu'): """ Return tensorflow activation function given string name. Args: type: Returns: """ if type == 'relu': return tf.nn.relu elif type == 'elu': return tf.nn.elu elif type == 'tanh': return tf.n...
import unittest from unittest_data_provider import data_provider from flambda_app.database.mysql import MySQLConnector from flambda_app.request_control import Pagination, Order from flambda_app.logging import get_logger from flambda_app.repositories.v1.mysql.product_repository import ProductRepository from flambda_ap...
# coding: utf8 from __future__ import annotations import collections.abc as c_abc #import cProfile import gzip import json import logging import pathlib from typing import Dict, IO, List, Optional, Union from pydub import AudioSegment from . import model, utau, utils from .jsonclasses import dataclass from .resampl...
import numpy as np import pytest import torch from carla.data.catalog import DataCatalog from carla.models.catalog import MLModelCatalog from carla.models.pipelining import encode, scale testmodel = ["ann", "linear"] test_data = ["adult", "give_me_some_credit", "compas"] def test_properties(): data_name = "adul...
# (C) Copyright 2020 EdgeCortix 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 ...
''' Created on Jan 28, 2015 @author: <NAME> <<EMAIL>> ''' from __future__ import division import os import UserDict import yaml import numpy as np from shapely import geometry import matplotlib.pyplot as plt from matplotlib import widgets from utils.plotting import backend class TackingAnnotations(UserDict.Dic...
# -*- coding: utf-8 -*- """ Last update: 30/11/2021 <NAME> """ import os try: import numpy as np from scipy.interpolate import griddata except ModuleNotFoundError as error: if error.name in ('numpy','scipy'): print('\n'+error.msg+'\nPlease use PIP to install: "pip install '+error.name+'"\n') ...
#-*- coding:utf-8 -*- from django.conf import settings from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.views.generic import View, TemplateView from core.models import Photodb, Photofavorite from django.contrib.auth import authenticate, login, logout f...
import datetime import json import os import subprocess import traceback from dateutil.parser import isoparse from auto_backup.argument_assigner import assign_arguments_to_self class Task(object): def __init__(self, name, tags, command, notify): self.name = name self.tags = set(tags) sel...
# Copyright 2018 Amazon.com, Inc. or its 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
""" <NAME> Thu Feb 12 10:22:28 2020 Python 2 - DAT-129 - Spring 2020 Homework 2 Icon Processing Adjustment A """ #PLAN # ============================================================================= # Print an icon using a static input # loop through list, print @ if 1, " " if 0 # ...
# triplet loss import tensorflow.keras.backend as K from itertools import permutations import random import tensorflow as tf import numpy as np def generate_triplet(x, y, ap_pairs=10, an_pairs=10): data_xy = tuple([x, y]) trainsize = 1 triplet_train_pairs = [] y_triplet_pairs = [] #triplet_test...
from nhlscrapi._tools import to_int from nhlscrapi._tools import exclude_from as ex_junk from nhlscrapi.scrapr.reportloader import ReportLoader from nhlscrapi.games.events import EventType as ET class TOIRepBase(ReportLoader): """ Scrapes TOI reports. (home/away are same format). """ def __init__...
from avatar2 import QemuTarget from avatar2 import MemoryRange from avatar2 import Avatar from avatar2.archs import ARM, MIPS_24KF from avatar2.targets import Target, TargetStates from avatar2.message import * import tempfile import os import time import intervaltree import logging from nose.tools import * qemu = ...
import os import textwrap import shutil import stat from jinja2 import Environment, FileSystemLoader import yzrpc from . import CommandBase, CommandError from yzrpc.utils import get_abspath class Command(CommandBase): formatter_cls_name = 'RawDescriptionHelpFormatter' description = textwrap.dedent('''\ ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Time: 2020/10/28 17:49:44 # Author: <NAME> import os import sys import copy from six import StringIO import numpy as np import gym from gym import spaces from chip_place_gym.envs import connect from chip_place_gym.native import load_data EMPTY = 0 BLACK = -1 # inp...
import numpy as np # The following functions take a dictionary of astronomical values (degrees) # and return dimensionless scale factors for constituent amplitudes. def f_unity(a): return 1.0 # Schureman equations 73, 65 def f_Mm(a): omega = np.radians(a['omega'].value) i = np.radians(a['i'].value) I = np.radia...
import numpy, openravepy from tsr.tsrlibrary import TSRFactory from tsr.tsr import TSR, TSRChain @TSRFactory('herb', 'rubbermaid_ice_guard_pitcher', 'push_grasp') def pitcher_grasp(robot, pitcher, push_distance=0.1, manip=None, **kw_args): ''' @param robot The robot performing the grasp @param pitcher The...
'''traju is a simple util for batch processing of MD trajectories using AmberTools' cpptraj ''' from __future__ import annotations __all__ = [] from os import getenv from sys import stdout from shutil import move from pathlib import Path from typing import * from itertools import chain import logging import asynci...
import tensorflow as tf import os import cv2 from config import config import dlib import argparse from data_utils import * from model import * def parse_arg(argv=None): parser = argparse.ArgumentParser() parser.add_argument("--trained_weights", type=str, default="weights/gl...
from collections import OrderedDict, defaultdict import six from six.moves import configparser class _LineTrackingMixin(object): # This is an internal class that patches in line tracking functionality # to objects derived from RawConfigParser. # Note: No docstring so that we don't accidentally mess up d...
import os import cv2 import copy import skimage import numpy as np from math import log10, sqrt from pathlib import Path import matplotlib.pyplot as plt def imageAcquisition(path): img = cv2.imread(path, 0) return img def getBlocks(img, i, j, size): #get the block of the image b_img = np.zeros((s...
import argparse import numpy as np import random import matplotlib import seaborn as sns; sns.set() # matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode import matplotlib.pyplot as plt import baselines.common.plot_util as pu # plt.rcParams['svg.fonttype'] = 'svgfont' # plt.rcParams.update({'font....
# coding: utf-8 from django.db import IntegrityError from django.utils import timezone from social_django.utils import load_backend, load_strategy from rest_framework.authtoken.models import Token from rest_framework import parsers from rest_framework import renderers from rest_framework import permissions from rest_f...
from flask import Flask, request, render_template from toolkit import WordCount from toolkit import Readability import re app = Flask(__name__) MAX_CONTENT_LENGTH = 10000 @app.route('/') def default(): return homepage() @app.route('/scores', methods=['GET']) def scores_get(): return render_template('readabil...
# -*- coding: utf-8 -*- import datetime import pkg_resources import requests from lxml.etree import XMLSchema, DTD, DocumentInvalid from defusedxml.lxml import fromstring from geolink_formatter.entity import Document, File class SCHEMA(object): """Provides the available geoLink schema versions.""" V1_0_0 = ...
from flask import Flask, request, jsonify, send_from_directory, Response, render_template, json from flask_cors import CORS from werkzeug.utils import secure_filename from werkzeug.exceptions import RequestEntityTooLarge from redis import Redis from rq import Queue from rq.job import Job from rq.command import send_st...
import io import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 import numpy as np from helpers import birdseye from threshold import combined_thresh def hist(image): '''take in a perspective transformed image and draw the histogram based on lane lines found near the bottom''' botto...
#/usr/bin/env python # -*- coding: utf-8 -*- '''from: http://www.dongwm.com/archives/pythonban-ge-ren-jian-li/''' import re import random def color(messages): color = '\x1B[%d;%dm' % (1, random.randint(30, 37)) return '%s %s\x1B[0m' % (color, messages) def len_zh(data): temp = re.findall('[^a-zA-Z0-9....
# Import Flask from flask import Flask, jsonify # Dependencies and Setup import numpy as np import datetime as dt # Python SQL Toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from sqlal...
import os import errno import socket import struct from select import select from .utils import DictWrapper from . import netlink, connector PROC_CN_MCAST_LISTEN = 0x1 PROC_CN_MCAST_IGNORE = 0x2 PROC_EVENT_NONE = 0x00000000 PROC_EVENT_FORK = 0x00000001 PROC_EVENT_EXEC = 0x00000002 PROC_EVENT_UID = 0x00000004 PROC_EV...
from pud.dependencies import * from pud.collector import Collector from pud.envs.simple_navigation_env import plot_walls, set_env_difficulty from pud.utils import set_global_seed, set_env_seed def visualize_trajectory(agent, eval_env, difficulty=0.5): set_env_difficulty(eval_env, difficulty) plt.figure(figsiz...
#!/usr/bin/env python3 # # Copyright 2019-2020 PSB # # 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 ...
""" MESH sub-module of pyhail Contains the single pol MESH retrieval for gridded radar data. Required reflectivity and temperature data <NAME> - 15 June 2018 """ import pyart from pyhail import common import netCDF4 import numpy as np def _get_latlon(radgrid, ref_name): """ Generates lattitude and longitud...
from typing import List import pytest from thinc.api import fix_random_seed, Adam, set_dropout_rate from numpy.testing import assert_array_equal import numpy from spacy.ml.models import build_Tok2Vec_model, MultiHashEmbed, MaxoutWindowEncoder from spacy.ml.models import build_bow_text_classifier, build_simple_cnn_text_...
import discord import asyncio from discord.ext import commands from discord.utils import get from modules.bot_functions import * from modules.chat_effects import * class Market(commands.Cog): """ Commands : - market - buy - sell - remove_offer """ def __init__(self, bot): sel...
import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.datasets import Cityscapes import numpy as np from matplotlib import pyplot as plt from skimage import color from skimage import io from ttictoc ...
import asyncio import gzip import json import socket import sys import threading from collections import OrderedDict, defaultdict from contextlib import contextmanager from queue import Queue from google.protobuf import json_format from sanic import Sanic, response from signalfx.generated_protocol_buffers import signa...
import datetime import json import os from typing import Type from pathlib import Path from experiment_visualization.app import WebApp, WebAppRunner from hypernets.experiment import ABSExpVisExperimentCallback, ActionType, ABSExpVisHyperModelCallback from hypernets.experiment import ExperimentMeta from hypernets.utils...
""" Definition: q - points_probability_matrix sigma - clusters_variance mu - clusters_means """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris def calculate_normal_distribution(point: np.ndarray = 0, clusters_means: np.ndarray = 0, clus...
import datetime from collections import Counter, deque import numpy as np from covid19sim.run import simulate from covid19sim.utils.utils import extract_tracker_data from tests.utils import get_test_conf def print_dict(title, dic, is_sorted=None): if not is_sorted: items = dic.items() else: ...
""" Este arquivo é destinado interação com nosso banco de dados firebase """ import firebase_admin from firebase_admin import credentials from firebase_admin import firestore from watson import criar_sessao import datetime # credenciais e inicialização da base de dados cred = credentials.Certificate('chatone-f8990-fir...
'''A library of Python date functions and terms for use within an ASP program. Some Clorm fields and complex terms are defined as well as functions to use them. Any function that is to be called from within an ASP program will be prefixed with: ``cl_``. .. code-block:: none date(@cl_date_range("...
from os import chdir, makedirs from pathlib import Path from typing import Iterator, Optional, TypedDict, Union import json import sys from loguru import logger from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from yt_dlp.cookies import extract_cookies_from_browser import click import req...
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex import libtbx.load_env import sys from six.moves import range def extend_sys_path(): sys.path.insert(0, libtbx.env.under_build("scitbx/array_family/boost_python")) def exercise_std_vector_conversions(verbose=0)...
#!/usr/bin/python3 import sys import numpy as np import numpysane as nps import os import re from inspect import currentframe Nchecks = 0 NchecksFailed = 0 # no line breaks. Useful for test reporting. Yes, this sets global state, but # we're running a test harness. This is fine np.set_printoptions(linewidth=1e10, su...
# -*- coding:utf-8 -*- from __future__ import unicode_literals import sys,os import tensorflow as tf from transwarpnlp.ner import reader, ner_model, ner_model_bilstm from transwarpnlp.ner.config import LargeConfig pkg_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(pkg_path) train...
# Version 4.0 import sys,splunk.Intersplunk import re import urllib import time """ This script looks for query ids that overlap in time or have time gaps between. max and min. The generated results only make sense for inputs that have a min/max time and a query/search id specified. Currently the follo...
import torch from torch import nn import math from .helpers import _make_divisible from src.utils import register_model, create_model class SELayer(nn.Module): def __init__(self, in_channels, out_channels, reduction=4): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) ...
import os import pickle from dataclasses import dataclass import numpy as np from nltk import word_tokenize from wordcloud import WordCloud import matplotlib.pyplot as plt import text_helpers import collections @dataclass class Corpus(object): word_index_map: np.ndarray document_matrix: np.ndarray invers...
#!/usr/bin/env python3 """ Tool to help with input/output encoding Helpers to run smoothly in unicode-unfriendly environments like output redirect or unusual language settings. In such settings, output to console falls back to ASCII-only. Also open() suddenly fails to interprete non-ASCII characters. Therefore, at ...
import json import os import subprocess import sys import numpy as np import scipy.misc WDIR = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(WDIR, "../../SETTINGS.json")) as f: SETTINGS_JSON = json.load(f) from scipy.ndimage.interpolation import zoom from scipy.ndimage.filters import gaussia...
import torch.nn as nn import torch import torch.nn.functional as F from avalanche.models.simple_mlp import SimpleMLP class DQNModel(nn.Module): def __init__(self): super().__init__() def forward(x: torch.Tensor, task_label=None): raise NotImplementedError() @torch.no_grad() def get_...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ MakeHuman redhat package build script **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** <NAME>, <NAME> **Copyright(c):** MakeH...
#!/usr/bin/env python import sys import os import platform import shutil import subprocess def check_for_executable(exe_name, args=['--version']): try: cmd = [exe_name] cmd.extend(args) subprocess.check_output(cmd) return True except (subprocess.CalledProcessError, IOError): ...
# coding: utf-8 from systemtools.basics import * from datatools.jsonreader import * from datatools.url import * from datatools.csvreader import * from systemtools.basics import * from systemtools.file import * from systemtools.logger import log, logInfo, logWarning, logWarning, logError, Logger from systemtools.locati...
import dork_compose.plugin from compose.cli.docker_client import docker_client class Subnet: """ Represents one subnet and provides useful calculation methods. """ def __init__(self, subnet="", ip=[], cidr=None): """ Create a new subnet either by parsing the ip/cidr notation or settin...
import numpy as np import healpy as hp from .. import coords from .. import pixel def randoms_usphere(size, phi_min=0., phi_max=2*np.pi, theta_min=0., theta_max=np.pi): """ Random points on the unit sphere or more generally across the surface of a sphere. The default will give randoms on the full unit sp...
# Copyright (C) 2007 <NAME> (<EMAIL>) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed ...
# Author: <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 wr...
""" Usage: # Create train data: python generate_tfrecord.py --label=<LABEL> --csv_input=<PATH_TO_ANNOTATIONS_FOLDER>/train_labels.csv --output_path=<PATH_TO_ANNOTATIONS_FOLDER>/train.record # Create test data: python generate_tfrecord.py --label=<LABEL> --csv_input=<PATH_TO_ANNOTATIONS_FOLDER>/test_labels.csv --out...
import math class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '({:.2f}, {:.2f})'.format(self.x, self.y) def distanceTo(self, point): return math.sqrt((self.x - point.x)**2 + (self.y - point.y)**2) class Line: def __...
import math import warnings import chainer import chainer.functions as F import chainer.links as L from tgan2.models.bn.categorical_conditional_batch_normalization \ import CategoricalConditionalBatchNormalization try: from chainermn.links import MultiNodeBatchNormalization except Exception: warnings.war...
# -*- coding: utf-8 -*- """ Created on Sun Mar 31 12:36:04 2019 @author: Chandar_S """ # import the necessary packages import imutils import time import cv2 from keras.preprocessing.image import ImageDataGenerator from keras.models import model_from_json import numpy as np from ReadLines import ReadLines def pyrami...
import inspect, sys, click, json from models.image import Image from descriptors import * from functions import get_commands, bold from log import logger import logging as log @click.group() def cli(): ''' Allows you to call the application features using a shell interface ''' @cli.command('parallels'...
# -*- coding: utf-8 -*- """ Created on 2017/4/14 @author: MG """ # w.wsd("300343.SZ", "div_exdate", "2005-01-01", "2017-04-01", "Days=Alldays") # w.wss("002482.SZ,300343.SZ", "div_recorddate,div_exdate","rptDate=20151231") # w.wss("002482.SZ,300343.SZ", "div_cashbeforetax2,div_cashaftertax2,div_stock2,div_capi...