content
stringlengths
5
1.05M
# Instructions: The following code example would print the data type of x, what data type would that be? x = ["apple", "banana", "cherry"] print(type(x)) ''' Solution: list Lists are list type. Read more here: https://www.w3schools.com/python/python_datatypes.asp '''
"""! \ingroup lammpstools Produces a histogram in a more intuitive way than numpy does. """ import numpy as np def make_histogram( yy, y0, y1, Nbins ): """! Produces a histogram from data in yy. @param yy Data to histogram @param y0 Lower bound of histogram @param y1 Upper bound of h...
# -*- coding: utf-8 -*- """ Created on Thu May 14 13:14:53 2020 @author: wuest """ import numpy as np from usm_make import usm_make from scipy.spatial.distance import pdist import matplotlib.pyplot as plt import datetime import pathlib from Bio import SeqIO import copy #from Bio import Seq #from Bio...
import sys sys.path.append("../synapse") import numpy as np import synapse as sn from synapse import Tensor from synapse.autograd.tensor import Node from synapse.nn.loss import MSE from synapse.nn.activations import ReLU from synapse.testing.graph import showParents data = np.arange(1,10, dtype=np.float) data = np.e...
# 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 writing, software # distributed under t...
import numpy as np import time from maci.misc import logger from copy import deepcopy def rollout(env, policy, path_length, render=False, speedup=None): Da = env.action_space.flat_dim Do = env.observation_space.flat_dim observation = env.reset() policy.reset() observations = np.zeros((path_leng...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-07-01 12:19 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
from urllib.request import urlopen from bs4 import BeautifulSoup as soup my_url ="https://www.politeianet.gr/best-sellers" uClient=urlopen(my_url) page_html=uClient.read() uClient.close() page_soup=soup(page_html, "html.parser") containers=page_soup.findAll("div",{"browse-page-block"}) # Csv file config filename="...
from src.init import Init import pytest def test_file1_method1(): x=5 y=6 assert x+1 == y,"test success" def test_file1_method2(): x=5 y=6 assert x+1 == y,"test success"
#!/usr/bin/python3 # program to implement lightweight mobilenet filter on some images. # see video at https://www.youtube.com/watch?v=qFJeN9V1ZsI&t=27s # name: R. Melton # date: 1/5/21 import os,shutil import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Dense...
import os import json path = "/home/lofowl/Desktop/data" data_elements = os.listdir(path) param_path = f'{path}/{data_elements[0]}' def ParamDataSet(dataset,*kwgs) -> list: param_test = f'{param_path}/{dataset}.json' with open(param_test,"r") as files: param_test = json.loads(files.read()) r...
from unittest import TestCase from lie2me.fields import Text from .common_tests import CommonTests class TextTestCase(TestCase, CommonTests): def setUp(self): self.Field = Text self.valid_default = 'foobar' def test_valid_value(self): field = Text() value, error = field.subm...
"""This module retrieves stock lists.""" from abc import ABC, abstractmethod from functools import lru_cache from io import BytesIO import json import pandas as pd import re from string import capwords from typing import Optional import xmltodict from zipfile import ZipFile from financialdatapy.exception import EmptyDa...
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 # pylint: disable=redefined-outer-name import os import re from decisionengine.framework.tests.fixtures import ( # noqa: F401 DEServer, PG_DE_DB_WITHOUT_SCHEMA, PG_PROG, SQLALCHEMY_PG_WITH_SCHEMA, S...
# TESTING NEW INTERFACES FOR THE COVID19 DATA # import tkinter as tk # from pandas import DataFrame # import matplotlib.pyplot as plt # from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # data1 = {'Country': ['US','CA','GER','UK','FR'], # 'GDP_Per_Capita': [45000,42000,52000,49000,47000] # ...
import copy import scrapy from scrapy.item import DictItem from scrapy.loader import ItemLoader from .abc import ItemABC from .utils import is_xpath_selector class BaseItem(scrapy.Item): """Base class that allows access to the field values using dot notation, i.e. item.my_field = my_value """ def _...
from dipy.io.streamline import load_tractogram,save_tractogram from dipy.segment.clustering import QuickBundles from dipy.segment.metric import ResampleFeature from dipy.segment.metric import AveragePointwiseEuclideanMetric from dipy.io.stateful_tractogram import StatefulTractogram,Space import numpy as np import os ...
from collections import namedtuple from typing import Tuple, Union import PIL.Image import matplotlib.pyplot as plt from pydispix.errors import CanvasFormatError Dimensions = namedtuple("Dimensions", ("width", "height")) SizeType = Union[Dimensions, Tuple[int, int]] class Pixel: """A single pixel of the canva...
# Copyright 2011 VMware, Inc. # 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 ...
from dataclasses import dataclass from dataclasses import field as dcls_field from typing import ClassVar @dataclass class Envelope: POSTAGE_MULTIPLIER: ClassVar[float] = dcls_field(default=10.0) weight: float postage: float = dcls_field(default=0.0) was_sent: bool = dcls_field(default=False) de...
"""Marlin command plug-ins for SVN-ish commands. Copyright 2015-2016 The Salish Sea MEOPAR Contributors and The University of British Columbia 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 ht...
# Copyright The IETF Trust 2019-2020, All Rights Reserved # -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2019-11-15 20:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('review', '0019_auto_20191023_0829'), ] operations = [ m...
import logging import time import ccobra import numpy as np import mreasoner import fol import phm logger = logging.getLogger(__name__) class MisinterpretedNecessityRestr(ccobra.CCobraModel): def __init__(self, name='MisinterpretedNecessity-Restr', method='mReasoner'): super(MisinterpretedNecessityRest...
(lambda numbers: print(len([i for i, num in enumerate(numbers) if i != 0 and num > numbers[i-1]])))([int(i) for i in open("input1.txt").readlines()])
from setuptools import find_packages, setup setup( name='python-boilerplate', verison='0.0.1', packages=find_packages(exclude=['docs', 'tests']), scripts=['bin/example_script'], author='someone', author_email='someone@intel.com', description='Python boilerplate', url='https://gitlab.de...
#!/usr/bin/env python import os import cPickle import sys from collections import defaultdict from lib import sval_systems_reader, wordnet_reader, create_freq_dict, get_naf_filename_for_token, get_freqclass_of_freq from extlib.KafNafParserPy import KafNafParser os.environ['LC_ALL'] = 'en_US.UTF-8' __this_dir__ = ...
# https://github.com/okfn/ckanext-datahub/blob/release-v2.0/ckanext/datahub/model/user_extra.py """ Provides extras for user model """ import vdm.sqlalchemy import vdm.sqlalchemy.stateful from sqlalchemy import orm, types, Column, Table, ForeignKey import ckan.model.group as group import ckan.model.meta as meta imp...
from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import re import time def scrape(): browser = Browser('chrome',executable_path = 'chromedriver', headless='False') news_title, news_p = mars_news(browser) scrap_data = { 'news_title': news_title, 'news_p':...
import matplotlib.pyplot as plt import numpy as np plt.figure() plt.subplot(1, 2, 1) plt.xlim((0, 1)) plt.ylim((0, 1)) plt.scatter([0.5, 0.499], [0.5, 0.499]) plt.subplot(1, 2, 2) plt.xlim((0.45, 0.55)) plt.ylim((0.45, 0.55)) plt.scatter([0.5, 0.499], [0.5, 0.499]) plt.show() x = np.linspace(0, 1) y = x**2 coords = ...
#!/usr/bin/env python # coding=utf-8 # Python linter configuration. # pylint: disable=I0011 # pylint: disable=C0301 # pylint: disable=W0702 # I don't get W0702, I want to catch all exceptions.. so, disabling. """ Prometheus Cisco ISE Exporter TODO: * Don't use globals! * Test / Travis """ import sys imp...
#!/usr/bin/env python # Lint as: python3 # -*- encoding: utf-8 -*- """Tests for grr.lib.client_index.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import binascii import ipaddress from absl import app from grr_response_core.lib.rdfvalues import cli...
# -*- coding:utf-8 -*- """ 压测的基础场景,用于定义一系列的接口 """ # java 类 from org.jeff.test import HTTPClient class SampleHttpScene(HTTPClient): """ 基础场景 """ def __init__(self, uid): """ @sig public HTTPClient(int uid) :param uid: 用户id """ super(SampleHttpScene, self).__in...
import pickle import matplotlib.pyplot as plt import os # write a list (test_nos) of the test numbers you want to plot against each other on different datasets. Write another # list with the corresponding names and pass these into the below function. This will generate plots that compare # configurations on the same d...
# coding utf-8 ''' Native support for HID input from the linux kernel ================================================== Support starts from 2.6.32-ubuntu, or 2.6.34. To configure HIDInput, add this to your configuration:: [input] # devicename = hidinput,/dev/input/eventXX # example with Stantum MTP4.3" ...
''' Encrypt or Decrypt a JWE token:: with imported or generated asymmetric keys: based on http://jwcrypto.readthedocs.io/en/latest/jwe.html#examples ''' from jwcrypto import jwk, jwe from jwcrypto.common import json_encode, json_decode ### GENERATE CUSTOM KEYS - ALTERNATIVE 1 # public_key = jwk.JWK() # private_key...
def foo(a): """ <caret> @param a: @type a: @return: @rtype: """ pass def foo1(): """ :return : """
import os os.environ["CUDA_VISIBLE_DEVICES"]='7' from model_multi_nerf import Multiple_NeRF from load_blender_torch import load_blender_data import torch import numpy as np import imageio import matplotlib.pyplot as plt from sklearn.cluster import KMeans from scipy import ndimage import torchvision.transforms.functiona...
import yt import yt.units as u ds = yt.load("HiresIsolatedGalaxy/DD0044/DD0044") center = [0.53, 0.53, 0.53] normal = [0, 0, 1] radius = 40 * u.kpc height = 2 * u.kpc disk = ds.disk(center, [0, 0, 1], radius, height) profile = yt.create_profile( data_source=disk, bin_fields=["radius", "cylindrical_tangentia...
#!/usr/bin/python ################################################################################ # # New Zealand Geographic Board gazetteer application, # Crown copyright (c) 2020, Land Information New Zealand on behalf of # the New Zealand Government. # # This file is released under the MIT licence. See the LICE...
from sseclient import Event from urllib3.exceptions import HTTPError import json def adapter_sse(record: Event) -> dict: """SSE adapter. Args: record: SSE Event Returns: data dict """ if record.event == "error": raise HTTPError(record.data) if record.event not in ["cl...
from __future__ import annotations from functools import lru_cache from sqlalchemy import Table from sqlalchemy.orm import Mapper from sqla_ext.protocols import ORMTableProtocol, TableCoercable @lru_cache() def to_core_table(entity: TableCoercable) -> Table: r"""Coerces multiple SQLA Table-like entities to a c...
import os import sys import pytest testpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.path.sep + \ 'wisdem' + os.path.sep + 'test' + os.path.sep if __name__ == '__main__': sys.exit( pytest.main([testpath]) )
import itertools import os print("Press <enter> to skip.") first_name = input("Enter target first name: ").strip() surname = input("Enter target surname: ").strip() last_name = input("Enter target last name: ").strip() birthdate = input("Enter target birthday (ddmmyyyy): ").strip() phone_number = input("Enter phone n...
from flask import Flask, render_template, request from flask_uploads import UploadSet, configure_uploads, IMAGES import os app = Flask(__name__) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'static/img' configure_uploads(app, photos) @app.route('/', methods=['GET', 'POST']) def upload(...
# Example motivated by dolfin mailing list (questions 221862): # http://answers.launchpad.net/dolfin/+question/221862 -- see last reply from Hake # The entry on the list is not actually very # informative, but the snippet below seems to show the key idea. # # I am gathering this here, to push forward the whole dofmap...
import os import sys def get_path(directory: str, filename: str): if directory: return os.path.join(ROOT_DIR, directory, filename) return os.path.join(ROOT_DIR, filename) def img_path(filename: str): return get_path('images', filename) def font_path(filename: str): return get_path('fonts', filename)...
import cv2 import numpy as np image = cv2.imread('plant.jpg',0) cv2.imshow('original',image) laplacian = cv2.Laplacian(image,cv2.CV_32F) cv2.imshow('laplacian',laplacian) edges1 = cv2.Canny(image,100,200) cv2.imshow('edges1',edges1) laplacian1 = cv2.Laplacian(edges1,cv2.CV_32F) cv2.imshow('laplacian1',laplacian1) ...
""" Quick script to create associated tables """ import sqlite3 as s open("./model/database.db", "x").close() db = s.connect("./model/database.db") cursor = db.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS clients( id_client INTEGER, name TEXT, street TEXT, ZIP INTEGER, ...
def main(): num = int(input("Digite o seu número: ")) if(num % 5 == 0): print("Buzz") else: print(num) main()
from os import system from pynput import keyboard import time break_program = False def on_press(key): global break_program print (key) if key == keyboard.Key.end: print ('end pressed') break_program = True return False with keyboard.Listener(on_press=on_press) as listener: whi...
# This file is part of BINANA, released under the Apache 2.0 License. See # LICENSE.md or go to https://opensource.org/licenses/Apache-2.0 for full # details. Copyright 2021 Jacob D. Durrant. """When used as a JavaScript library, BINANA cannot access the local file system to save and load files. These functions save a...
import pickle import shutil import re import hashlib import base64 from datetime import datetime import pandas as pd def df_to_records(df: pd.DataFrame, dataset: str, drop_columns = []): """ Convert dataframe to a list of record oriented dicts. Parameters ---------- df : pd.DataFrame Inp...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'chainer_wing/resources/mainwindow.ui' # # Created by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtWidgets from chainer_wing.node_lib import NodeList, NodeFilter from chai...
import json import re from django.utils.decorators import method_decorator from rest_framework.viewsets import ModelViewSet from rest_framework import status from rest_framework import exceptions from rest_framework.response import Response from rest_framework.permissions import DjangoModelPermissions from dj...
#!/bin/python # -*- coding: utf-8 -*- """ Unit tests for gluon.sqlhtml """ import os import sys import unittest from gluon.sqlhtml import safe_int, SQLFORM, SQLTABLE DEFAULT_URI = os.getenv('DB', 'sqlite:memory') from gluon.dal import DAL, Field from pydal.objects import Table from gluon.tools import Auth, Mail...
# API Depedencies here
#GLOBAL IMPORTS import numpy as np import pygame #PACKAGE IMPORTS from .gameobjects import GameObject, Move from .bullet import Bullet from colearning.utils import clip_to_dim, clip_array_to_dim, TeamColors class Player(GameObject): """ The base class for all players. Handles all game-related logic """ #----...
class SSZException(Exception): """ Base class for exceptions raised by this package. """ pass class SerializationError(SSZException): """ Exception raised if serialization fails. """ pass class DeserializationError(SSZException): """ Exception raised if deserialization fails....
from CodeWriter import CodeWriter from Parser import Parser from Lex import Lex, ARITHMETIC_COMMANDS, PUSH_OR_POP_COMMANDS import os, sys # Parsing and sanytizing args asm_file = sys.argv[1] if asm_file == None: raise Exception('missing .asm file') file_name, file_type = os.path.splitext(asm_file) if file_type.lo...
from django.urls import path, re_path from invoice.views import InvoiceByIdView, InvoiceView urlpatterns = [ re_path(r"^$", InvoiceView.as_view(), name="invoice"), path(r"<id>", InvoiceByIdView.as_view(), name="invoice_id"), ]
import jmespath test_dictionary = { 'level_1': { 'level_2_a': { 'level_3_a': 'some_string' }, 'level_2_b': { 'level_3_b': 'a_different_string' } } } # method 1 level_3_a = test_dictionary.get('level_1', {}).get('level_2_a', {}).get('level...
import pandas as pd import os import random import numpy as np # setting path os.chdir('Z:/sorger/data/IN_Cell_Analyzer_6000/Connor/Fixed MCF10 Common/20x full exp/20180905_Updated/') path_out = 'N:/HiTS Projects and Data/Personal/Jake/mcf10a/' # get list of valid columns and feature selected columns feature_metadata =...
# Generated by Django 4.0.3 on 2022-05-13 00:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('libraries', '0002_library_library_code'), ('profiles', '0006_alter_mentorprofile_assigned_library'), ] oper...
def read_line(s): """ Reads one line in ipsec.secrets(5) format and returns a dictionary with left, right, and auth-type keys. Caveat: very simplistic, does not handle includes, non-quoted passwords, inlined RSA, ... Also requires that : between username and auth_type is space-delimeted from bot...
# pylint: disable=import-error # pylint: disable=no-name-in-module import time from enum import Enum, auto from dataclasses import dataclass, field # pylint: enable=import-error from utils.common import uuid_factory class EventType(Enum): # Generic GENERIC_EVENT = auto() GENERIC_MODEL_CREATED = auto() ...
import os import sys import logging from typing import List, Dict from jinja2 import Template def populate_template(template: str, input_values: dict) -> str: "populate template renders a given Jinja2 template string with the given input_values" template_obj = Template(template) return template_obj.rende...
#trader cancels trade order.
#!/usr/bin/env python3 """Primary entry point to CustomCam from the command line.""" import inspect import logging from CustomCam.camera import CameraModifier from CustomCam.utils import setup_logger, setup_argparse import CustomCam.filters as filters def run(): """Command line run function.""" # Set up a...
# test data from test.c import wolfssl KEY_LENGTH = 24 SHA256 = 2 # Hashtype, stands for Sha256 in wolfssl. def to_c_byte_array(content): output = wolfssl.byteArray(len(content)) for i, ch in enumerate(content): output[i] = ord(ch) return output password = '\x00\x73\x00\x6d\x00\x65\x00\x6...
# -*- coding: utf-8 -*- __author__ = "Vinícius Silva Madureira Pereira <viniciusmadureira@outlook.com>" __date__ = "$Jul 7, 2017 7:14:12 PM$" import urllib.request class Download: header = None @staticmethod def get(url): request = urllib.request.Request(str(url)) response = urllib.reque...
import logging from threading import RLock from typing import Callable, Tuple, TypeVar import schedule import ts3 from ts3.query import TS3ServerConnection, TS3TransportError from bot.config import Config from bot.ts.ts3_extensions import ExtendedTS3ServerConnection LOG = logging.getLogger(__name__) R = TypeVar('R'...
import itertools import random from typing import Set, List, Any, Dict import pandas as pd from autopandas_v2.generators.base import BaseGenerator from autopandas_v2.generators.dsl.values import Fetcher from autopandas_v2.generators.ml.traindata.exploration.iospecs import ExplorationSpec from autopandas_v2.generators....
# -*- coding: utf-8 -*- from .core import create_session, remove_session import threading from django.conf import settings SQLALCHEMY_SESSION_AUTOCOMMIT = getattr(settings, 'SQLALCHEMY_SESSION_AUTOCOMMIT', False) class EnsureSession(object): def process_request(self, request): global local loca...
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='booksread', version='0.0.1', description='get all the stats related words from book', keywords='book word autocomplete suggest data \ Google author chain machine learning \ Umesh Joshi', aut...
#!/usr/bin/env python # whisker_serial_order/settings.py """ =============================================================================== Copyright © 2016-2018 Rudolf Cardinal (rudolf@pobox.com). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compli...
from flask import Blueprint from common.libs.Helper import ops_render route_stat = Blueprint('stat_page', __name__) @route_stat.route('/index') def index(): return ops_render('stat/index.html') @route_stat.route('/food') def stat_food(): return ops_render('stat/food.html') @route_stat.rou...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 24 23:58:17 2018 @author: user """ import numpy as np import pandas as pd import matplotlib.pyplot as plt ######################### CONSTANT ############################### ########### RGB COLORS ############ RGB1 = {'black' :[ 0, 0, 0],...
#! /usr/bin/python # -*- coding: utf-8 -*- import numpy as np import tensorflow as tf __all__ = [ 'Initializer', 'Zeros', 'Ones', 'Constant', 'RandomUniform', 'RandomNormal', 'TruncatedNormal', 'deconv2d_bilinear_upsampling_initializer' ] class Initializer(object): """Initializer base class: all initia...
from MagniPy.ABCsampler.sampler_routines import * from copy import deepcopy,copy from MagniPy.paths import * from pyHalo.pyhalo import pyHalo import time from MagniPy.util import approx_theta_E from lenstronomywrapper.LensSystem.macrolensmodel import MacroLensModel from lenstronomywrapper.LensSystem.LensComponents.pow...
expr = str(input('Digite uma expressão: ')) pilha = [] for simb in expr: if simb == '(':# acha o símbolo e adiciona na lista pilha.append('(') elif simb == ')':# acho o símbolo e se o tamanho da pilha for maior que 0, remove o símbolo de abertura. if len(pilha) > 0: pilha.pop() ...
from LnkParse3.target.lnk_target_base import LnkTargetBase # https://github.com/libyal/libfwsi/blob/master/documentation/Windows%20Shell%20Item%20format.asciidoc#37-uri-shell-item # TODO: rename to uri class Internet(LnkTargetBase): pass
import json from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import svm from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.linear_model i...
# coding: utf-8 # author: gabriel couture import unittest from pyorthanc import Orthanc from tests import setup_server from tests.data import a_patient class TestOrthancPatientDeleters(unittest.TestCase): @classmethod def setUpClass(cls) -> None: global orthanc_subprocess orthanc_subprocess ...
from pgdrive.examples.ppo_expert.numpy_expert import expert
# -*- coding: utf-8 -*- #Clase que devuelve los datos que necesita las funciones de estadísticas para funcionar #(Alumnos, profes, faltas, etc.). # En una primera arpoximación, se hará con listas, pero más adelante class RecolectorDatos: #Función que devolverá a los alumnos @classmethod def obtenerAlumno...
# Програма определяет длину сторон треугольника. # Находит биссектрису наибольшего угла # Определяет является ли треугольник прямоугольным. # Определяет находится ли точка внутри треугольника # Находит расстояние до ближайшей стороны. # x1, y1 - координаты вершины A # x2, y2 - координаты вершины B # x3, y3 - ко...
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
from rest_framework import serializers from store.models import Store class StoreSerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField() class Meta: model = Store fields = "__all__" read_only_fields = ["owner", "slug"] def get_owner(self, obj): ...
# # DAPLink Interface Firmware # Copyright (c) 2016-2016, ARM Limited, All Rights Reserved # 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...
#!/usr/bin/env python3 import unittest import timeout_decorator from challenges.codility.lessons.q020.brackets_v001 import * MAX_N = 200000 class NestingTestCase(unittest.TestCase): def test_description_examples(self): self.assertTrue(solution("(()(())())")) self.assertFalse(solution("())")) # Corre...
# -*- coding: utf-8 -*- import info from Blueprints.CraftVersion import CraftVersion import subprocess import sys from info import DependencyRequirementType class subinfo(info.infoclass): def setTargets(self): self.versionInfo.setDefaultValues() self.description = "Text-based video subtitle editor...
import itertools import json import string # Create the string with all possible charactesr according to specs charset = string.ascii_lowercase + string.digits + string.ascii_uppercase # Calculate all the combinations and convert to a list list_combinations = list(itertools.product(charset, repeat=2)) # Write all th...
from collections import OrderedDict from IPython.display import Markdown, display, JSON import ipywidgets as widgets from tofnet.utils.config import BaseConfig as Config class SelectLogs: def __init__(self, logspath): self.logs = sorted([(x.name, x) for x in logspath.iterdir()], reverse=True) self...
# coding: utf-8 import os import beansdbadmin from flask import Flask from flask import render_template as tmpl from beansdbadmin.tools.gc import GCRecord, SQLITE_DB_PATH, update_gc_status from beansdbadmin.models.server import ( get_all_server_stats, get_all_buckets_key_counts, get_all_buckets_stats) from beansdb...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ created by Halo 2020/10/27 14:21 """ import torch from torch import nn from torch.nn import init import numpy as np import mytorch.d2lzh_pytorch as d2l num_inputs, num_outputs, num_hiddens = 784, 10, 256 class FlattenLayer(nn.Module): def __init__(self): ...
# -*- coding: utf-8 -*- from ....Functions.Plot.Pyvista.plot_glyph_pv import plot_glyph_pv from ....Functions.Plot.Pyvista.configure_plot import configure_plot from numpy import ( pi, max as np_max, abs as np_abs, linspace, exp, ) from ....Classes.MeshMat import MeshMat from ....definitions import...
import math #num = float(input('Digite')) #print(math.trunc(num)) #print(int(num)) #catop=float(input("digite o cateto oposto:")) #catadj=float(input('Digite o catete adjacente')) #print('A hioitenusa é:',math.hypot(catop, catadj)) # #from math import radians,sin, cos, tan (importando apenas as funções) #angulo=float...
# -*- coding: utf-8 -*- # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from flask import Blueprint, current_app, flash, render_template from flask_wtf.csrf import CSRFError from werkzeug.exceptions import NotFound from nscheck.dns.gluerecords...
# import sys try: import lxml except ImportError: lxml = None SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']} def approximate_size(size, a_kilobyte_is_1024_bytes=True): '''Convert a file size to human-readable...
import pytest from tartiflette import Resolver, Scalar, create_engine @pytest.mark.asyncio async def test_tartiflette_execute_basic_type_introspection_output( clean_registry ): schema_sdl = """ \"\"\"This is the description\"\"\" type Test { field1: String field2(arg1: Int = 42): Int ...