content stringlengths 5 1.05M |
|---|
#Criar um programa que some, divida e multiplique e mostra os resultados ao final
n1 = int(input('Digite um numero:'))
n2 = int(input('Digite mais um numero:'))
n = n1 + n2
print('A soma entre {} e {} vale {}!'.format(n1, n2, n))
n = n1 * n2
print('A multiplicação entre {} e {} vale {}!'.format(n1, n2, n))
n = n1 / n2
... |
import os
import requests
import yaml
import re
import json
from pathlib import Path
compiled_models = []
preserved_keys = ["config_url", "applications", "download_url", "name", "description", "cite", "authors", "documentation", "tags", "covers"]
assert 'url' not in preserved_keys
models_yaml_file = Path(__file__).pa... |
# MIT License
#
# Copyright (c) 2018 Benjamin Bueno (bbueno5000)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... |
#! /usr/bin/python
# Filename: function2.py
# Description: This script is used to test function with parameters.
def funcWithParameter(a, b):
if a > b:
print 'max number is a =', a
elif a < b:
print 'max number is b=', b
else:
print 'equal'
x = 4
y = 8
funcWithParameter(x,y)
|
import discord
import update_demonlist as update
import commit_player_record as pcommit
import commit_player_record_list as plcommit
import commit_creator_record as ccommit
import delete_player_record as pdelete
import delete_creator_record as cdelete
import show_player_record as p
import show_creator_record as... |
def autoplot(server, dataset, parameters, start, stop, **kwargs):
"""Plot data from a HAPI server using Autoplot.
If not found, autoplot.jar is downloaded an launched. If found,
autoplot.jar is updated if server version is newer than cached version.
Example
-------
>>> from hapiclient... |
# Generated by Django 2.1.5 on 2020-07-24 05:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organization', '0002_service'),
]
operations = [
migrations.AlterField(
model_name='service',
name='ticket',
... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import random
import sys
p = argparse.ArgumentParser()
p.add_argument('-n', type=int, default=100)
p.add_argument('--seed', type=int, default=1234)
args = p.parse_args()
random.seed(args.seed)
sample = []
for index, line in enumerate(sys.std... |
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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 ... |
## @ingroup Methods-Missions-Segments-Common
# Aerodynamics.py
#
# Created: Jul 2014, SUAVE Team
# Modified: Jan 2016, E. Botero
# Jul 2017, E. Botero
# Aug 2021, M. Clarke
# ----------------------------------------------------------------------
# Imports
# --------------------------------------... |
# 2020.08.30
# maybe won't do leetcode tomorrow
# Problem Statement:
# https://leetcode.com/problems/unique-paths-ii/
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid[0])
n = len(obstacleGrid)
# check corner cases and do... |
import requests
from selenium import webdriver
driver = webdriver.Chrome()
import time
from bs4 import BeautifulSoup
counter = 0
total = 11
url = "https://www.soccerstats.com/homeaway.asp?league=england3"
data = requests.get(url,time.sleep(2))
soup = BeautifulSoup(data.content)
div = soup.find("div", id="h2h-team1"... |
class ColumnOrder:
# Enforce column order for relational table outputs
FORM_SPECIFICATIONS = [
'custom_form_id',
'custom_form_organizations',
'custom_form_class',
'custom_form_type_of_form',
'custom_form_name',
'custom_form_description',
'custom_form_heade... |
from django.db import models
from django.utils import timezone
from django.conf import settings
# Create your models here.
class Tag(models.Model):
""" Represents the Tag model """
title = models.CharField(max_length=200)
def __str__(self):
return self.title
def __repr__(self):
retur... |
import json
import boto3
client = None
def handler(event, context):
print('Received event:', json.dumps(event))
global client
if not client:
client = boto3.client('cognito-idp')
token = event['headers']['Auth']
res = client.get_user(AccessToken=token)
username = res['Username']
... |
from django.core.management.base import BaseCommand
from channels import Channel
import irc.bot
import irc.client
import irc.connection
import irc.buffer
import socket
import ssl
import logging
logging.getLogger('irc.client').setLevel(logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def flip(self, node):
if not node:
return None
hold_node ... |
#!/usr/bin/env python3
import os
import subprocess
import time
import json
configuration = {}
def executeTest(cluster, url, payload, rate, connections, duration, id, max_retries):
failures = 0
for tries in range(int(max_retries)):
process = subprocess.run(['./autobench', '-cluster', c... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import *
# Create database and create a shortcut
engine = create_engine('postgresql://catalog:password@localhost/catalog')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
... |
a = 1
j = "Less than ten" if a < 10 else "More than ten"
# j = "Less than ten"
|
import mock
from cStringIO import StringIO
from tornado import httpclient
from viewfinder.backend.base import testing
kURL = "http://www.example.com/"
class MockAsyncHTTPClientTestCase(testing.BaseTestCase):
def setUp(self):
super(MockAsyncHTTPClientTestCase, self).setUp()
self.http_client = testing.MockAs... |
from __future__ import annotations
from model.image.entity.subtag_condition import SubtagCondition
class VirtualTag:
def __init__(self, name: str) -> None:
self.name = name
self.subtags: list[VirtualTag.Subtag] = []
def add_subtag(self, subtag_name: str, subtag_condition: SubtagCondition) ->... |
# Generated by Django 2.2.4 on 2020-07-14 19:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('commerce', '0028_auto_20200710_1214'),
]
operations = [
migrations.AddField(
model_name='order',
name='reminder_sent... |
'''run.py - Joshua Wallace - Mar 2019
This is an example for how to run the simple_deblend code.
'''
import numpy as np
import sys, os
sys.path.insert(1,os.path.abspath('../src'))
import data_processing as dproc # one of the simple_deblend codes
def get_input_light_curves(list_of_ids,list_of_times,list_of_mags,li... |
#!/usr/bin/env python3
import argparse
import datetime
import sys
# XXX we're using more than one date format (one for arg, one for parsing), name is confusing
# this one is the date format used in the standard text file
DATEFMT = "%Y%m%dT%H%M%S"
def main():
cfg = _parse_args()
if cfg.date_min:
... |
from django.test import TestCase
from django.contrib.auth.models import User
from dwitter.models import Dweet
from dwitter.models import Comment
from django.utils import timezone
from datetime import timedelta
class DweetTestCase(TestCase):
def setUp(self):
user1 = User.objects.create(id=1, username="user... |
#
# Copyright (C) 2013, 2014 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
"""anyconfig globals.
"""
import logging
import os
AUTHOR = 'Satoru SATOH <ssat@redhat.com>'
VERSION = "0.0.5"
_LOGGING_FORMAT = "%(asctime)s %(name)s: [%(levelname)s] %(message)s"
def get_logger(name="anyconfig", log_format=_LOGGING_F... |
# _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2020/3/24.
↓↓↓ 权限组管理接口 ↓↓↓
"""
from app.libs.core import find_auth_module, get_ep_name
from app.libs.error_code import Success, NotFound, ForbiddenException
from app.libs.redprint import RedPrint
from app.libs.token_auth import auth
from app.models.base import db
fr... |
from django.urls import path
from apple import views
app_name = "apple"
urlpatterns = [
path(
"receipt-type-query/",
views.ReceiptTypeQueryView.as_view(),
name="receipt-type-query",
)
]
|
# coding: utf-8
import time
import random
import os
import json
import re
import sys
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'rsyncd'
def getInitDTpl():
path = getPluginDir() + "... |
#!/usr/bin/env python
from setuptools import setup, find_packages
def readme():
with open('README.rst') as f:
return f.read()
setup(name='cabot-alert-rocketchat',
version='0.1.2',
description='A RocketChat alert plugin for Cabot',
long_description=readme(),
license='MIT',
au... |
import torch
def get_device(verbose=True):
torch.cuda.is_available()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
if verbose: print('Torch running on:', device)
return device
def to_numpy(x):
return x.detach().cpu().numpy()
def to_torch(x, devi... |
#!/usr/bin/env python
import time
from datetime import datetime
from datetime import timedelta
from datetime import date
import sys
import threading
import RPi.GPIO as GPIO
import Adafruit_DHT
from Adafruit_LED_Backpack import SevenSegment
import holidays
us_holidays = holidays.US()
holiday_list = [
'New Year\'s ... |
import numpy as _onp
from numpy import pi as _pi
_deg2rad = 180. / _pi
_rad2deg = _pi / 180.
def degrees(x):
"""Converts an input x from radians to degrees"""
return x * _deg2rad
def radians(x):
"""Converts an input x from degrees to radians"""
return x * _rad2deg
def sind(x):
"""Returns the ... |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
sentinel =... |
from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient
from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry, Region
from msrest.authentication import ApiKeyCredentials
import time
import os
def main():
from dotenv im... |
#!/usr/bin/python
import argparse
import json
import re
import readline
import requests
import sys
import time
from utils import *
from attacks import *
class GraphQLmap(object):
author = "@pentest_swissky"
version = "1.0"
endpoint = "graphql"
method = "POST"
args = None
url = None
d... |
import numpy as np
import torch
import torch.nn as nn
from utils.transforms import outer_product
VERY_SMALL_NUMBER = 1e-16
def noise_like(tensor, noise_type, noise, label_slices=None):
if noise_type == 'expand':
noise_tensor = randn_like_expand(tensor, label_slices, sigma1=noise)
elif noise_type == ... |
from pypika import analytics as an
from pyspark.sql import functions as F
ENGINE = "spark"
agg_mapping = {
"min": {"spark": F.min, "sql": an.Min},
"max": {"spark": F.max, "sql": an.Max}
}
funcs = [F.min, F.max, F.stddev, F.kurtosis, F.mean, F.skewness, F.sum, F.variance]
class Agg:
@staticmethod
de... |
# -*- coding: utf-8 -*-
"""VIF calculation."""
from wildfires.analysis import vif
from ..cache import cache
@cache
def calculate_vif(X):
"""Calculate the VIF."""
return vif(X, verbose=True).set_index("Name", drop=True).T
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
import rclpy
import numpy as np
from rclpy.qos import QoSDurabilityPolicy
from rclpy.qos import QoSHistoryPolicy
from rclpy.qos import QoSProfile
from rclpy.qos import QoSReliabilityPolicy
from rclpy.node import Node
from rclpy.parameter import Parameter
impo... |
import basevcstest
class TestVCSBoxfill(basevcstest.VCSBaseTest):
def boxfillProjection(self, projection, zoom):
a = self.clt("clt")
self.x.clear()
p = self.x.getprojection(projection)
b = self.x.createboxfill()
b.projection = p
if zoom is None:
self.x.... |
"""
This script reads the original labels of Cityscapes (CO) and compares them against
the Cityscapes-Panoptic-Parts (CPP) labels. It verifies that the semantic and instance
level labels of Cityscapes Panoptic Parts (CPP) are equivalent to
original Cityscapes (CO), i.e., sids_iids_CPP == sids_iids_CO.
"""
import sys
as... |
# Copyright 2012 NetApp. All rights reserved.
# Copyright (c) 2015 Tom Barron. 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.or... |
# Copyright (c) 2013 Alon Swartz <alon@turnkeylinux.org>
#
# This file is part of ec2metadata.
#
# ec2metadata is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# opt... |
"""
Test basic functionality for loading datasets.
"""
import pytest
import numpy as np
import numpy.testing as npt
from ..datasets import load_japan_quakes, load_earth_relief
from ..exceptions import GMTInvalidInput
def test_japan_quakes():
"Check that the dataset loads without errors"
data = load_japan_qua... |
class Solution:
def reverseWords(self, s: str) -> str:
"""
Given an input string, reverse the string word by word.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
"""
# side case
i = 0
flag = True
for i in ... |
from flask import Flask, request
from werkzeug.routing import BaseConverter
app = Flask(__name__)
# 自定义转换器
class MobileConverter(BaseConverter):
"""自定义手机号转换器"""
regex = r'1[3-9]\d{9}'
# 注册自定义转换器
app.url_map.converters['mobile'] = MobileConverter
# 路径参数
@app.route('/users/<int(min=1):user_id>')
def login(... |
'''Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu indice de massa corporal(IMC)
e mostre seu status, de acordo com a tabela abaixo:
- IMC abaixo de 18,5: Abaixo do peso
- Entre 18,5 e 25: Peso Ideal
- 25 até 30: Obesidade
- Acima de 40: Obesidade mórbida'''
# weight - peso em english
weigh... |
from tkinter import Tk, Label, Button, messagebox
import random
rickyism = ["Fuck you, Lahey!", "allow me to play doubles advocate here for a moment. ",
"For all intensive purposes I think you are wrong.",
"you all seem to be taking something very valuable for granite.",
"Gettin' tw... |
from enum import Enum
import datetime
class FlightInfoMode(Enum):
DEPARTURE = 1
ARRIVAL = 2
class FlightType(Enum):
NATIONAL = 1
INTERNATIONAL_DESTINY = 2
INTERNATIONAL_ORIGIN = 3
class Weather:
def __init__(self, min, max, description):
self.min = min or '-'
self.max = ma... |
def longest_substring_util(s: str, start: int, end: int, k: int) -> int:
if end < k:
return 0
# will hold the occurrences of each character in the string
# counter = Counter(s)
count_map = [0] * 26
# build the count map which will contain the occurrences of each character in the string
... |
# -*- coding: utf-8 -*-
"""API blueprint and routes."""
from functools import partial
from flask import Blueprint, abort, jsonify, request
import bioregistry
from .utils import (
_autocomplete,
_get_identifier,
_normalize_prefix_or_404,
_search,
serialize,
)
from .. import normalize_prefix
from... |
"""
K Closest Point to Origin
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k,
return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the a... |
#!/usr/bin/env python3
#This sample demonstrates setting fan speed according to CPU temperature.
#Install RC Driver HAT library with "pip3 install turta-rcdriverhat"
from time import sleep
from turta_rcdriverhat import Turta_IMU
from turta_rcdriverhat import Turta_RCDriver
#Initialize
imu = Turta_IMU.IMU()
rc = Turt... |
import sys
sys.path.append('..')
from scrython.foundation import FoundationObject
import aiohttp
import asyncio
import urllib.parse
from threading import Thread
class CardsObject(FoundationObject):
"""
Master class that all card objects inherit from.
Args:
format (string, optional):
De... |
from django.test import Client, TestCase
from posts.models import Group, Post, User
class PostModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='Igor')
self.user_client = Client()
self.user_client.force_login(self.user)
self.test_post = Post.obje... |
import numpy
def bubblesort(array):
for i in range(len(array)):
for k in range(0, len(array) - i - 1):
if array[k] > array[k + 1]:
array[k], array[k + 1] = array[k + 1], array[k]
return array
def main():
print("**Bubblesort**")
randarray = list(numpy.random.randin... |
def get_model():
from django_comments.models import Comment
return Comment
def get_form():
from extcomments.forms import CommentForm
return CommentForm
|
import numpy as np
import matplotlib.pyplot as plt
import corner
nbuilt = 30000
mcmc = np.loadtxt("../data/mcmc.txt")
ntheta = mcmc.shape[1]
#fig = plt.figure()
corner.corner(mcmc[nbuilt:, 1:])
plt.show() |
from .intelligent_system_group_dataset_reader import IntelligentSystemGroupDatasetReader
from .survey_dataset_reader import SurveyDatasetReader
|
# Тема 2. Тип данных СПИСОК (list)------------------------
# ------------------------------------------
print('--------------------------------------Тема 2. Тип данных СПИСОК (list)----------------------------------------')
print('-----------------------------------------------------------------------------------------... |
def scoreBianka(inp):
if inp == "WWW": return 2
if inp == "BBB": return 0
if inp.count("B") == 2 or inp.count("W") == 2: return 1
def scoreWilliams(inp):
if inp == "WWW": return 2
if inp == "BBB": return 0
if inp.count("B") == 2: return 0
if inp.count("W") == 2: return 2
def winner(bianka, williams):
if biank... |
#!/usr/bin/env python3
from sys import argv
import argparse
import UPhO
def main():
usage = u"""
\t\t\u26F1 \u001b[31;1m newick2json.py \u001b[0m \u26F1
\n
Convert your newick file in hierafchichal json format.
This script is written for python3 and requires the corresponding version of UPhO (https://g... |
"""
Auxiliary functions for accessing the logging information generated by the
Test Application Server (TAS).
"""
#################################################################################
# MIT License
#
# Copyright (c) 2018, Pablo D. Modernell, Universitat Oberta de Catalunya (UOC),
# Universidad de la Republi... |
import cv2
import face_recognition
import os
SMALLEST_DISTANCE_THRESHOLD = 2
NO_RECOGNITION = SMALLEST_DISTANCE_THRESHOLD + 1
class FaceRecognition(object):
def __init__(self, face_detector, known_face_path):
self.face_detector = face_detector
self.known_face_path = known_face_path
self.... |
#!/usr/bin/env python
import math, os, sys, random
try:
from optparse import OptionParser
except:
from optik import OptionParser
def main():
(instar,output) = parse_command_line()
g = open(instar, "r")
instar_line=g.readlines()
o1=open(output,"w")
mline0=judge_mline0(instar_line)
mline1=judge_mline1(mline0,i... |
from authx.database.mongodb import MongoDBBackend
from authx.database.redis import RedisBackend
"""
This is the database module, which contains the database class, also a cache class.
"""
__all__ = ["MongoDBBackend", "RedisBackend"]
|
import click
import grab
PREFIX = "GRAB"
path_message = (
"A path is required, set system variable 'export GRAB_PATH=/path/to/code' or pass in the path using "
"the '--path' keyword"
)
@click.group(
invoke_without_command=False,
context_settings={
"help_option_names": ["-h", "--help"],
... |
from django.core.management.base import BaseCommand
from django.db import models, transaction
from typing import Any, Optional
from api.apps.users.models import User
from api.apps.users.factory import (AdminUser,
AdminProfile,
ActiveUser,
... |
# (C) Datadog, Inc. 2019
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# 1st party.
import argparse
import re
# 3rd party.
from tuf.exceptions import UnknownTargetError
# 2nd party.
# 2nd party.
from .download import REPOSITORY_URL_PREFIX, TUFDownloader
from .exceptions import No... |
from werkzeug.contrib.cache import SimpleCache
class BasicCache:
cache = SimpleCache()
def set(self, key, value):
self.cache.set(key, value, timeout=50 * 1000)
def get(self, key):
return self.cache.get(key=key)
|
import unittest
from pymocky.models.header_matcher import HeaderMatcher
class HeaderMatcherTests(unittest.TestCase):
def test_dict_headers(self):
headers = {
"Content-Type": "application/json",
"Content-Length": "123",
}
other_headers = {
"Content-Type... |
# coding=utf-8
import sys
if sys.version_info > (3, 0):
from html2jirawiki.html2jirawiki import html_to_jira_wiki, ATX, ATX_CLOSED
else:
from html2jirawiki import html_to_jira_wiki, ATX, ATX_CLOSED
|
def coords2display(p,
valbounds=[-46.702880859375, -23.569022144054955, \
-46.69189453125, -23.57405696664267],
imgsize=[512, 256]):
pnormalized = [(p[0] - valbounds[0]) / (valbounds[2]-valbounds[0]),
(p[1] - valbounds[1]) / (val... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
class RequestExceededError(Exception):
pass
|
from flask import Blueprint
bp = Blueprint('dashboard', __name__, template_folder='templates')
from pugsley.dashboard import routes
|
import os
import importlib
import globals as G
for f in os.listdir(G.local + "/mods/mcpython/Commands"):
if os.path.isfile(G.local + "/mods/mcpython/Commands/" + f) and not f in [
"__init__.py"
]:
name = f.split(".")[0]
locals()[name] = importlib.import_module("Commands." + name)
|
# Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... |
"""Some plot."""
import random
import matplotlib.pyplot as plt
import numpy as np
def main():
"""Go Main Go."""
(fig, ax) = plt.subplots(1, 1)
x = []
y = []
cnts = []
data = []
for i in range(250):
x.append(i)
data.append(random.randint(0, 100))
std = np.std(data)... |
from python_specific_patterns.prebound_method_pattern.random import random, set_seed
print(set_seed(100))
print(random())
|
from sqlalchemy import Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import relationship
from app.db.base_class import Base
class Like(Base): # type: ignore
__tablename__ = 'like'
id = Column(Integer, primary_key=True, index=True)
post_id = Column(Integer, ForeignKey('post.id', ondelet... |
from rest_framework import serializers
from .models import Post
from django.contrib.auth.models import User
class PostSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'text', 'author', 'image', 'pub_date')
model = Post
read_only_fields = ['author'] |
from iclientpy.rest.apifactory import iManagerAPIFactory
from iclientpy.rest.api.node_service import NodeService
import requests
from urllib.parse import quote
import logging
logger = logging.Logger(__name__)
class MsgHandler:
def __init__(self, user_access_imgr_url, url, user, password, factory_kls = ... |
"""
General user access control methods
"""
from typing import Optional
from sni.user.models import Group, User
# pylint: disable=too-many-return-statements
def is_authorized_to_login(usr: User) -> bool:
"""
Tells wether a user is authorized to login or not. A user is authorized to
login if the followin... |
import cv2 as cv
face_cascade = cv.CascadeClassifier('haarcascade_frontalcatface_extended.xml')
image = cv.imread('enes.png')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(image=gray, scaleFactor=1.02, minNeighbors=2, minSize=(200, 200))
for (x, y, width, height) in faces :
... |
'''
- DESAFIO 056
- Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa mostre:
- A média de idade do grupo.
- Qual é o nome do homem mais velho.
- Quantas mulheres tem menos de 20 anos
'''
soma_idade = 0
media_idade = 0
maior_idade_homem = 0
nome_mais_velho = ''
totmulher20 ... |
DEBUG = True
SECRET_KEY = 'dev'
|
# allennlp train config.json -s res --include-package packages --force
from typing import Iterator, List, Dict
import torch
import torch.optim as optim
import numpy as np
import pandas as pd
from allennlp.data import Instance
from allennlp.data.fields import TextField, SequenceLabelField
from allennlp.data.dataset_read... |
#!/usr/bin/env python
import sys
import os
import subprocess
import string
import time
import datetime
import shutil
import stat
#import utils
if len(sys.argv) != 4:
print ("input params error!")
os._exit(1)
src_media_url=sys.argv[1]
trans_profile=sys.argv[2]
dst_format=sys.argv[3]
FFM... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 11:25:48 2018
@author: 89288
"""
import pymongo
class DataArranger():
def __init__(self):
'''
链接数据库
'''
self.client = pymongo.MongoClient('localhost',27017)
self.database = self.client.MultiThread
... |
import time
import numpy as np
from fuzzer.lib.queue import FuzzQueue
from fuzzer.lib.queue import Seed
class ImageInputCorpus(FuzzQueue):
"""Class that holds inputs and associated coverage."""
def __init__(self, outdir, israndom, sample_function, cov_num, criteria):
"""Init the class.
Args:... |
import pytest
@pytest.fixture()
def mongodb_with_members(mongo_testdb):
mongo_testdb["members"].insert_many(
[
{
"_id": 1,
"name": "Duong Thai Minh",
"codeforces_handle": "I_UsedTo_Love_You",
"codeforces": {
"h... |
#
# Copyright (c) 2020 Juniper Networks, Inc. All rights reserved.
#
import logging
from vnc_api.vnc_api import FlowNode
from vnc_api.vnc_api import GlobalSystemConfig
from vnc_api.vnc_api import Project
from vnc_cfg_api_server.tests import test_case
logger = logging.getLogger(__name__)
class TestFlowNode(test_cas... |
# coding=utf-8
class Test:
def class_func(self, p):
# self代表的是类的实例对象
print self # <__main__.Test instance at 0x01D98E40>
print self.__class__ # __main__.Test
print p
t = Test()
t.class_func("p") |
print('{:^20}'.format('BRASILEIRÃO 2019'))
classificacao = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo', 'Internacional',
'Corinthians', 'Fortaleza', 'Goiás', 'Bahia', 'Vasco da Gama', 'Atlético-MG', 'Fluminense',
'Botafogo', 'Ceará', 'Cruzeiro', 'CSA', 'Ch... |
from asyncio import CancelledError
from contextlib import suppress
from typing import AsyncIterator, Callable, Iterator
from uuid import uuid4
import aiobotocore
import pytest
from aiobotocore.client import AioBaseClient
from localstack.services import infra
from pytest_lazyfixture import lazy_fixture
from src.room_... |
import pandas as pd
def a_function(foo):
""" A function
Args:
foo (integer) : foo
Returns:
bar (integer) : bar
"""
return 1 |
import PyWave
import pytest
@pytest.fixture
def wf():
PATH = "path/to/a/wave/file.wav"
wavefile = PyWave.open(PATH)
yield wavefile
wavefile.close()
def test_read(wf):
wfile = wf.read(1)
assert wf is not None
assert isinstance(wf, object)
# due to the read(1) we should have a warning... |
from wtpy.monitor import WtMonSvr
svr = WtMonSvr(deploy_dir="E:\\deploy")
svr.run(port=8099, bSync=False)
input("press enter key to exit\n") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.