text
stringlengths
3.07k
22.1k
from adlib27.optimize import optimize from adlib27.elem_function import exp, sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, logistic, log, log2, log10, logb, sqrt from adlib27.autodiff import AutoDiff as AD import numpy as np #initialize the program and ask for variables def getvars(): yeslist = ["y", "Y...
from utils.decorators import timer, debug from utils.task import Task def all_orientations(): orientations = [] for facing in range(6): for rotation in range(4): orientations.append((facing, rotation)) return orientations def transform_position(pos, orientation, rotation): # Cred...
import pytest from django_filters import FilterSet, AllValuesMultipleFilter from django_property_filter import PropertyFilterSet, PropertyAllValuesMultipleFilter from property_filter.models import AllValuesMultipleFilterModel @pytest.mark.parametrize('lookup', PropertyAllValuesMultipleFilter.supported_lookups) def...
import matplotlib.pyplot as plt from scipy.io import wavfile import os from pydub import AudioSegment import pandas as pd import numpy as np import pickle from scipy.signal import spectrogram from python_speech_features import mfcc from mpl_toolkits.axes_grid1 import make_axes_locatable from src import char_map # impo...
import time from base import * from . import trf from . import sampler class Config(trf.Config): def __init__(self, data): super().__init__(data) self.chain_num = 25 self.multiple_try = 4 def __str__(self): s = super().__str__() s = s.replace('trf_IS', 'trf_sa') ...
""" make_allvar_report allvar_periodogram_checkplot allvar_plot_timeseries_vecs plot_rotationcheck """ from glob import glob import os, pickle, shutil, multiprocessing import numpy as np, pandas as pd, matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from numpy import array as...
import wx import sys, platform, time, ast from packages.rmnetwork import netutil import packages.rmnetwork as network from packages.rmnetwork.constants import * from packages.lang.Localizer import * from wx.lib.wordwrap import wordwrap import wx.lib.scrolledpanel as scrolled import wx.lib.masked as masked if platform....
import discord import sys, os import psutil from discord.ext import commands import data.constants as tt # ======================== class admin(commands.Cog): def __init__(self, bot): self.bot = bot # ======================== @commands.command() async def admins(self, ctx): await ctx.trigger_typing() ...
# Copyright (c) 2019 Science and Technology Facilities Council # All rights reserved. # Modifications made as part of the fparser project are distributed # under the following license: # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
#!/usr/bin/env python # # Used to convert elasticsearch queries to fsdb format # # python requirements: # up to date (i.e. pip3 install) elasticsearch # up to date pyOpenSSL # import argparse import sys from elasticsearch import Elasticsearch import json from collections import defaultdict, Mutabl...
import base64 import datetime import hashlib import hmac import json import os import random import re import string import zipfile import six from dateutil.tz import tzlocal from requests import Session from requests.adapters import HTTPAdapter from restle.exceptions import HTTPException from six import text_type im...
from crops.about import __prog__, __description__, __author__, __date__, __version__ import gemmi import os import csv import urllib3 import copy from crops.elements.sequence import Sequence from crops.elements.sequence import guess_type from crops.io.taggers import retrieve_id from crops.elements.intervals import in...
""" .. _l-einsum: Compares implementations of Einsum ================================== This example compares the performance of :func:`numpy.einsum`, :func:`torch.einsum` and its decomposition into standard vector operations for a couple of equations. * :func:`numpy.einsum` * :func:`torch.einsum` * function *einsum...
import datetime import logging import random import re from zoneinfo import ZoneInfo import pytz import requests from telegram import Update import database import rules_of_acquisition import main import git_promotions from ranks import ranks from weather_command import weather_command logger = logging.getLogger(__n...
import argparse import warnings import numpy as np import torch import math from torchvision import transforms import cv2 import os from glob import glob from dectect import AntiSpoofPredict from pfld.pfld import PFLDInference, AuxiliaryNet warnings.filterwarnings('ignore') device = torch.device("cuda" if torch.cuda....
import settings # Import related setting constants from settings.py import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.graph_objs as go import settings import itertools import math import base64 from flask imp...
import sys import getopt import json import requests import collections from requests_oauthlib import OAuth1 from urllib.parse import urljoin url_get_trends_WOEID = "https://api.twitter.com/1.1/trends/available.json" url_get_tends_by_location = "https://api.twitter.com/1.1/trends/place.json?id=" d...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Weather cli - Weather from the command line Basically the script checks your ip, geolocate the ip and checks the weather based on that information, so cool! """ import os import sys import requests from requests.exceptions import ConnectionError import geocoder import ...
import os import re import numpy as np import matplotlib.pyplot as plt from periodictable import elements class Tfactors(object): """ precompute temperature factors for speed """ def __init__(self, T): """ return the Tfactors object. Here, T is temperature in Kelvin """ self.T9 = T/1.e9 ...
# Modifications and additions to code written by brooksandrew import osmnx as ox import networkx as nx import pandas as pd import matplotlib.pyplot as plt import gpxpy from collections import Counter def circuit_path_string_to_int(circuit_rpp): """ Converts nodes in path lists from strings to integers Arg...
import math import numpy as np import functions.optimiser as op # finds the change in tremor output def calc_delta(feature, index_difference=1): past_feature = shift(feature, index_difference) # replaces all zeros with the first non-zero value for i in range(index_difference): past_feature[i] = pa...
import subprocess import os import glob import shutil import sys import optparse import tempfile TMP_OUT = tempfile.mkdtemp() SECRETS = "secrets" DISTINGUISHED_NAME = {"domain": "example.com", "C": "US", "ST": "Maryland", "L": "Baltimore", ...
#!/usr/bin/env python3 import sys import os import argparse import subprocess import json import ssg.build_remediations import ssg.fixes import ssg.rule_yaml import ssg.utils SSG_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) REMEDIATION_LANGS = list(ssg.build_remediations.REMEDIATION_TO_EXT_M...
from typing import Iterable, Iterator, List, Dict, Set, Any, Tuple, Optional import random, math from Helpers.SearchLog import SearchLog, RawSearchLog class SearchLogCollection: logs: List[SearchLog] def __init__(self, logs: List[SearchLog] = []): self.logs = list(logs) def __getitem__(self, index: int)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 7 12:23:43 2018 @author: antony """ import glob import numpy as np import pandas as pd import sys import matplotlib from matplotlib.colors import Normalize import matplotlib.pyplot as plt import matplotlib.transforms as transforms import libplot ...
import numpy as np import random from tqdm import tqdm import math import time # random.seed(1) global connection_info def generate_optimal(n): optimal = [0, 3, 7, 8, 14, 18, 25, 26, 28, 30] state = np.zeros(n) for i in range(n): if i in optimal: state[i] = 1 else: state[i] = 0 return state def reinfor...
from unimodals.common_models import * import torch DATA_PATH = '/home/arav/MultiBench/MultiBench/' def test_id(): """Test Identity module.""" id = Identity() test = torch.Tensor([0]) assert id(test) == test def test_linear(): """Test Linear Module.""" lin = Linear(3,4) test = torch.z...
""" Tests for our physical database """ import unittest import tempfile import datetime from hivemind.util.misc import temp_dir from hivemind.data.abstract.table import _TableLayout from hivemind.data.abstract.field import _Field from hivemind.data.exceptions import IntegrityError from hivemind.data.contrib.sqlite_...
#!/usr/bin/env python3 """ gremlin.py usage: gremlin.py [-h] [-d] config_files [config_files ...] Gremlin finds features sets where a given machine learning model performs poorly. positional arguments: config_files path to configuration file(s) which Gremlin uses to set up the problem and algorith...
# coding=utf-8 # Copyright (c) 2015 EMC 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 # #...
import itertools import functools import collections from enum import Enum from robostat.util import noneflt from robostat.ruleset import Ruleset, ValidationError, cat_score, IntCategory, CategoryRuleset WEIGHTS = { "viiva_punainen": 20, "viiva_palat": 10, "viiva_kippi": 10, "viiva_maki...
""" Install odet first: https://github.com/kun0906/odet """ import os import pickle import pandas as pd from odet.pparser.parser import _pcap2flows, _get_IAT_SIZE, _get_STATS from odet.utils.tool import dump_data, check_path import numpy as np """ Analyze IOT datasets (data-clean.zip: 20GB, 20210714) collecte...
import logging from collections import defaultdict, OrderedDict from functools import reduce from operator import itemgetter as ig from pprint import pformat from typing import Iterable, TypeVar, Callable, List, Any, Dict, Set from future.utils import lmap from itertools import groupby, chain from nose.tools import a...
# -*- coding: utf8 -*- # Copyright 2012 <NAME> <<EMAIL>> # # 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 o...
from typing import Iterable from typing import Optional from typing import Type from typing import Union from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import UserManager from django.core import checks from django.core.exceptions import ValidationError from django.db.models impo...
from prompt_toolkit import print_formatted_text, HTML from prompt_toolkit.styles import Style from prompt_toolkit.validation import Validator from prompt_toolkit import prompt from prompt_toolkit.completion import PathCompleter, WordCompleter, ExecutableCompleter from prompt_toolkit.shortcuts import yes_no_dialog impor...
import json import sys def load_from_file(): try: with open("plugin_options.sav") as fh: str = fh.readline() return json.loads(str) except: return [] def store_to_file(options): with open("plugin_options.sav", "w") as fh: fh.write(json.dumps(options)) def get_index_of_option_in_opti...
# Load required libraries import numpy as np import pandas as pd import os import glob from PIL import Image import pydicom import PIL import imageio import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, LinearSegmentedColormap import seaborn as sns import tqdm import cv2 import png import pyla...
## Copyright (c) 2016-2017 Upstream Research, Inc. All Rights Reserved. ## ## Subject to an 'MIT' License. See LICENSE file in top-level directory ## ## #python-3.x ## python 2 does not work due mostly to issues with csv and io modules with unicode data help_text = ( "CSV-PREPEND tool version 20170918\n" ...
import torch.nn as nn import torchvision import torch, os from skimage import morphology as morph import numpy as np from src.modules.eprop import eprop import torch.utils.model_zoo as model_zoo from scripts.SEAM.network import resnet38_SEAM, resnet38_aff #----------- LC-FCN8 class FCN8VGG16(nn.Module): def __ini...
#! /usr/bin/env python import sys import os import glob import re import fnmatch from dateutil.parser import parse as time_parse from nose.tools import ok_, eq_ def camelize(string): string = re.sub("[^\w\d_]", "_", string) return "".join([s.capitalize() for s in string.split("_")]) def create_dynamic_method...
# coding: utf-8 import webbrowser from operator import itemgetter from .config import feedback, gconfig from .symbol_format import completion_to_suggest from .util import catch, Pretty class ProtocolHandler(object): """Mixin for common behavior of handling ENSIME protocol responses. Actual handler implemen...
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' This is master branch. :) ''' ### Modules Importing ### import os import requests from bs4 import BeautifulSoup import toml import argparse ### Modules Importing ### class Main: ''' Main Opertations Loading configuration files and languages, show the version and...
import re import os import sys import json import scrapy import argparse from glob import glob from datetime import datetime from w3lib.url import is_url from scrapy.crawler import CrawlerProcess from scrapy.utils.project import inside_project, get_project_settings from scrapy.utils.python import to_unicode from scrap...
#!/usr/bin/python3 import requests import webbrowser import pickle5 as pickle import sys import configparser import argparse import json from datetime import datetime, timedelta import feedparser import time import os #Get Pickle data def __init__(): redirect_uri = 'https://github.com/acymbalski/Auto-Pocket.git' ...
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.nn import Module import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset import torchnlp.nn as nlpnn class Net(Module): def __init__(self, config, attention_net=False): super(Net, s...
import json import logging import os import re import tempfile import m3u8 from tqdm import tqdm yuu_log = logging.getLogger('yuu.gyao') class GYAODownloader: def __init__(self, url, session): self.url = url self.session = session self.merge = True if os.name == "nt": ...
# 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...
import collections from typing import Dict, List, Union, Tuple from utils import string_to_letters, EPSILON, concat_regex, add_regex """ 1. REGEX to TG 3. Moore, mealy machine 4. Moore to mealy """ class Node: def __init__(self, name: str, edges: List['Edge'] = (), output=None): self.id = name s...
# Copyright 2017 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <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, ...
import time from kombu import Connection, Queue, Exchange from kombu.common import maybe_declare from kombu.mixins import ConsumerProducerMixin from kombu.pools import producers from spylunking.log.setup_logging import build_colorized_logger from celery_connectors.utils import SUCCESS from celery_connectors.utils impor...
import cx_Oracle try: import configparser except ImportError: import ConfigParser as configparser import logging import threading import time import sys from dbsource import DBSource def open(configuration_file): '''Create an user admin DB connection using settings from a configuration file.''' config = config...
from geoalchemy2 import Geography, Geometry from pytz import timezone from shapely import wkb from sqlalchemy import ( Column, Integer, BigInteger, String, Boolean, DateTime, ForeignKey, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import deferred,...
# -*- coding: utf-8 -*- from flask import Flask, request, render_template, Markup import codecs import json import uuid app = Flask(__name__) @app.route('/') def wordlist(): word_list = open('wordlist.csv', 'r', encoding='utf-8') table = '' for line in word_list: word_id = line.split(';')[0] ...
from typing import List, Set, Union, Tuple, Collection import clingo import networkx as nx from clingo import Control, Symbol from vizlo.types import ASTRuleSet, FlatASTProgram, ASTProgram from vizlo.util import log EMERGENCY_EXIT_COUNTER = 0 def get_all_trues_from_assumption(assumptions: Collection[Tuple[Symbol,...
from __future__ import print_function, unicode_literals from flask import render_template, request, flash, Blueprint from .calcs import dbs_to_excel, recalculate_CO2_from_excel from io import open import os import traceback vindta = Blueprint('vindta', __name__) @vindta.route('/', methods=['GET', 'POST']) def index()...
import boto3 import json import sagemaker from sagemaker import mxnet from sagemaker import get_execution_role import io import random import matplotlib.pyplot as plt import matplotlib.image as mpimg import os from PIL import Image, ImageEnhance # start AWS resources in global context s3 = boto3.resource('s3') s3_cli...
# Copyright (C) 2015-2019 <NAME> <<EMAIL>> # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; # version 2.1 of the License. # This library is distributed in the hope that it will be usefu...
from unittest.mock import Mock, patch, call import pytest from faker import Faker import spotipy as spt from diversify.session import SpotifySession, _get_session, _fields fake = Faker() Faker.seed(0) # I'm using this project as a way to learn how to test functions # and isolate dependencies, so there might be a bunc...
import os.path import subprocess import numpy as np import nibabel as nib import matplotlib matplotlib.use('Agg') import matplotlib.cm as cm import matplotlib.colors import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.axes_grid1 import ImageGrid def run(command, env={}): merge...
#!/usr/bin/env python3 """ Train my neural network Usage: homework4 autoencoder homework4 werk <partitions> <sampling> homework4 test Arguments: autoencoder Run autoencoder werk Perform rap1 learning task with cross-validation test Classify test data and output to ts...
#!/usr/bin/env python3 import sys # add search paths seen from project root folder # (used for vscode test integration) sys.path.insert(0, 'source') sys.path.insert(0, 'tools/ubpf') # add search paths when run from inside test folder # (used when running test directly) sys.path.insert(0, '../source') sys.path.insert(0...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Project: cuckoo_docker @File: sysinit.py.py @Author: XuRuoYu @Describe: @Date: 2021/11/16 10:18 上午 """ # coding:utf-8 import json from configparser import ConfigParser import xml.etree.ElementTree as ET import os import time # 通过基础镜像增量生成各个虚拟机磁盘文件 def generate_vm_d...
#!/usr/bin/env python3 # -*- coding: utf8 # urban_population2osm # Extracts urban settlements with population numbers from SSB and updates OSM. # Produces OSM file ready for additional edits before upload, filename 'tettsted_<year>.osm' # Input CSV on: https://www.ssb.no/en/befolkning/statistikker/beftett. # Usage: ur...
# Modified by Seungjae @ 2021. 07. 31 # Copyright (c) 2020 Huawei Technologies Co., Ltd. # Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https:...
"""NetCDF reader. Pupynere implements a PUre PYthon NEtcdf REader. """ __author__ = "<NAME> <<EMAIL>>" import struct import mmap from numpy import ndarray, zeros, array ABSENT = '\x00' * 8 ZERO = '\x00' * 4 NC_BYTE = '\x00\x00\x00\x01' NC_CHAR = '\x00\x00\x00\x02' NC_SHORT = '\x00\x00\x00\x03' NC_INT = '\x00\x00\...
# by TR from obspy.core import UTCDateTime try: from sito.util import dist2gps except: pass import logging import numpy as np import matplotlib from matplotlib.colors import Normalize from matplotlib import cbook from numpy import ma log = logging.getLogger(__name__) def equi(m, lat, lon, radius, indeg=True...
# -*- coding: utf-8 -*- ''' otsu.fun - Website Api Engine @version: 1.6 @author: PurePeace @time: 2019-12-27 @describe: run this file to serve. ''' from flask import request from flask_restplus import Resource, fields, Api from initial import app import utils, docs, core # app config api = Api(ap...
import io from typing import Any, Callable, Dict, List, Optional, Set import determined as det import determined.keras train_begin = "on_train_begin" train_workload_begin = "on_train_workload_begin" train_batch_begin = "on_train_batch_begin" train_batch_end = "on_train_batch_end" train_workload_end = "on_train_worklo...
import json import re from collections import OrderedDict from datetime import datetime from logzero import logger from .config import DhisConfig, ODKConfig, SmartVAConfig from .exceptions.errors import ( ValidationError, BirthDateParseError, DeathDateParseError, AgeParseError, AgeOutOfBoundsError...
from tempfile import NamedTemporaryFile from typing import IO from fastapi.middleware.cors import CORSMiddleware from bson import ObjectId from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Depends, BackgroundTasks from pybadges import badge from pydantic import BaseModel, validator from keras.models...
""" This file defines a logger object to keep everything. This object is like a dictionary. To use the logger, use from lib.utils.vis_logger import logger and then log any data using logger.update(name0=value, name1=value, ...) Various getters should also be defined here. These are config-dependent objects,...
import ubiops as api from ubiops_cli.utils import set_dict_default from ubiops_cli.constants import ML_MODEL_FILE_NAME_KEY, ML_MODEL_FILE_NAME_VALUE, SYS_DEPLOYMENT_FILE_NAME_KEY, \ SYS_DEPLOYMENT_FILE_NAME_VALUE from ubiops_cli.src.helpers.helpers import strings_to_dict DEPLOYMENT_REQUIRED_FIELDS = ['input_type'...
from collections import defaultdict from datetime import timedelta from time import time import numpy as np from scipy import sparse as sp from menpo.visualize import bytes_str, print_progress from .base import gradient_xy, camera_parameters_update from .hessian import (initialize_hessian_and_JTe, insert_frame_to_H,...
""" ============================================================================ 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.o...
import os import posixpath from itertools import product import pytest from bs4 import BeautifulSoup from yawrap import Yawrap, NavedYawrap, ExternalJs, ExternalCss, EmbedJs, EmbedCss, LinkJs, LinkCss, BODY_BEGIN, \ BODY_END, _sourcer @pytest.fixture def mocked_urlopen(mocker): class MockedUrlopen(object): ...
import torch from torch.autograd import Variable import os import argparse from datetime import datetime from lib.DPRAEdgeNet import DPRAEdgeNet,EdgeNet from lib.segnet import SegNet from lib.pranet import PraNet from utils.utils import EarlyStopping from utils.dataloader import get_loader,test_dataset from utils.uti...
from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django import template import requests import json, os...
__all__ = [ 'GenerateKeys', 'GenerateKeysDeterministic' ] import os from ..base import ComputationStep from ...lookup.factory import KeyServerFactory from ...utils.exceptions import OasisException from ...utils.coverages import SUPPORTED_COVERAGE_TYPES from ...utils.data import get_utctimestamp class Gener...
import array import errno import json import os import random import zipfile from argparse import ArgumentParser from collections import Counter from os.path import dirname, abspath import nltk import six import torch from six.moves.urllib.request import urlretrieve from tqdm import trange, tqdm URL = { 'glove.42...
#!/usr/bin/env python # coding=utf-8 from typing import List, Union, Tuple, Any, Optional import os.path from os.path import join as pjoin from pathlib import Path import hashlib import matplotlib.pyplot as plt from PIL import Image import numpy as np import torch import torchvision.transforms as T plt.rcParams["save...
from .. import surface, rect, video, pixels, render, rwops from .color import convert_to_color from .common import SDLError from .compat import isiterable from .ebs import System from .image import load_image from .renderer import Renderer from .sprite import Sprite, SoftwareSprite, TextureSprite from .window import W...
''' Start of :code:`matrix_functions` module documentation >>> from sympy import * >>> from commons import * >>> from sequences import * >>> from matrix_functions import * ''' import collections from contextlib import contextmanager from functools import lru_cache from sympy import * from sym...
import os import sys import cv2 import numpy as np DRONE_IMAGE_SIZE = (5300, 7950) CASE1_CONFIG = ["./images/CASE_1", "drone7.JPG", 800, 600, 4096, 4096] CASE2_CONFIG = ["./images/CASE_2", "drone10.JPG", 409, 1200, 4096, 4096] CASE3_CONFIG = ["./images/CASE_3", "drone8.JPG", 700, 200, 4096, 4096] CASE4_CONFIG = ["./i...
#!/usr/bin/env python 2.x import socketserver, socket import threading from os.path import exists, isfile from time import sleep, strftime, time, localtime import signal from aes import myAES from os import system, fork, kill from sys import argv from random import shuffle, randrange HOST = '' PORT = 10007 aes = myAE...
# Author: <NAME> # Time: 2020-5-21 import numpy as np import cv2 as cv from PIL import Image import random import math def imwrite(image, filename): """cv无法读取中文字符 (CV cannot read Chinese characters)""" retval, arr = cv.imencode('.' + filename.rsplit('.', 1)[1], image) # retval: 是否保存成功 if retval is True:...
# This file is part of pex_config. # # Developed for the LSST Data Management System. # This product includes software developed by the LSST Project # (http://www.lsst.org). # See the COPYRIGHT file at the top-level directory of this distribution # for details of code ownership. # # This software is dual licensed under...
from __future__ import absolute_import import time import glob import os.path as osp import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.optim import lr_scheduler import models from util.losses import CrossEntropyLoss, DeepSupervisi...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
import pandas as pd import numpy as np import logging import swifter import click import gzip import json import os from functools import partial, reduce from src.models import ndcg_score from collections import Counter from datetime import datetime def predict_simple(row:pd.Series, cols_domain:list, ...
import os import re from pathlib import Path import music_tag from telegram import ReplyKeyboardMarkup from telegram.ext import CallbackContext from models.admin import Admin from models.user import User from utils.lang import keys def translate_key_to(key: str, destination_lang: str) -> str: """Find the specif...
import numpy import theano import theano.tensor as T numpy.set_printoptions(linewidth=230, threshold=10000, edgeitems=18) from codec import Codec from visualize_weights import VisualizeWeights class RBM: def __init__(self, num_visible, num_hidden, minibatch_size, venabledp=1, henabledp=1): ...
""" Test tasks """ from os import listdir from os.path import isfile, join from unittest.mock import patch, Mock import boto3 import pytest from moto import mock_s3 from course_catalog.models import Course, CoursePrice, CourseInstructor, CourseTopic from course_catalog.tasks import get_edx_data, get_ocw_data pytest...
# Reproduction from Payan and Montana import torch import torch.nn as nn import torch.nn.functional as F from os import path import os import numpy as np import pandas as pd from copy import copy, deepcopy class LargeAutoEncoder(nn.Module): """ Sparse Autoencoder for transfer learning """ def __init...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Audio Spectrum analyser v0.7.0 - summed given fft in n bands, but re normalized between 0 - 70? - Peaks L and R - amplitude for given target frequency and PEAK frequency - "music note" to given frequency - Real FFT, Imaginary FFT, Real + imaginary FFT - threshold detec...
#!/usr/bin/env python3 import xml.etree.ElementTree as ET from PIL import Image # -- Tileset ------------------------------------------------------------- tsx=ET.parse('tiles_bg.tsx').getroot() # export terrains terrains = [elt.get('name') for elt in tsx.findall('terraintypes/terrain')] tile2terrain = { int(e.get(...
import gym, torch, random, copy import torch.nn as nn import torch.optim as optim import numpy as np import torch.nn.functional as F import neptune.new as neptune # initialize policy & value network class PolicyNetwork(nn.Module): def __init__(self, beta): super().__init__() self.model = nn.Sequen...
import re import copy import numpy as np import lmfit from .noise import NoiseModel from .population import Population from .. import definitions as xrsdefs from ..tools import compute_chi2 from ..tools.profiler import profile_keys, profile_pattern # TODO: when params, settings, etc are changed, # ensure all attr...
import os import math import scipy.stats import random prec = 56 total = 128 def mul(a, b): z = int(a * (1 << prec)) * int(b * (1 << prec)) return z >> prec def div(a, b): a = int(a * (1 << prec)) b = int(b * (1 << prec)) z = (a * (1 << prec)) // b return z def fixed(x): return int(x *...
import os import sys import copy import tensorflow as tf import tensorflow_addons as tfa import tqdm import numpy as np import sklearn from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from notmad.baselines import NOTEARS, ClusteredNOTEARS from notmad.notmad import NOTMAD from ...