text
stringlengths
3.07k
12.6k
#!/usr/bin/python import numpy as np from numpy import dot, random import matplotlib.pyplot as plt import time from scipy.io import loadmat def softmax(x): exps = np.nan_to_num(np.exp(x)) return exps/np.nan_to_num(np.sum(exps)) class classifier(object): def __init__(self, input_size, classes, debug=True)...
# -*- coding: utf-8 -*- from opensextant.TaxCat import Taxon, get_taxnode, TaxCatalogBuilder, get_starting_id import json catalog = "WFB" # WFB = World FactBook min_len = 4 min_len_acronym = 3 def evaluate_text(txn, stop): """ Consolidate evaluations of text if it is valid to tag or not. :param txn: Ta...
import tensorflow as tf from collections import namedtuple from abc import abstractmethod class PreprocessedData(namedtuple("PreprocessedData", ["key", "waveform", "waveform_length", "speaker_id", "age", "gender"])): pass class SourceData(name...
"""Event tracing.""" import json import logging import time import datetime import requests from marshmallow import fields from ..transport.inbound.message import InboundMessage from ..transport.outbound.message import OutboundMessage from ..messaging.agent_message import AgentMessage from ..messaging.decorators.tra...
""" Author: <NAME> Date: August, 2019 """ import sys, os, time sys.path.insert(0, "/export/guanghan/CenterNet-Gluon/dataset") sys.path.insert(0, "/Users/guanghan.ning/Desktop/dev/CenterNet-Gluon/dataset") import mxnet as mx from mxnet import nd, gluon, init, autograd from gluoncv.data.batchify import Tuple, Stack, P...
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved. """Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from mock import patch, MagicMock from resilient_circuits.util import get_function_definition from resilient_circuits import SubmitTestFunct...
# Copyright 2015 The TensorFlow 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 applica...
import zlib # from sympy import * mod = 1000000007 # p0, pl, ph, ps = symbols('p0 pl ph ps', integer=True) # f3a57af828f277d9cab8453e4d4778b33d4f5906 refs/remotes/origin/example root = '7c7837741bc79e997484dc56709ef07397d1ee60' # 5b99b65eafacf910586dd1f50483fd2147f9988d refs/remotes/origin/easy # root = '3636ca1b8b...
# Copyright 2021, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
# Generate attribution results # from utils.loading import load from utils.reading import read import os import numpy as np import cv2 from utils.utils_network import InceptionV1 from utils.attr_computing import compute_attr, compute_deepliftreveal from utils.utils_activation_maps import create_root_dir, print_result...
# Copyright 2016 The BigDL Authors. # # 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...
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
""" Copyright 2019 Samsung SDS 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 ...
from .enums import GameMode, Mod import lzma, struct, datetime class ReplayEvent(object): def __init__(self, time_since_previous_action, x, y, keys_pressed): self.time_since_previous_action = time_since_previous_action self.x = x self.y = y self.keys_pressed = keys_pressed...
""" 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 """ class Tests: creation_undo = ( "UNDO Entity creation success", "UNDO Entity creation failed...
from __future__ import absolute_import from __future__ import print_function import os import scipy import scipy.signal import numpy as np import scipy.io.wavfile def waveReadAsFloat(wavFileIn): """ sr, wavData = wavReadToFloat(wavFileIn) Wrapper over scipy.io.wavfile Return: sr: sampling_rate ...
# encoding: utf-8 """Gherkin step implementations for presentation-level features.""" import os import zipfile from behave import given, when, then from pptx import Presentation from pptx.compat import BytesIO from pptx.opc.constants import RELATIONSHIP_TYPE as RT from pptx.util import Inches from helpers import s...
import os import os.path import math import threading import torch import torch.utils.data import numpy as np import librosa as lr import bisect from torch.utils.data import Dataset class AudioDataset(Dataset): def __init__(self, filename, len_sample): """ filename: Path to .pt file containing the ...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ...
from functools import lru_cache from os.path import commonprefix import pathlib from .dataset import SeriesData, hash_obj from .dataset import SingleData # noqa:F401 (user convenience) from .series_hdf5_hyperspy import SeriesHdf5HyperSpy from .series_hdf5_qpimage import SeriesHdf5Qpimage, SeriesHdf5QpimageSubjoined f...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Main module.""" import argparse import csv import json import logging import os import sys import tkinter as tk from pathlib import Path from tkinter import filedialog from typing import Optional, IO, Union # from tkinter import messagebox try: # If we're not instal...
from datetime import datetime from io import BytesIO import zipfile from django.db.models import Q from django.http.response import HttpResponse from rest_framework import status from rest_framework.response import Response from rest_framework import viewsets, permissions from rest_framework.views import APIView from...
# -*- coding: utf-8 -*- # # Copyright 2020 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...
# Copyright (c) Microsoft Corporation. All rights reserved. # # MIT License # # 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 u...
import requests import ast import logging import argparse from pandas import DataFrame from bs4 import BeautifulSoup from datetime import datetime from multiprocessing.pool import ThreadPool logging.basicConfig(level=logging.INFO) PAGE_OFFSET_INTERVAL = 30 BASE_URL = "https://www.tripadvisor.com" N_THREADS = 8 # Dep...
""" Dveloper: <NAME> E-mail: <EMAIL> Github: https://github.com/vujadeyoon Date: May 31, 2020. Title: vujade_videocv.py Version: 0.1 Description: Video processing with computer vision module """ import numpy as np import math import cv2 import ffmpeg class VideoReaderFFmpeg: def __init__(self, _path_video, _ch...
import os import sys import numpy as np import math # add path to sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) UTILS_DIR = os.path.dirname(os.path.abspath('src/utils')) sys.path.append(BASE_DIR) sys.path.append(UTILS_DIR) from utils import * # function to write predictions and ground-truth to file in KI...
import itertools import json from zope.globalrequest import getRequest from zope.interface import implements from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces import NotFound from interfaces import IComparator, IComparators _u = lambda v: v if isinstance(v, unicode) else...
from django.http import JsonResponse from django.views.generic import View from django.contrib.auth.hashers import check_password from user.models import User, Notification from user.verify import verify_register, verify_login, verify_edit, verify_change_password, verify_post_notification from utils.auth import gene...
import rasterio import geopandas as gpd from geopy.geocoders import Nominatim import shapely from shapely.geometry import Polygon, Point from shapely.ops import cascaded_union import numpy as np import pickle import os def city_folder_creator(cities, adresses): for city in cities: os.mkdir(f'{city}') ...
from Tkinter import * from math import * from helper_function import * WIDTH = 120 HEIGHT = 60 PRIMITIVE = "CUBE" # Chooose between CUBE and PYRIMID SCALE = 1 # Scale the primitive ########################## Below is the helper functions, nothing needs to be changed ########################## camera_pos = [ 0,0,-5 ]...
import asyncio import base64 import logging import pprint import urllib.parse from xml.etree import ElementTree ROOT_DESC_PATH = "/root_desc.xml" ICON_PATH = "/icon.png" ROOT_DESC_TEMPLATE = """ <?xml version="1.0" encoding="utf-8"?> <root xmlns="urn:schemas-upnp-org:device-1-0"> <specVersion> <major>1</m...
from collections import defaultdict from sqlalchemy.orm import load_only from ichnaea.constants import ( PERMANENT_BLACKLIST_THRESHOLD, TEMPORARY_BLACKLIST_DURATION, ) from ichnaea.data.base import DataTask from ichnaea.models import ( Cell, CellBlacklist, CellObservation, Score, ScoreKey,...
from bitarray import bitarray from Visualizer import display_board from lookup_tables.RayTables import RAY_TABLE,RAY_TABLE_CAPPED from lookup_tables.MagicNumberGeneration import get_permutations,magic_multiply import random with open("MagicNumbers.txt", "r") as f: MAGIC_NUMBERS = [] for line in f: # read rest ...
import torch as t import torch.nn as nn from torchvision.ops import misc as misc_nn_ops from torchvision.models.mobilenetv2 import ConvBNReLU from collections import OrderedDict from .utils import register_layers class CNN_constructer(nn.Sequential): def __init__(self, networklist, upsample_mode='bilinear', outp...
########################################################################## # # Copyright (c) 2018, Image Engine Design 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: # # * Redistrib...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ## # @file ga-based_image_mapping.py # @author <NAME> (<NAME> <<EMAIL>> # @date 2018-06-06 # # @brief Prototype GA-based mapping of unstructured data to 2-D images. # # @remarks The results will be published in a paper submitted to the <a # href="...
"""Commands for generating DFT input files. Not intended to be called from places besides control_script.py.""" import numpy as np import os from amlt import reasonable_random_structure_maker, PolymorphD3, try_mkdir from ase import io from os.path import isfile def convert_to_traj(filename, traj_name= 'images.traj')...
# -*- coding: utf-8 -*- """ @author: Turnphy """ import numpy as np from matplotlib import pyplot as plt from tkinter import * from tkinter import filedialog from PIL import ImageTk import PIL from scipy.fftpack import fft from scipy import interpolate from detect_peaks_py import detect_peaks # from tkinte...
# -*- coding: utf-8 -*- """ @created on: 11/24/19, @author: <NAME>, @version: v0.0.1 @system name: badgod Description: ..todo:: """ import torch.nn as nn import torch.nn.functional as F import math import torch from torch import tensor import cv2 import numpy as np class SmallConvNet(nn.Module): def __init__(s...
# 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...
__author__ = "<NAME>" __version__ = "1.1" __date__ = "12-10-2021" # bot.py import os import discord from neural_network import * import json import random from dotenv import load_dotenv models = {} jsons = {} class AverageUser(discord.Client): async def on_ready(self): #When booting up print(f'{...
#!/usr/bin/python #hengfengzhang #20210721 #all right reserved import os import sys import re import argparse import shutil def get_parse(): parser = argparse.ArgumentParser(description='Flating the input filelist with specified macro') parser.add_argument('-f', '--file' , metavar='vlogfile.f', nargs='+', defaul...
"""Helpers that help with state related things.""" import asyncio import datetime as dt import json import logging from collections import defaultdict from types import TracebackType from typing import ( # noqa: F401 pylint: disable=unused-import Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union) from...
import numpy as np import torch, os from MiniImagenet_cross_val import MiniImagenet # from MiniImagenet2 import MiniImagenet2 import scipy.stats from torch.utils.data import DataLoader from torch.optim import lr_scheduler import random, sys, pickle import argparse import pandas as pd from meta import Met...
#!/usr/bin/env python # coding: utf-8 # # usage: python cccc2csv.py """ cccc.exeコマンドを使って、メトリクス集計されたデータを、より見やすいCSVファイル化する。 CSVファイル化すれば、Excelで簡単に見れる理屈。 ccccについては、以下を参照。 - SourceForge.net: C and C++ Code Counter http://sourceforge.net/projects/cccc - UNIXの部屋 検索:cccc (*BSD/Linux/Solaris) ...
import json import datetime import dateutil import dateutil.parser from django.db import models #from tutorial.quickstart.models import UserData from tutorial.quickstart.fly_me import find_airport_query, flight_search_query, flight_search_query, gql_request, token import tutorial.quickstart.aa_flight from tutorial.qui...
#!/usr/bin/env python3 ############################################################################# # Copyright (C) 2014-2016 OpenEye Scientific Software, Inc. ############################################################################# # Converting CSV or SDF files into EXCEL ########################################...
# Copyright 2020 Superb AI, 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 writi...
import sys import pygame import random import time pygame.init() SIZE = width, height = 700, 500 BLOCKSIZE = 10 BLACK = pygame.Color(0, 0, 0) WHITE = pygame.Color(255, 255, 255) RED = pygame.Color(255, 0, 0) GREEN = pygame.Color(0, 255, 0) CLOCK = pygame.time.Clock() difficulty = 20 velocity = BLOCKSIZE score = 0...
from __future__ import print_function, division import numpy as np import numpy.random as npr import dynet as dy import time import sys import os.path sys.path.append(os.path.abspath(os.path.realpath(__file__) + '/../../util/')) import options import data # Retrieve command line options opt = options.rnn_parser().pars...
# Copyright 2013 New Dream Network, LLC (DreamHost) # # 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...
import sys, os import struct import json import numpy as np import torch import math import scipy import scipy.ndimage import torchvision.transforms.functional as TF def generate_icosahedron(): t = (1.0 + math.sqrt(5.0)) / 2.0 # Vertices num_vertices = 12 vertices = np.zeros((num_vertices, 3), dtype...
import math import numpy as np from enum import Enum from terran import default_device from terran.checkpoint import get_class_for_checkpoint TASK_NAME = 'pose-estimation' class Keypoint(Enum): NOSE = 0 NECK = 1 R_SHOULDER = 2 R_ELBOW = 3 R_HAND = 4 L_SHOULDER = 5 L_ELBOW = 6 L_H...
"""Chalice app and routing code.""" import re import base64 # Implementation note: This file is intended to be a standalone file # that gets copied into the lambda deployment package. It has no dependencies # on other parts of chalice so it can stay small and lightweight, with minimal # startup overhead. _PARAMS =...
#!/usr/bin/env python3 import os import setuptools import subprocess import sys from setuptools.command.build_ext import build_ext from setuptools.command.install import install from setuptools.command.sdist import sdist from setuptools.extension import Extension curr_dir = os.path.dirname(os.path.realpath(__file__)...
from os import environ import telebot from flask import Flask, request import config import replies from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, BaseFilter, RegexHandler, ConversationHandler, CallbackQueryHandler from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboard...
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Development System # All trademark and other rights reserved by their respective owners # Copyright 2008-2021 Neongecko.com Inc. # BSD-3 # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fo...
import telebot from telebot import types from Messages import * from dataEgine import * access_token = '<KEY>' bot = telebot.TeleBot(access_token) def inline_menu(): """ Create inline menu for new chat :return: InlineKeyboardMarkup """ callback = types.InlineKeyboardButton(text='\U00002709 New ...
from reversi import * import random import numpy as np import math from copy import deepcopy invalidMove = (-1, -1) structure = [n * n, 2 * n * n, 2 * n * n, n * n] population = 50 bestNetworksPopulation = 5 previousGeneration = 1271 mutationAmount = 0.05 # sigmoid function def sigmoid(x): return...
""" Trains a simple DNN on the MNIST dataset using the TensorFlow Estimator API. """ import logging import os import tarfile import requests from typing import Callable, Dict, List, Tuple import tensorflow as tf from determined.estimator import EstimatorTrial, EstimatorTrialContext, ServingInputReceiverFn MNIST_TF_...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # OS: GNU/Linux, Author: <NAME>. ''' Unpacking the "Grammatical dictionary" by <NAME> from .zip archive, converting it to the format of exception dictionary and combining it with the current exception dictionary. Zaliznyak's dictionary is taken from http://odict.ru/. ''' im...
#!/usr/bin/env python """Analyze the quality of recommendations.""" # core modules import math import click import implicit import pandas as pd import progressbar # 3rd party modules from sklearn.base import BaseEstimator from sklearn.model_selection import train_test_split def load_data(rating_filepath="ratings.c...
#!/usr/bin/env python3 # Copyright (c) 2021, <NAME> # # SPDX-License-Identifier: MIT import git from git import Repo import io import os import requests import types import pytest import problem from problem import Problem from problem import Difficulty repo = Repo() assert(repo.bare == False) git = repo.git init...
# Copyright 2009-2017 <NAME>. # This program is distributed under the MIT license. ''' This module defines decorators that modify context managers. See their documentation for more information. ''' import string import random from python_toolbox import caching from .context_manager import ContextManager def as_...
from collections import namedtuple import sqlite3 import random import os import pathlib import shutil from flask.ext.script import Manager, prompt_bool from flask import Flask import dateutil.parser import time import simple from simple import bing_images DEFAULT_APP = Flask("simple") try: from simple.app imp...
import pandas as pd import numpy as np import requests from datetime import datetime import time import os from bitdotio_pandas import BitDotIOPandas from config import CONFIG, LOGO, INSTRUCTIONS from queries import get_status_sql, get_leaderboard_sql, get_batch_sql, get_update_sql def get_prompt(num_labels, df): ...
import time import datetime import utilities as ut def time_stats(df, show_month_stat, show_day_stat, months_list, days_list): """ Displays statistics on the most frequent times of travel. Args: (dataframe) df - Panda dataframe with bikeshare data (boolean) show_month_stat - show or not s...
import os import csv import requests import logging import pandas as pd from time import time from bs4 import BeautifulSoup from datetime import datetime from typing import List, Dict from sqlalchemy import create_engine import warnings warnings.filterwarnings("ignore") logging.basicConfig(filename='pipeline.log', le...
load(":target_recipes.bzl", "TARGET_RECIPES") load(":repository_locations.bzl", "REPO_LOCATIONS") def _repository_impl(ctxt): # Setup the build directory with links to the relevant files. ctxt.symlink(Label("//bazel:repositories.sh"), "repositories.sh") ctxt.symlink(Label("//ci/build_container:build_and_in...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, <NAME> <<EMAIL>> # Based on homebrew (<NAME> <<EMAIL>>) # # This file is part of Ansible # # Ansible 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, eithe...
import json import logging import requests from blog.models import Entry, Tag, Photo from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse from django.urls import reverse from django.utils.text import slugify from django.utils.timezone import now from django.views ...
'''Define basic blocks ''' import torch from torch import nn from torchmeta.modules import (MetaModule, MetaSequential) # from torchmeta.modules.utils import get_subdict import numpy as np from collections import OrderedDict import math import torch.nn.functional as F '''Adapted from the SIREN repository https://gith...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 1 18:05:49 2019 @author: <EMAIL> molecular physchemical properties """ from rdkit import Chem from rdkit.Chem import QED from rdkit.Chem import Crippen from rdkit.Chem import MolSurf from rdkit.Chem import Descriptors from rd...
from backend import db from backend.models.dtos.team_dto import ( TeamDTO, NewTeamDTO, TeamMembersDTO, TeamProjectDTO, ) from backend.models.dtos.organisation_dto import OrganisationTeamsDTO from backend.models.postgis.organisation import Organisation from backend.models.postgis.statuses import ( Te...
# (c) Copyright 2017-2018 OLX from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import OrderedDict import sys import yaml from var_types import VarEntity try: from io import StringIO except ImportE...
import dolfin as df import mshr from pulse.geometry_utils import generate_fibers from geometry import Microstructure, Geometry, MarkerFunctions comm = df.MPI.comm_world # get mesh from Gmsh mesh = df.Mesh() fmesh = df.XDMFFile(comm, "./biv_meshes/biv20k.xdmf") fmesh.read(mesh) fmesh.close() base_x = 0.0 # LV cent...
import json import os from cirrocumulus.abstract_db import AbstractDB from cirrocumulus.envir import * from cirrocumulus.io_util import unique_id def create_dataset_meta(path): result = {'id': path, 'url': path, 'name': os.path.splitext(os.path.basename(path))[0], 'description': ''} if os.path.basename(path)...
#!/usr/bin/env python3 import numpy as np import logging, io, os, subprocess, json, multiprocessing SM2_PATH = './csm/sm2' MIN_READING = 0.02 MAX_READING = 50 TRH = 1000 def get_lines(scans, odometry, indexes, fov): for scan, pose, index in zip(scans, odometry, indexes): data = {} theta = np.radi...
from announcements import Announcement from more_tools import BidirectionalMap message_templates = { 'stocks': '@{user_name} Minigame basic commands: !autoinvest, !introduction, !buy, !companies, !all commands, !my stats', 'stocks_alias': 'stocks', 'company_alias': 'company', 'buy_successful': "@{user_...
# -*- coding: utf-8 -*- # Copyright 2012 Fanficdownloader team, 2018 FanFicFare team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
from simtk.openmm import Vec3 from simtk.unit import nanometer from simtk.openmm.app import element from copy import deepcopy import numpy as np import itertools class MaxMonIterExceedError(Exception): """Base class for exceptions in this module.""" pass class MaxPolyIterExceedError(Exception): """Base c...
from sympy import (symbols, MatrixSymbol, Matrix, IndexedBase, Idx, Range, Tuple, sin) from sympy.core.relational import Relational from sympy.utilities.pytest import raises from sympy.codegen.ast import (Assignment, aug_assign, CodeBlock, For, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssig...
import os import sys import hashlib import marshal import builtins from xonsh.lazyasd import lazyobject def _splitpath(path, sofar=[]): folder, path = os.path.split(path) if path == "": return sofar[::-1] elif folder == "": return (sofar + [path])[::-1] else: return _splitpath...
# -*- coding: utf-8 -*- """ Created on Thu Apr 29 15:33:38 2021 @author: Jeonghan """ import torch from torch import nn, optim from torch.utils.data import DataLoader import tqdm from torchvision.datasets import ImageFolder from torchvision import transforms device = torch.device("cuda" if torch.cuda.is_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unit tests for package.""" import unittest from glob import glob from pmix.borrow import borrow as borrow_api, cli_parser as borrow_parser from argparse_to_web import ArgparseToWeb # from argparse_to_web.argparse_to_web import create_app from test.config import TEST_...
# -*- coding: utf-8 -*- """ Copyright (c) 2019 <NAME> MIT License 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...
""" Helper functions to make fpdf2 Templates more useful """ __author__ = "<NAME> <<EMAIL>>" __copyright__ = "Copyright (C) 2021 <NAME>" __license__ = "MIT" from collections.abc import Sequence from typing import Union, Tuple, Iterator from fpdf.fpdf import get_page_format from .helpers import convert_unit class ...
import cv2 import numpy as np from keras import backend as K from losses import ActivationMaximization from optimizer import Optimizer from regularizers import TotalVariation, LPNorm from utils import utils def _get_num_filters(layer): """ Returns: Total number of filters within this layer """ # For ...
#!/usr/bin/env python3 # # This file is part of LiteX. # # Copyright (c) 2014-2019 <NAME> <<EMAIL>> # Copyright (c) 2013-2014 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause import os import argparse import importlib from migen import * from litex.build.io import CRG from litex.soc.integration.soc_core im...
import copy class Board: __slots__ = ["columns", "rows", "positions"] def __init__(self, columns, rows): self.columns = columns self.rows = rows self.positions = {} def free(self, position, new_piece): if position in self.positions: return False for oc...
#!/usr/bin/python3 """Script to train a single-layer perceptron network to learn the AND function""" class Neuron(object): """A Neuron object. It contains inputs, weights and an activation function""" def __init__(self, inp_lis, w_lis, thresh): """Constructor""" self.y = 0 self.out =...
import numpy as np from indicator.oscillator import Atr, Macd, Rsi, Stochastic, Obv from indicator.trend import BollingerBands, Adx, Slope from utils.utils import compute_sign_changement def atr_features(candles): atr = Atr(candles, 'close') for avg_type in ['ma', 'ewm', 'wws']: candles.loc[:, f'atr_7_...
import jsonpickle import os from datetime import datetime os.system("chcp 65001>nul") # avoids GBK codec error when reading JSON print(datetime.now()) #course_data_utm_20205 course_data_stg_artsci_20205 with open("course_data_stg_artsci_20205", "r") as f: all_crs = jsonpickle.loads(f.read()) """ # Filter course...
import argparse import numpy as np import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf import keras import keras.backend as K from keras.models import load_model from keras.layers import Convolution2D, GlobalAveragePooling2D, Dense from rme.utils import config_gpu, load_meta import rme.data...
# # Copyright (c) 2011 OpenStack Foundation # 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 # # Unles...
# -*- encoding: utf-8 -*- """ @File : schema_tools.py @Time : 2020/4/7 20:48 @Author : chise @Email : <EMAIL> @Software: PyCharm @info : """ from datetime import datetime, date from typing import List from pydantic import BaseModel, Field from sqlalchemy import Integer, Boolean, String, Float, DateTime, Tex...
""" function to read data from dwd server """ from itertools import zip_longest, groupby from pathlib import Path from typing import List, Tuple, Optional, Union import re from io import BytesIO import pandas as pd from python_dwd.additionals.functions import retrieve_parameter_from_filename, retrieve_period_type_from...
"""Real-world robot pushing problems: push4 and push8. push4 is the "4-D ACTION" problem from [1]_, a four-dimensional robot pushing task in which a robot has to push and object to an unknown target and receives feedback, after completing its task, in the form of the distance from the pushed object to the target. The ...
import os import time import configparser as cp import run_nets as r from absl import flags from absl import app FLAGS = flags.FLAGS #name of flag | default | explanation flags.DEFINE_string("arch_config","./configs/scale.cfg","file where we are getting our architecture from") flags.DEFINE_string("network","./topologi...