content
stringlengths
5
1.05M
import numpy N, M = map(int, input().split()) A = numpy.array([input().split() for _ in range(N)], int) print(numpy.prod(numpy.sum(A, axis=0), axis=0))
import typemap_delete r = typemap_delete.Rect(123) if r.val != 123: raise RuntimeError
from .TagContainer import TagContainer from collections import deque # Will only be one for a template. Will be the top level parent of all tags. # Only there to hold the top level children. class RootTag(TagContainer): tag = None def __init__(self, tagchar, template): self._tagchar = tagchar self._te...
#!/usr/bin/python import sys fact = lambda n: float(reduce(int.__mul__, range(1, n+1)) if n else 1) pow_xc = lambda c, n: Polinome(*[c**(n-i)*fact(n)/fact(i)/fact(n-i) for i in range(n+1)]) # (x+c)**n extend = lambda L1, L2: map(lambda a, b: (0. if a is None else a, 0. if b is None else b), L1, L2) class Polinome:...
#!/usr/bin/env python # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 import sys, time, collections, csv from subprocess import call, Popen, PIPE def exec_no_fail(seq): p = Popen(seq, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() if p.returncode != 0: print 'err: ...
from pycnic.core import Handler, WSGI from pycnic.utils import requires_validation def has_proper_name(data): if 'name' not in data or data['name'] != 'root': raise ValueError('Expected \'root\' as name') class NameHandler(Handler): @requires_validation(has_proper_name) def post(self): ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Fecapi Decoders # Generated: Mon Dec 17 16:34:10 2018 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platfo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `sqlf` package.""" # import pytest import sqlf ############################################################################### # Data Serialisation UDFs ############################################################################### def test_cbor_map(): ...
import pytest from mock import MagicMock from airflow_monitor.data_fetcher import DbFetcher, decorate_fetcher def test_db_fetcher_retries(): class TestException(Exception): pass db_fetcher = MagicMock(spec=DbFetcher) func_mock = MagicMock( side_effect=TestException(), __name__="get_airf...
''' Style Transfer Network - Main network, which combines all rest ''' import tensorflow as tf # from utils import * from functions import * from encoder import Encoder from decoder import Decoder from samod import SAMod class STNet: def __init__(self, encoder_weights_path): self.encoder = Encoder(enco...
from django.urls import path from .views import firstPage, site_redirection urlpatterns = [ path('', firstPage, name='first_page'), path('link/<slug:slug>/', site_redirection, name='site_redirection'), ]
# # PySNMP MIB module WWP-LEOS-PING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PING-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:38:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
#!/usr/bin/env python from distutils.util import strtobool from time import sleep import configargparse from github3 import login from github3.exceptions import NotFoundError, GitHubException def toggle_enforce_admin(options): access_token, owner, repo_name, branch_name, retries, github_repository = options.acce...
import os token = os.getenv("TELEGRAM_BOT_TOKEN", '') forum = { 'login': os.getenv('FORUM_LOGIN', ''), 'password': os.getenv('FORUM_PASSWORD', '') }
def solution(array, commands): answer = [] for i in commands: answer.append(sorted(array[i[0]-1:i[1]])[i[2]-1]) return answer
import statistics data = [9, 12, 6, 10, 9, 5, 8, 7, 13, 11] mode = statistics.mode(data) print(mode)
from solution import get_file_info from glob import glob import os.path import shutil from pathlib import Path def test_nothing(tmp_path): d = tmp_path / 'sub' d.mkdir() assert len(list(d.iterdir())) == 0 assert get_file_info(d) == [] def test_three_good_files(tmp_path): d = tmp_path / 'sub' ...
import numpy as np import cv2 import matplotlib.pyplot as plt # read the input image img = cv2.imread("city.jpg") # convert from BGR to RGB so we can plot using matplotlib img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # disable x & y axis plt.axis('off') # show the image plt.imshow(img) plt.show() # get 20...
import os import unittest from click.testing import CliRunner from changelog.commands import cli class CliIntegrationTestCase(unittest.TestCase): def setUp(self): self.runner = CliRunner() os.environ.setdefault('LC_ALL', 'en_US.utf-8') os.environ.setdefault('LANG', 'en_US.utf-8') de...
#!/usr/bin/python #coding=utf-8 #@+leo-ver=5-thin #@+node:bob.20180206123613.1: * @file ../plugins/leo_babel/tests/idle_time.py #@@first #@@first #@@language python #@@tabwidth -4 #@+<< imports >> #@+node:bob.20180206123613.2: ** << imports >> import os import time # import traceback from leo.core import leoGlobals a...
# coding=utf-8 """ Copyright 2012 Ali Ok (aliokATapacheDOTorg) 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 ...
import json from unittest.mock import call import pytest from flask_restalchemy import Api from flask_restalchemy.decorators.request_hooks import before_request, after_request from flask_restalchemy.tests.sample_model import Employee, Company, Address @pytest.fixture def sample_api(flask_app): return Api(flask_...
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. '''Defines various tools for manipulating sequences.''' import collections import numbers import types import itertools import random from combi._python_toolbox import math_tools from combi._python_toolbox import caching from comb...
if __name__ == '__main__': N = int(input('Enter N: ')) tokens = [] print('Enter (token no, id): ') for i in range(0, N): token = input() token = token.lstrip('(') token = token.rstrip(')') token = token.replace(' ', '') token = token.split(',') tokens.app...
import io import base64 import json import os import requests from PIL import Image HOST = "http://127.0.0.1:5000" INPUT_IMAGE_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "images/input.jpg" ) INPUT_TXT_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "images/input...
class ExponentialMovingAverage(object): ''' 权重滑动平均,对最近的数据给予更高的权重 uasge: # 初始化 ema = EMA(model, 0.999) # 训练过程中,更新完参数后,同步update shadow weights def train(): optimizer.step() ema.update(model) # eval前,apply shadow weights; # eval之后(保存模型后),恢复原来模型的参数 def eva...
import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from WizardVsWorld.classes.draw import * from WizardVsWorld.classes.fsm import FSM import WizardVsWorld.phases.player_movement_phase import WizardVsWorld.phases.player_attack_phase import WizardVsWorld.phas...
#!/usr/bin/env python3 import os import gzip import sys # Run this scrpipt under eggNOG 5.0 per_tax_level folder, # mirroring the following site. # 33208_Metazoa # http://eggnog5.embl.de/download/eggnog_5.0/per_tax_level/33208/ # 7742_Vertebrata # http://eggnog5.embl.de/download/eggnog_5.0/per_tax_level/7742/ tax_...
from jsonschema import validate from jsonschema.exceptions import ValidationError from jsonschema.exceptions import SchemaError updateshift_schema = { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "s...
''' ''' def openAsAscii(path): if path == "": path = "cipher.txt" file = open(path,"rb") data = file.read() udata = data.decode("utf-8") bytearray = udata.encode("ascii",errors="ignore") bytearray = bytearray.replace(bytes([ord("\n")]),bytes([ord(" ")])) return bytearray
import sys import os from subprocess import Popen, PIPE, STDOUT RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' LIGHT_PURPLE = '\033[94m' PURPLE = '\033[95m' END = '\033[0m' if __name__ == '__main__': try: src_dir = sys.argv[1] new_dir = sys.argv[2] except IndexError: print "Us...
from IPython.core.error import UsageError from adlmagics.magics.adls.adls_folders_listing_magic import AdlsFoldersListingMagic from adlmagics.exceptions import MagicArgumentError from adlmagics.session_consts import session_adls_account, session_null_value from adlmagics.models.adls_folder import AdlsFolder from adlm...
from pytorchtools.pytorchtools import EarlyStopping, save_model
from elasticsearch.helpers import bulk from msg_archive import es_client, get_data import utils crs = utils.get_cursor() sql = "select max(imsg) as highmsg from webdata.archive" crs.execute(sql) rec = crs.fetchone() curr = rec["highmsg"] with open(".highmessage") as ff: last = int(ff.read().strip()) if curr > l...
cur_dir = "" domain = "" user_sid = "" user_path = "" system_root = "" base_user_dir = "" user_appdata_dir = "" user_local_appdata_dir ="" user_roaming_appdata_dir = "" user_temp_dir = "" target = "" elevated_username = "" user_target = "" admin_priv = "" build = "" execution_label = "" artifact_file=""...
from .connection import Connection
class RebarShapeMultiplanarDefinition(object, IDisposable): """ A specification for a simple 3D rebar shape. RebarShapeMultiplanarDefinition(outOfPlaneBendDiameter: float) """ def Dispose(self): """ Dispose(self: RebarShapeMultiplanarDefinition) """ pass def ReleaseUnma...
# # 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 ...
#!/usr/bin/env python3 import unittest from hammingclasses import HammingEncoder, HammingChecker, random_word from basictests import corrupt_one_bit, corrupt_two_bits # ---- Unit test class --- # class TestStringMethods(unittest.TestCase): def setUp(self): """Sets up Hamming encoders and checkers for ...
from django.db import models # Create your models here. class Messages(models.Model): from_person = models.TextField() to_person = models.TextField() read = models.TextField() title = models.TextField() body = models.TextField() time = models.TextField() def __repr__(self): ...
from chronometry.date import get_today import re RESOLUTION_MARKERS0 = [ '2160p', '1440p', '1080p', '720p', '480p', '360p', '240p', '4k', '8k' ] RESOLUTION_MARKERS = RESOLUTION_MARKERS0 + [f'[{x}]' for x in RESOLUTION_MARKERS0] def is_resolution(string): return string.lower() in RESOLUTION_MARKERS def is_year...
import io ASCII = b'.' * 32 + bytes(range(32, 127)) + b'.' * 129 def dump(data, n=16, base=0): data = bytes(data) res = io.StringIO() for i in range(0, len(data), n): row = data[i : i + n].hex() + ' ' * n left = ' '.join(row[k : k + 2] for k in range(0, n, 2)) right = ' '.join(ro...
""" DQN - Test-time attacks ============ Sample usage ============ No attack, testing a DQN model of Breakout trained without parameter noise: $> python3 enjoy-adv.py --env Breakout --model-dir \ ./data/Breakout/model-100 --video ./Breakout.mp4 No attack, testing a DQN model of Breakout trained with parame...
import urllib.request, urllib.parse, urllib.error import json import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE address = input('Enter location: ') serviceurl = "http://py4e-data.dr-chuck.net/geojson?" url = serviceurl + urllib.par...
# -*- coding: utf-8 -*- """ Содержит в себе информацию о доменах, запускаемых в других процессах / на других серверах. """ from openre.domain.base import DomainBase import logging from openre.helpers import StatsMixin from openre.layer import RemoteLayer from copy import deepcopy class RemoteDomainBase(DomainBase): ...
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython Dadas N placas de automóvil, obtener la cantidad de placas que contienen una secuencia determinada SEC de caracteres. Construya el algoritmo. Ejemplo: Si N = 4 Placas: 649XGT, 1365SDG, 6789ERT, 1267SDG SEC = "SDG" Entonces: Cantidad de placas = 2 """ fro...
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Unlimited developers import asyncio from test_framework.util import assert_equal from test_framework.test_framework import BitcoinTestFramework from test_framework.loginit import logging from test_framework.electrumutil import bitcoind_electrum_args, \ Electru...
# -*- coding: utf8 -*- import codecs import os import sys try: from setuptools import setup except: from distutils.core import setup """ 打包的用的setup必须引入, """ def read(fname): return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read() NAME = "openastro" """ 名字,一般放你包的名字即可 """ PACKAGES = ["o...
# Copyright (c) 2018 Cisco and/or its affiliates. # 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...
""" This script adds MQTT discovery support for Shellies devices. """ ATTR_MANUFACTURER = "Allterco Robotics" ATTR_SHELLY = "Shelly" ATTR_MODEL_SHELLY1 = "Shelly 1" ATTR_MODEL_SHELLY1PM = "Shelly 1PM" ATTR_MODEL_SHELLY2 = "Shelly 2" ATTR_MODEL_SHELLY25 = "Shelly 2.5" ATTR_MODEL_SHELLY3EM = "Shelly 3EM" ATTR_MODEL_SHEL...
# -*- coding: utf-8 -*- """ Assembly https://github.com/mardix/assembly -------------------------------------------------------------------------------- "wsgi.py" is the application object. It's required by Assembly. It sets up and initialize all the views per application -------------------------------------------...
import typing as T from dataclasses import dataclass import moonleap.resource.props as P from moonleap import MemFun, Resource, extend, register_add from titan.project_pkg.service import Service, Tool from . import props @dataclass class PkgDependency(Resource): package_names: T.List[str] is_dev: bool = Fal...
# -------------- #Importing header files import pandas as pd import scipy.stats as stats import math import numpy as np import matplotlib.pyplot as plt from statsmodels.stats.weightstats import ztest from statsmodels.stats.weightstats import ztest from scipy.stats import chi2_contingency import warnings w...
import json import imp import os # Remove when transferred to server from flask import Flask from flask import render_template from flask import request # Remove when transferred to server app = Flask(__name__) # Database integration # from cassandra.cluster import Cluster # lsof -i :5000 """ # Ingestion integrat...
import sys from qshell.core import ctx # Decorator for registering functions as commands def command(func): if callable(func): def inner(*args, **kwargs): return func(*args, **kwargs) ctx.register(func.__name__, func) return inner else: def decorator(fn): ...
# -*- coding: utf-8 -*- # @File : xcache.py # @Date : 2021/2/25 # @Desc : import copy import time import uuid from django.core.cache import cache from Lib.log import logger class Xcache(object): """缓存模块""" XCACHE_MODULES_CONFIG = "XCACHE_MODULES_CONFIG" XCACHE_SESSION_INFO = "XCACHE_SESSION_INFO" ...
import py import sys, os, gc from rpython.translator.c.test import test_newgc from rpython.translator.translator import TranslationContext from rpython.translator.c.genc import CStandaloneBuilder from rpython.annotator.listdef import s_list_of_strings from rpython.conftest import option from rpython.translator.tool.cbu...
import tensorflow as tf import numpy as np from tensorflow import python_io as tpio import os def _int64_features(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_features(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) class VOC_TFReco...
import os import logging log = logging.getLogger("APTS.emit_changes") def __main__(*args): """Emit file change on task completed even no one cares Subscribers would lookup for changes and copy files to local drive if any. (NOTE) Post task script will not run if task has error. Args: (...
from datetime import datetime from background_worker.task.task import Task class RemoveTask(Task): def __init__(self, block_id_to_remove= None, datetime_to_run= None, client= None, dic = None): if client: self.notion_client = client if dic: super().__init__(type=...
from setuptools import setup setup( name='amptrac', version='0.1', url='https://github.com/twisted-infra/amptrac', description="Client for twisted's amp interface to trac", license='MIT', author='Tom Prince', author_email='tom.prince@ualberta.net', packages=['amptrac', 'amptrac.test'], ...
import torch from gensim.models import FastText from dataset import AuxTables from .featurizer import Featurizer class LangModelFeaturizer(Featurizer): def specific_setup(self): self.name = 'LangModelFeaturizer' self.emb_size = 10 self.all_attrs = self.ds.get_attributes() self.att...
from django.template import RequestContext, loader from django.shortcuts import get_object_or_404, render_to_response, redirect from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse, Http404 from apps.hypervisor.models import Hypervisor from apps.storagepool.models...
"""Model for the screens of protocol upload.""" import logging from typing import Optional, Tuple from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait fr...
from django.db import models from rest_offlinesync.models import TrackedModel class Document(TrackedModel): user = models.ForeignKey('auth.User', to_field='username', on_delete=models.CASCADE) title = models.CharField(max_length=128) text = models.TextField(max_length=2048)
from livro import Livro class Biblioteca: def __init__(self): self.__livros = [] @property def livros(self) -> Livro: return self.__livros def incluirLivro(self, livro: Livro) -> None: if livro not in self.livros and isinstance(livro, Livro): self.__livros.append(...
# -*- coding: utf-8 -*- """ pygments.lexers.shell ~~~~~~~~~~~~~~~~~~~~~ Lexers for various shells. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, inclu...
from sqlglot import expressions as exp from sqlglot.optimizer.normalize import normalized from sqlglot.optimizer.scope import traverse_scope from sqlglot.optimizer.simplify import simplify def pushdown_predicates(expression): """ Rewrite sqlglot AST to pushdown predicates in FROMS and JOINS Example: ...
from glloader.lang.c.loader.egl import EGLCLoader from glloader.lang.c.loader.gl import OpenGLCLoader from glloader.lang.c.loader.glx import GLXCLoader from glloader.lang.c.loader.wgl import WGLCLoader from glloader.lang.c.generator import CGenerator from glloader.lang.c.debug import CDebugGenerator _specs = { 'egl...
""" Contains names of DB tables """ T_NAME_AUTHORS = "authors" """`str` : `__tablename__` value for `BaseAuthor` table""" T_NAME_EVENTS = "events" """`str` : `__tablename__` value for `BaseEvent` table""" T_NAME_KEYS = "keys" """`str` : `__tablename__` value for `BaseKey` table""" T_NAME_SETTINGS = "settings" """`st...
# Tensorflow mandates these. from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import functools import tensorflow as tf slim = tf.contrib.slim def ShuffleNet(images, bottleneck_layer_size, is_training, reuse=False, shuffl...
from abc import ABC from selenium.webdriver import ActionChains from selenium.webdriver.common.alert import Alert from selenium.webdriver.remote.switch_to import SwitchTo from selenium.webdriver.remote.webelement import WebElement from ..drivers.driver_manager import DriverManager from ..general import Log from ..mix...
# Generated by Django 3.0.4 on 2020-03-24 06:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('customers', '0002_auto_20200324_0620'), ('invoices', '0001_initial'), ] operations = [ migrations.A...
import hashlib import json import re from typing import List, Union, Optional import aiohttp from sentry_sdk.utils import Dsn from . import Storage, AlreadyStoredError from ..database_entry import DatabaseEntry from ..exceptions import StorageError, ParserError class SentryFrame: """ Represents a Sentry sta...
# -*- coding: utf-8 -*- import requests import json from multiprocessing import Pool import time import os def send(data, url, key): print('send ', data) try: headers = {'Content-type': 'application/json', 'Accept': 'text/plain', 'X-PYTILT-KEY': key} r = requests.post(url, data=json.dumps(data)...
import os from .base import * ALLOWED_HOSTS = ['*'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS += ['debug_toolbar', 'django_extensions'] MIDDLEWARE = ( MIDDLEWARE[:-1] + [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'querycount.middleware.QueryCou...
import json from logging import getLogger import boto3 from django.apps import apps from django.conf import settings from domain_events.handler import HANDLERS logger = getLogger(__name__) def process_sqs_messages(event): apps.populate(settings.INSTALLED_APPS) for record in event["Records"]: if re...
from base64 import b64encode from app import app import unittest from mock import patch import os import json from twython import Twython class TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() os.environ['SERVICE_KEY'] = 'test-key' os.environ['SERVICE_PASS'] = 'tes...
# flake8: noqa from .segmentation import * from .resnet_encoder import * from .sequential import * __all__ = ['UNet', 'ResNetUnet', 'LinkNet']
import pytest from freezegun import freeze_time from flask import current_app from notifications_utils import SMS_CHAR_COUNT_LIMIT import app from app.dao import templates_dao from app.models import SMS_TYPE, EMAIL_TYPE, LETTER_TYPE from app.notifications.process_notifications import create_content_for_notification fr...
import pandas as pd import numpy datset=pd.read_csv("zoo.data") X=datset.iloc[:,1:17].values y=datset.iloc[:,17].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) from sklearn.svm import SVC classifier = SVC(kernel...
from .Cross_Validation import Cross_Validation from .BootstrapCV import BootstrapCV from .KFold import KFold from .NxM import NxM from .TestCV import TestCV from .loadercv import LoaderCV from .VersionDropout import VersionDropout __all__ = [ "Cross_Validation", "BootstrapCV", "KFold", "NxM", "Test...
import ast import io import json import tokenize from collections import namedtuple import asttokens import six def parse_acl_formula(acl_formula): """ Parse an ACL formula expression into a parse tree that we can interpret in JS, e.g. "rec.office == 'Seattle' and user.email in ['sally@', 'xie@']". The idea...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ## QC ## *Created on Mon, Mar 26 by A. Pahl* Tools for interactive plate quality control in the notebook. Uses Holoviews and its Bokeh backend for visualization. """ import os.path as op import pandas as pd import numpy as np import matplotlib as mpl import holovi...
from django.contrib import admin from .models import Actor admin.site.register(Actor)
from flask import Flask, render_template, request, jsonify, send_file, make_response app = Flask(__name__) @app.route('/files/<path>/<filename>') def test(path, filename): print(request.url) print(path, filename) return send_file('/home/ej/tmp.txt', as_attachment=True, mimetype='text/csv; charset=x-EBC...
import logging import random from tornado import gen log = logging.getLogger() def arguments(parser): parser.add_argument( "--workers", "-w", type=int, default=5, help="Number of workers to launch." ) parser.add_argument( "--znode-path", "-p", type=str, default="examplelock", ...
from django.forms import ModelForm from .models import Automate_text class TimetableForm(ModelForm): class Meta: model = Automate_text fields = ['title', 'message', 'number', 'important']
from datetime import datetime from typing import List from marshmallow import Schema, fields, post_load from src.dto.common.base_dto import BaseDto class ConsoleGamesListDto(BaseDto): def __init__(self, console_code: str = None, reference_id: str = None, title: str = None, ...
# coding=utf-8 # !/usr/bin/python3.6 ## Please use python 3.6 """ __synopsis__ : Produces pdfs over the support set classes for the target set sample. __description__ : Produces pdfs over the support set classes for the target set sample. __project__ : MNXC __author__ : Samujjwal Ghosh <cs16resch01001@iith...
# 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 u...
from urllib import urlopen from bs4 import BeautifulSoup htmlparent = urlopen("http://www.pythonscraping.com/pages/page3.html") bsObj = BeautifulSoup(htmlparent.read()) print(bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())
# Copyright (c) 2021 - present, Timur Shenkao # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
from django.contrib.contenttypes.models import ContentType from django.dispatch import receiver from django.db.models.signals import pre_delete from . import utils ModelFieldSchema = utils.get_model_field_schema_model() @receiver(pre_delete, sender=ModelFieldSchema) def drop_table_column(sender, instance, **kwargs...
__author__ = 'at' from app import AfricasTalkingGateway, AfricasTalkingGatewayException from app import settings from app import logging from urllib import urlencode import requests from redis import Redis redis_conn = Redis() class FetchUrl(object): """ Form urls, parse and """ def __init__(self, ...
from django.urls import path, include from . import views urlpatterns = [ # Articles Home/Index page path: path('', views.blog_homepage, name='blog_homepage'), # Articles Home page path w/ specific category search: path('blog_category/<str:category>', views.blog_homepage, name='blog_homepage_category'), # P...
import itasca from itasca import wall, ballfacetarray import statistic.models def get_stress_mpa(project: statistic.models.Project): """获取荷载板的正应力,单位为MPa""" width = project.specimen_width / 1000 top_position = wall.find('top').pos_y() bottom_position = wall.find('bottom').pos_y() top_position_array...
import unittest from garminworkouts.models.power import Power class PowerTestCase(unittest.TestCase): def test_valid_power_to_watts_conversion(self): ftp = 200 diff = 0 valid_powers = [ ("0", 0), ("0%", 0), ("10", 20), ("10%", 20), ...
import setlibspath from builder import * a = Builder()
from app.core.config import settings def test_fetch_ideas_reddit_sync(client): # When response = client.get(f"{settings.API_V1_STR}/recipes/ideas/") data = response.json() # Then assert response.status_code == 200 for key in data.keys(): assert key in ["recipes", "easyrecipes", "TopSe...