text stringlengths 2 999k |
|---|
import os
from tests.opentera.db.models.BaseModelsTest import BaseModelsTest
from sqlalchemy import exc
from opentera.db.Base import db
from opentera.db.models.TeraService import TeraService
class TeraServiceTest(BaseModelsTest):
filename = os.path.join(os.path.dirname(__file__), 'TeraServiceTest.db')
SQLI... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
import unittest
import panphon._panphon as panphon
class TestFeatureTableAPI(unittest.TestCase):
def setUp(self):
self.ft = panphon.FeatureTable()
def test_fts(self):
self.assertEqual(... |
from resource_management import *
from resource_management.core.resources.system import Execute
from resource_management.libraries.script.script import Script
from client import install_flink, config_flink
from resource_management.libraries.functions.check_process_status import check_process_status
class Historyserv... |
import torch
import torch.nn as nn
from module.BaseBlocks import BasicConv2d
from utils.tensor_ops import cus_sample, upsample_add
from backbone.origin.from_origin import Backbone_ResNet50_in3, Backbone_VGG16_in3
from module.MyModule import AIM, SIM
class MINet_VGG16(nn.Module):
def __init__(self):
super... |
###############################################################################################
# 确实简单
###########
# 时间复杂度:O(n),n表示以‘.’分开后的数组长度
# 空间复杂度:O(m),m表示两个字符串长度
###############################################################################################
class Solution:
def compareVersion(self, vers... |
# -*- coding: utf-8 -*-
"""Utility functions.
:author: Stefan Lehmann <stlm@posteo.de>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2018-06-11 18:15:53
:last modified by: Stefan Lehmann
:last modified time: 2018-07-12 14:11:12
"""
import sys
from ctypes import c_ubyte
def pla... |
# Copyright 2020- Robot Framework Foundation
#
# 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... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class PublicTag... |
#!/usr/bin/env python
PARTS = ['negative', 'positive', 'full'] # up and left is negative, down and right is positive
MODES = ['interceptor', 'injector', 'adder']
class Interceptor:
def __init__(self):
self.enabled = False
self.interceptor = None
self.watchdog = 2 * 1e9 # In 2 sec disable interceptor i... |
import numpy
def as_str (l):
return ' '.join (map(str, l))
def randelt (l):
return l[numpy.random.randint(len(l))]
def append (*l):
result = []
for x in l: result.append (x)
return result
def roll_die (p):
if sum(p) > 1 + 1e-12:
raise "Huh? p: %s" % (p,)
# Weird numpy thing
... |
from django.contrib import admin
from .models import Stoyo
from .models import Publisher
from .models import Temporary
# Register your models here.
admin.site.register(Stoyo)
admin.site.register(Publisher)
admin.site.register(Temporary)
|
# Copyright 2017 The TensorFlow Authors. 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 applica... |
from contextlib import contextmanager
import colorama
import atexit
import faulthandler
import hashlib
import inspect
import io
import json
import logging
import os
import redis
from six.moves import queue
import sys
import threading
import time
import traceback
# Ray modules
import ray.cloudpickle as pickle
import ra... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from .authentication import FirebaseAuthentication
from rest_framework.permissions import IsAuthenticated
class FirebaseAuthMixin():
permission_classes = (IsAuthenticated,)
authentication_classes = (FirebaseAuthentication,)
|
#!/usr/bin/env python3
import templates
import cgi
import secret
import os
# import json
# Print environment as json
# print("Content-Type: application/json")
# print()
# print(json.dumps(dict(os.environ), indent=2))
# Print query parameter data in html
# print("Content-Type: text/html")
# print()
# print(f"<p>QUERY_... |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
def revString(astring):
return astring[::-1]
if __name__ == '__main__':
ans = revString('stressed')
print(ans)
|
# ~*~ encoding: utf-8 ~*~
from functools import wraps
from flask import abort
from flask_login import current_user
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.permission != permission:
abort(4... |
# Copyright [2019] [Christopher Syben, Markus Michen]
#
# 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 ... |
# coding: utf-8
"""
Idfy.Signature
Sign contracts, declarations, forms and other documents using digital signatures. ## Last update Last build date for this endpoint: 18.03.2019
"""
import pprint
import re
from typing import List, Dict
from datetime import datetime as datetime
class SignSuccess(objec... |
# Copyright 2015 Google 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 applicable law or a... |
class ContextualHelp(object):
"""
Contains the details for how Revit should allow invocation of contextual help for an item added by an application.
ContextualHelp(helpType: ContextualHelpType,helpPath: str)
"""
def Launch(self):
"""
Launch(self: ContextualHelp)
Launches and d... |
import re
import xml.etree.ElementTree as ET
from pyplwnxml.enums import Domain, RelationType, PartOfSpeech, Qualifier, SentimentType
from pyplwnxml.utils import regex_escaped_joined_enum_values
from pyplwnxml.wordnet import LexicalUnit, Synset, Wordnet, Sentiment
class PlwnxmlParser:
__LEXICAL_RELATIONS = 'lexi... |
import math
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
def get_or... |
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1467227107.320681
_enable_loop = True
_template_filename = u'/home/sumukh/Documents/thesis/Cyberwe... |
import yfinance
class Stock:
__stock_data = None
def __init__(self):
pass
def grab(self):
self.__stock_data = yfinance.download(tickers='BASFY', period='1d', interval='1m')
def to_console(self):
print(self.__stock_data)
|
from .externalcalendar import ExternalCalendar
|
from __future__ import print_function
import sys
from robot.api import logger
class InitLogging:
called = 0
def __init__(self):
InitLogging.called += 1
print('*WARN* Warning via stdout in init', self.called)
print('Info via stderr in init', self.called, file=sys.stderr)
logger... |
from ce_turtl import *
turtle.home()
turtle.clear()
for i in range(600):
if i % 5 == 0:
turtle.left(3)
turtle.forward(200)
turtle.left(360/5)
turtle.show()
|
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/Python/Advanced/non_blocking_visualization.py
import open3d as o3d
import numpy as np
import copy
if __name__ == "__main__":
o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Debug)
sou... |
import json
from collections import UserDict
from dataclasses import dataclass
from typing import List
from mach_nix.cache import cached
from mach_nix.versions import parse_ver, Version
@dataclass
class NixpkgsPyPkg:
name: str
nix_key: str
ver: Version
class NixpkgsIndex(UserDict):
# mapping from p... |
import sys
sys.path.append('../..')
import os.path
from os import path
import pytest
from input_output_processing.cats_input_file_writer import *
from input_output_processing.read_moose_csv_to_df import *
# Start single tests
@pytest.mark.unit
def test_build_error():
with pytest.raises(TypeError):
data =... |
from unittest import mock
from uuid import UUID
from carbonserver.api.infra.repositories.repository_projects import SqlAlchemyRepository
from carbonserver.api.schemas import Project, ProjectCreate
from carbonserver.api.services.project_service import ProjectService
PROJECT_ID = UUID("f52fe339-164d-4c2b-a8c0-f562dfce0... |
#recommendations
from math import sqrt
critics={
'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman... |
'''
AM2315 Temp/Humidity Sensor Driver (using Silta bridge)
Based on the Adafruite Arduino driver
https://github.com/adafruit/Adafruit_AM2315
'''
import time
import tca9548a
AM2315_ADDR = 0xB8
class AM2315:
def __init__(self, bridge, mux_channel=3):
self.bridge = bridge
self.mux = tca9548a.TCA... |
import os
import runpy
path = r'Demos'
#python_file = 'C:/src/GIT/PythonEssentials/async_finish.py'
#runpy.run_path(python_file)
for (path, dirs, files) in os.walk(path):
python_files = [file for file in files if file.endswith(".py")]
for python_file in python_files:
runpy.run_path(os.path.join... |
import os
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import hmac
from cryptogra... |
# project/server/auth/views.py
from flask import Blueprint, request, make_response, jsonify
from flask.views import MethodView
from project.server import bcrypt, db
from project.server.models import User
auth_blueprint = Blueprint('auth', __name__)
class RegisterAPI(MethodView):
"""
User Registration Resour... |
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import echoclient
from twisted.internet import defer, endpoints, protocol, ssl, task
from twisted.python.modules import getModule
@defer.inlineCallbacks
def main(reactor):
factory = protocol.Factory.forProtocol(echocli... |
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
#################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). ... |
# coding: utf-8
"""
Aspose.ThreeD Cloud API Reference
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import ... |
import unittest, time, sys, random, math, json
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_kmeans, h2o_hosts, h2o_import as h2i, h2o_jobs
import socket
# kevin@mr-0xb1:~/h2o/py/testdir_hosts$ ls -ltr /home3/0xdiag/datasets/kmeans_big
# -rw-rw-r-- 1 0xdiag 0xdiag 183538602156 Aug 24 11:43 syn_sphere15_271... |
'''
Source : https://leetcode.com/problems/unique-email-addresses/
Author : Yuan Wang
Date : 2019-01-04
/**********************************************************************************
*Every email consists of a local name and a domain name, separated by the @ sign.
*
*For example, in alice@leetcode.com, alice i... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
width = height = 32
channel = 3
patch_size_x = 8 ;patch_size_y = 8
class Augmentator(object):
def __init__(self,type,size=1,mean=0,std=1):
self.size = size
if type==... |
"""
Board object contains all features for displaying pieces and chess board, also allows to move the all pieces on the board.
Object contains two dictionary, there are:
- self._notation_to_xy_position: contains the chess notation names "notation" and the corresponding X and Y
coordinat... |
from django.apps import AppConfig
class CsmAppConfig(AppConfig):
name = 'csm_app'
|
#!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
# Copyright (c) 2020 Nordic Semiconductor NA
#
# SPDX-License-Identifier: Apache-2.0
"""Translate generic handles into ones optimized for the application.
Immutable device data includes information about dependencies,
e.g. that a particular sensor is cont... |
from threading import Thread, Event, Lock
from typing import Union
from mongoengine.errors import NotUniqueError
from web3.datastructures import AttributeDict
from src.contracts.ethereum.event_listener import EthEventListener
from src.contracts.ethereum.multisig_wallet import MultisigWallet
from src.contracts.secret.... |
# Copyright (c) 2017 LSD - UFCG.
#
# 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 writin... |
from dis_snek import InteractionContext, slash_command
from ElevatorBot.commands.base import BaseScale
from ElevatorBot.core.misc.calculator import Calculator
class CalculatorCommand(BaseScale):
@slash_command(name="calculator", description="Summons a handy calculator")
async def calculator(self, ctx: Intera... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import torch
import to... |
""" FTPhub is an easy ftp management tool. """
__author__ = "Lukas Mahler"
__copyright__ = "(C) 2018-2019"
__version__ = "1.4.0"
__date__ = "05.07.2019"
__email__ = "lm@ankerlab.de"
__status__ = "Prototype"
###################################################################################################
#... |
import uuid
from django.test import SimpleTestCase
from corehq.util.es.elasticsearch import ConnectionError
from pillowtop.es_utils import initialize_index_and_mapping
from corehq.apps.export.esaccessors import get_case_export_base_query
from corehq.apps.export.export import get_export_documents
from corehq.apps.ex... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-24 21:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('suite', '0011_merge_20170221_0803'),
('suite', '0010_merge_20170221_0803'),
('suite'... |
import pytest
from ansiblelint import Runner
ROLE_TASKS_MAIN = '''
- name: shell instead of command
shell: echo hello world
'''
ROLE_TASKS_WORLD = '''
- command: echo this is a task without a name
'''
PLAY_IMPORT_ROLE = '''
- hosts: all
tasks:
- import_role:
name: test-role
'''
PLAY_IMPORT_ROLE_I... |
# Generated by Django 3.1.4 on 2021-03-06 11:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0023_add_choose_permissions'),
('home', '0003_booknowpage_cookiesettingspage'),
]
operatio... |
from src.db.database import SessionLocal
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
imp... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import collections
import contextlib
import itertools
import warnings
fro... |
import numpy as np
from fastgac import GaussianAccumulatorS2Beta, IcoCharts, MatX3d
from scipy.spatial.transform import Rotation as R
def setup_fastgac(normals:np.ndarray, level=4):
kwargs_s2 = dict(level=level)
# Create Gaussian Accumulator
ga_cpp_s2 = GaussianAccumulatorS2Beta(**kwargs_s2)
_ =... |
import matplotlib.pyplot as plt
from libpysal.weights.contiguity import Queen
import libpysal as lp
from libpysal import examples
import geopandas as gpd
import numpy as np
from pytest import raises, warns
from esda.moran import (Moran_Local, Moran, Moran_BV,
Moran_Local_BV, Moran_BV_matrix)
fr... |
# Generated by Django 3.2.7 on 2021-09-30 17:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0007_store_review'),
]
operations = [
migrations.DeleteModel(
name='CustomClass',
),
migrations.DeleteModel(
... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "knox_project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
from django.conf.urls import url
from . import views
app_name = 'ui'
urlpatterns = [
url(r'^signup$', views.signup, name='signup'),
url(r'^main$', views.landing, name='landing'),
url(r'^league/join$', views.league_join, name='league_join'),
url(r'^league/join/submit$', views.league_join_submit,
... |
from toontown.toonbase.ToonBaseGlobal import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from toontown.toonbase import ToontownGlobals
import cPickle
import ToonInterior
from direct.directnotify import DirectNotifyGlobal
from direct.fsm im... |
"""
Tests for the Audit Service integration:
- test the creation of presigned URL audit logs
- test the creation of login audit logs
- test the SQS flow
Note 1: there is no test for the /oauth2 endpoint: the /oauth2 endpoint
should redirect the user to the /login endpoint (tested in
`test_redirect_oauth2_authorize`), ... |
# -*- coding: utf-8 -*-
import os
import graphviz
import pytest
from ..testing_utils import make_ecommerce_entityset
@pytest.fixture()
def entityset():
return make_ecommerce_entityset()
def test_returns_digraph_object(entityset):
graph = entityset.plot()
assert isinstance(graph, graphviz.Digraph)
... |
import collections.abc
import typing
def is_generic37(as_class: typing.Type):
return isinstance(as_class, typing._GenericAlias) and as_class.__origin__ not in (
typing.Union, typing.ClassVar, collections.abc.Callable
)
_collection_types = [
collections.abc.Collection,
]
def is_collection37(as_... |
"""Key OpenMDAO classes can be imported from here."""
# Core
from openmdao.core.problem import Problem
from openmdao.core.group import Group
from openmdao.core.parallel_group import ParallelGroup
from openmdao.core.explicitcomponent import ExplicitComponent
from openmdao.core.implicitcomponent import ImplicitComponent... |
import os
import sys
# Append paths so that dependencies would work.
_FINDIT_DIR = os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
_THIRD_PARTY_DIR = os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'third_party')
_FIRST_PARTY_DIR = os.path.join(
os.path.dir... |
from django.conf import settings
from django.urls import include, path, re_path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from rest_framework.authtoken import views
from rest_framework_swa... |
# Copyright (c) 2015 Midokura SARL, All Rights Reserved.
# 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 requir... |
from keras import Model, Input
from keras.layers import Dense, Dropout, Embedding, Bidirectional, LSTM, Lambda, Concatenate, Permute, RepeatVector, Multiply, Flatten, Activation, Conv1D, MaxPooling1D
import numpy as np
from keras import regularizers
from keras.optimizers import Adam
def base_lstm_cnn_user(vocabulary_... |
#!/usr/bin/python
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import re
from ior_test_base import IorTestBase
from general_utils import get_log_file, run_task
#List of NVMe statistics
NVME_STATS = ['read_bytes',
'read_ops',
'write_byt... |
import code
from pprint import pprint
from grouper import models
from grouper.ctl.util import make_session
from grouper.graph import GroupGraph
def shell_command(args):
session = make_session()
graph = GroupGraph.from_db(session)
m = models
pp = pprint
try:
from IPython import embed
... |
# A Hero, No More (Mercedes)
medal = 1142336
if sm.canHold(medal):
sm.chatScript("You have earned a new medal.")
sm.startQuest(parentID)
sm.completeQuest(parentID) |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
#
# 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
# ... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import string
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOW
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Double url-encodes al... |
import hashlib
import hmac
import json
import uuid
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import scrypt
from Crypto.Util import Counter
from eth_keys import keys
from eth_utils import (
big_endian_to_int,
decode_hex,
encode_hex,
int_to_big_endian,
is_dict,... |
from os import system
import json
sett_file = open("sett.json", "r").read()
sett_json = json.loads(sett_file)
imagesrc = sett_json["photo"]
grayscaleimagesrc = sett_json["grayscale_photo_OUTPUT"]
asciiimagesrc = sett_json["ascii_photo_OUTPUT"]
firstReqCommand = sett_json["ConvertSett"]["firstReq"]
secondR... |
# -*- coding: utf-8 -*-
from django.db import models, transaction
from django.utils.translation import gettext_lazy as _
from markdownx.models import MarkdownxField
from reversion import revisions
from asylum.models import AsylumModel
class TokenType(AsylumModel):
label = models.CharField(_("Label"), max_length=... |
'''059 - MENU DE OPERAÇÕES
Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.'''
from time import sleep
numero1 = int(input('Digite um valor: '))
numero2 =... |
import jsonschema
from jsonschema import validate
class GithubConfSchema():
def __init__(self, schema):
self.schema = schema
def validate(self, data):
try:
validate(instance=data, schema=self.schema)
except jsonschema.exceptions.ValidationError:
return False
... |
# -*- encoding: utf-8 -*-
from .. import db
from .mobile_wallet import MobileWallet
class UPI(db.Model):
__tablename__ = "UPI"
ID = db.Column(db.String(45), primary_key = True, nullable = False)
ApplictionName = db.Column(db.String(45), nullable = False)
WalletIdentifier = db.Column(db.String(45)... |
# Copyright 2021 NVIDIA Corporation
#
# 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 wr... |
import os
import h5py
import numpy as np
from scipy.spatial.distance import pdist
from joblib import Parallel, delayed
from sklearn.preprocessing import normalize
# version for GPD
def read_skeleton_file(file_path):
skeleton_file = open(file_path)
lines = skeleton_file.readlines()
frame_count = int(lines[... |
import patcherex
import angr
import logging
from collections import defaultdict
from itertools import chain
import patcherex.cfg_utils as cfg_utils
from patcherex.patches import *
l = logging.getLogger("patcherex.techniques.malloc_ext_patcher")
class CfgError(Exception):
pass
class RegUsed(Exception):
pas... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd.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 ... |
"""This module defines the logic for the `/transaction` endpoint."""
import json
from urllib.parse import urlencode
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from django.shortcuts import render
from dj... |
import cv2
import numpy as np
# Load image
image = cv2.imread('/bala/projects/inoru/WheelVisualizer/storage/app/public/demo_cars/0777_cc1280_032_KH3.jpg', 0)
# Set our filtering parameters
# Initialize parameter settiing using cv2.SimpleBlobDetector
params = cv2.SimpleBlobDetector_Params()
# Set Area fi... |
import aiohttp
DOMAIN = 'hikvision'
class Hikvision(object):
def __init__(self, token, communityId):
"""Initialize device."""
self.name = '云眸社区'
self.token = token
self.communityId = communityId
@property
def device_info(self):
return {
"identifiers": ... |
#####################
# #
# shelltimeout.py #
# #
#####################
#
# A simple module for executing a command
# or executable from a shell, with a given
# time limit.
#
import subprocess
import time
import tempfile
def shrun(cmd, timeout_limit, use_exec=False, poll_inter... |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
from functools import reduce
from operator import sub, mul
from typing import Tuple, Union
Scalar = Union[int, float]
Vector = Tuple[Scalar, ...]
Matrix = Tuple[Vector, ...]
vector = tuple
def mult_vs(u: Vector, s: Scalar) -> Vector:
return vector(map(lambda x: s * x, u))
def mult_v(u: Vector) -> Scalar:
... |
import typing as t
import discord
from bot.api.api_client import ApiClient
from bot.api.base_route import BaseRoute
class UserRoute(BaseRoute):
def __init__(self, api_client: ApiClient):
super().__init__(api_client)
async def create_user(self, user_id: int, name: str, **kwargs):
json = {
... |
###############################################################################
##
## Copyright 2011-2013 Tavendo GmbH
##
## Note:
##
## This code is a Python implementation of the algorithm
##
## "Flexible and Economical UTF-8 Decoder"
##
## by Bjoern Hoehrmann
##
## bjoern@hoehrmann.de
## h... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/customization"
# docs_base_url = "https://[org_name].github.io/customization"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Cust... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.