content
stringlengths
5
1.05M
n = int(input()) a = list(map(int, input().split())) sm = sum(a)//(n//2) l = [] for i in range(n): for j in range(i+1, n): if a[i]+a[j] == sm and i+1 not in l: l.append(i+1) l.append(j+1) break for i in range(0,len(l), 2): print(l[i], l[i+1])
from __future__ import ( absolute_import, unicode_literals, ) import re from typing import ( AbstractSet, Any, Dict, List, Mapping, MutableMapping, Tuple, Type, Union, ) from pyparsing import ( And, Literal, MatchFirst, Optional, Or, ParserElement, ...
class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: """ Approach: 1.descrease trust for person1 and increase trust for person2 2.if there is a judge, trust count must be equals to n-1(everyone except judge) Time complexity O(N) ...
from django.contrib import admin from metaci.repository.models import Branch from metaci.repository.models import Repository from metaci.plan.models import PlanRepository class BranchAdmin(admin.ModelAdmin): list_display = ("repo", "name") admin.site.register(Branch, BranchAdmin) class PlanRepositoryInline(ad...
from fabric.api import * def Install(): run('git clone https://github.com/JotaGalera/FindAInformatic') with cd("~/FindAInformatic/"): run('make') def Start(): with cd("~/FindAInformatic/"): run('sudo gunicorn --bind 0.0.0.0:80 application:app') run('pgrep gunicorn > ~/id.tx') #Para asegurarnos que t...
import torch import torch.nn as nn import torch.nn.functional as F import gc import time import json import sys import gc import numpy as np import os from datetime import datetime import pytorch3d from pytorch3d.structures import Meshes from pytorch3d.io import load_obj from pytorch3d.ops import sample_points_from_me...
"""CLI scripts."""
# -*- coding: utf-8 -*- """ .. moduleauthor:: Mark Hall <mark.hall@mail.room3b.eu> """ from csv import DictReader from io import TextIOWrapper from nose.tools import eq_ from pkg_resources import resource_stream def full_test(): reader = DictReader(TextIOWrapper(resource_stream('pycaptioner', 'test/data/points.c...
from day11 import part1, part2 test_input = """5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526""".splitlines() def test_part1(): assert part1(test_input) == 1656 def test_part2(): assert part2(test_input) == 195
from SimPEG import Utils, np from scipy.constants import mu_0, epsilon_0 from SimPEG.EM.Utils.EMUtils import k def getKc(freq,sigma,a,b,mu=mu_0,eps=epsilon_0): a = float(a) b = float(b) # return 1./(2*np.pi) * np.sqrt(b / a) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a)) return np.sqrt(b / a) * np.exp(-1j*k(...
''' Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 明显是一个动态规划问题, 当然有一些技巧性方法,比如: 1 3 3 1 0 + 0 1 3 3 1 = 1 4 6 4 1 ''' class Solution: def generate(self, numRows): """ :typ...
import unittest from cnc.gcode import * class TestGCode(unittest.TestCase): def setUp(self): self.default = Coordinates(-7, 8, 9, -10) def tearDown(self): pass def test_constructor(self): # GCode shouldn't be created with constructor, but since it uses # in...
import tvm import tvm.micro def targetIsARM(target): return target.attrs["mcpu"] == "armv6-m" def targetIsRISCV(target): return target.attrs["mcpu"] == "rv32gc" class Compiler_Ext(tvm.micro.DefaultCompiler): def _autodetect_toolchain_prefix(self, target): if targetIsARM(target): retu...
""" # test_config_gunicorn """ import logging import unittest import mock import ml.config_gunicorn as config_gunicorn class ConfigGunicornTester(unittest.TestCase): """ ConfigGunicornTester includes all unit tests for ml.config_gunicorn module """ @classmethod def teardown_class(cls): l...
import heapq from collections import deque from typing import List class Solution1: def max_result(self, nums: List[int], k: int) -> int: q = deque(([(0, nums[0])])) ret = nums[0] for i in range(1, len(nums)): while q and q[-1][0] < (i - k): q.pop() ...
import copy from cumulusci.robotframework import locators_52 lex_locators = copy.deepcopy(locators_52.lex_locators) lex_locators["object_list"] = { # Note: this matches the <td> with the checkbutton, not the inner checkbutton # This is because clicking the actual checkbutton will throw an error that # ano...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from netests.constants import NOT_SET as NSET from netests.protocols.lldp import LLDP, ListLLDP def _napalm_lldp_converter( hostname: str(), cmd_output: json, options={} ) -> ListLLDP: lldp_neighbors_lst = ListLLDP( lldp_neighbors_ls...
from __future__ import absolute_import from dataverse.settings.defaults import * # noqa try: from dataverse.settings.local import * # noqa except ImportError as error: pass
"""An example of unit tests based on pytest.""" from .demo import add def test_add() -> None: """Test add.""" assert add([1, 2, 3]) == 6
"""seed databases and allow nullable password_hash Revision ID: 5818f4679595 Revises: 4b61e9319ad9 Create Date: 2021-09-08 14:27:33.384835 """ from alembic import op import sqlalchemy as sa from datetime import datetime import uuid # revision identifiers, used by Alembic. revision = "5818f4679595" down_revision = "...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Stub functions that are used by the AWS Organizations unit tests. When tests are run against an actual AWS account, the stubber class does not set up stubs and passes all calls through to the Boto3 client. "...
#!/usr/bin/python3 import pathlib import os import subprocess import yaml FILENAME = 'xmake.yml' CONFIG = '.git' OUTDIR = '.out' def repo_abs_path(): d = pathlib.Path.cwd() while not (d / CONFIG).exists(): d = d.parent return d def curr_rel_path(): d = pathlib.Path.cwd() return d.relat...
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 9 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class HdfsInotifySettingsSetting...
# system import logging import subprocess # local from ..config import LoadedConfig from ..executable import Executable from ..projects import Projects from ..rootkit import Rootkit, prefix_path_mnt from ..subcommand import SubCommand class ConfCopyCommand(SubCommand): """kiwi conf-copy""" def __init__(self...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Variab...
#!/usr/bin/env python import os.path import logging import locales _ = locales._ from gui_image_opener import toAbsPath, getBackground PATH_BACKGROUNDS = toAbsPath('backgrounds/gif') pattern_fn = 'irka3_{fld}{scheme}.fld' TITLE_BORDER = _("BG Border") TITLE_TOUCHED = _("BG Touched") TITLE_UNTOUCHED = _("BG Untouc...
x = input( "enter number:") sroot = x ** 2 print sroot
import pygame class Button(pygame.sprite.Sprite): def __init__( self, id_: int, image_path: str, rect: pygame.Rect, color: pygame.Color, highlight_color: pygame.Color, text: str, font_size: int, text_color: pygame.Color, highlight_text_color: pygame.Color = None ): """Initialize the...
from sklearn.metrics import accuracy_score, precision_recall_fscore_support import numpy as np import torch def tc_compute_metrics(pred): labels = pred.label_ids preds = pred.predictions.argmax(-1) precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary') simple_accur...
from .gathering_env import GatheringEnv import torch class SingleAgentGatheringEnv(GatheringEnv): def __init__(self, cfg): assert cfg.no_agents == 1, "Config not configured for 1 agent." super(SingleAgentGatheringEnv, self).__init__(cfg) def reset(self): self._record_ep = False ...
#!/usr/bin/env python import sys sys.path.append('/opt/lib/python2.7/site-packages/') import math import numpy as np import pylab import nest import nest.raster_plot import nest.topology as tp nest.ResetKernel() nest.SetKernelStatus({'local_num_threads': 8}) a = { "tau_m" : 20.0, "V_th" : -55.0, "E_...
class Solution: def maxNumberOfBalloons(self, text: str) -> int: d = Counter(text) return min(['b'], d['a'], d['l']//2, d['o']//2, d['n'])
""" table object reference count """ a="nyc" b="nyc" print(a) a=123 print(a) print(b) b=456 print(b) c='nyc' d=c print(c==d) print(d is c)
from unittest import mock, main, TestCase from api.handlers import HttpHandlers class TestHttpHandlers(TestCase): "test class for HttpHandlers" def test_valid_visits_1(self): "succesfully call the endpoint, key has not yet been setup in Redis" m_redis_client = mock.MagicMock() m_redis...
import pytest import anthpy.strings @pytest.mark.parametrize("input_str,expected", [ ("/path/to/file.txt", ["/path/to", "file", ".txt"]), ("file.txt", ["", "file", ".txt"]), ("/path/file", ["/path", "file", ""]), ("", ["", "", ""]), ]) def test_file_parts(input_str, expected): assert expected == a...
from __future__ import print_function, division, absolute_import """ Physics Routines for aporbit ============================ """ import numpy as np import aphla as ap from PyQt4.QtCore import QObject, Qt, QSettings, QSize, QThread, SIGNAL from PyQt4.QtGui import QApplication, QBrush, QMdiArea, QMessageBox, QPen, Q...
""" Contains the QuantumCircuit class boom. """ class QuantumCircuit(object): # pylint: disable=useless-object-inheritance """ Implements a quantum circuit. - - - WRITE DOCUMENTATION HERE - - - """ def __init__(self): """ Initialise a QuantumCircuit object """ pass def add_ga...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('music', '0001_initial'), ] operations = [ migrations.CreateModel( name='Song', fields=[ ...
def exec_after_process(app, inp_data, out_data, param_dict, tool, stdout, stderr): for name,data in out_data.items(): if name == "seq_file2": data.dbkey = param_dict['dbkey_2'] app.model.context.add( data ) app.model.context.flush() break
import yaml from box import Box def load_config(fp): return Box(yaml.load(open(fp, 'r').read()))
"""The action definition for the SysML toolbox.""" from gaphas.item import SE import gaphor.SysML.diagramitems as sysml_items import gaphor.UML.diagramitems as uml_items from gaphor import UML, diagram from gaphor.core import gettext from gaphor.diagram.diagramtoolbox import ToolboxDefinition, ToolDef from gaphor.dia...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
import unittest from luna.datatypes.dimensional import DataTimeSeries, DataTimePoint, PhysicalDataTimePoint, PhysicalDataTimeSlot, StreamingDataTimeSeries from luna.datatypes.dimensional import * from luna.common.exceptions import InputException, StorageException from luna.spacetime.time import dt, TimeSlotSpan from lu...
MASTEMA = 2151009 sm.setSpeakerID(MASTEMA) if not sm.canHold(1142556): sm.sendNext("Please clear some space in your equip inventory.") sm.dispose() sm.sendNext("You made it back, #h #! How are you?") sm.flipDialoguePlayerAsSpeaker() sm.sendSay("I didn't know I had such anger within me. It is not easy to con...
""" Virtual Namespace for 3rd party openaps contributions """ from pkg_resources import declare_namespace from pkgutil import extend_path __path__ = extend_path(__path__, __name__) declare_namespace(__name__)
import itertools import json import math import os import random import sys import time from matplotlib.colors import to_hex from shapely.geometry import Point, Polygon import matplotlib.pyplot as plt import numpy as np PROBLEM_FILEDIR = "problems" SOLUTION_FILEDIR = "solutions" sys.setrecursionlimit(1000000) def ...
from __future__ import unicode_literals from django.db import models from sortedm2m.fields import SortedManyToManyField from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): re...
# Generated by Django 3.0.6 on 2020-10-18 14:50 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(pri...
import math from typing import Tuple, Union, Optional import torch from torch import nn from torch import Tensor from flambe.compile import registrable_factory from flambe.nn.module import Module class Embeddings(Module): """Implement an Embeddings module. This object replicates the usage of nn.Embedding ...
#!/usr/bin/env python3 #coding=utf8 from . import * from collections import namedtuple as _nt Texture2d = _nt('Texture2d', 'format width height miplevels') def texture2d(factory): fmt = u32(factory) w = u32(factory) h = u32(factory) n = u32(factory) mips = n * [None] for i in range(n): dsize = u32(factory) ...
# Copyright [2020] [Toyota Research Institute] # # 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 agre...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from .ip...
''' Created on 2017年1月8日 @author: Think 【程序15】 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,    60分以下的用C表示。 1.程序分析:(a>b)?a:b这是条件运算符的基本例子。 2.程序源代码: 不支持这个运算符 ''' from pip._vendor.distlib.compat import raw_input def jcp015(): score = int(raw_input('input score:\n')) if score >= 90: grade = 'A' e...
import tweepy, requests from credentials import * def create_api(): """Creates api object from tweepy using api auth credentials. """ auth = tweepy.OAuthHandler(api_key, secret_key) auth.set_access_token(access_token, access_token_secret) return tweepy.API(auth) def retrieve_tweet(api_object...
from ..distance_metrics import levenshtein_distance, hamming_distance from ..exceptions import DistanceMetricError class PhoneticAlgorithm: """ The main Phonetic Algorithm class, to ensure a unified API for all the included algorithms. """ def __init__(self): self.distances = { ...
# -*- coding: utf-8 -*- # Author: jS1ngle # License: MIT License (http://opensource.org/licenses/MIT) import pandas as pd import requests import matplotlib.pyplot as plt from pytrends.request import TrendReq import datetime from datetime import timedelta from scipy.stats.stats import pearsonr from SimulationHelperFunc...
from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.template import loader from .models import Question def index(request): ultima_questao_lista = Question.objects.order_by('data_publicacao')[:5] template = loader.get_template('polls/index.html') context = { 'ul...
# Copyright 2019 The TensorNetwork 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 ...
#! /usr/bin/env python import json, sys import ddlib # Load the ddlib Python library for NLP functions # For each input row for line in sys.stdin: # Load the JSON object row = json.loads(line) # Output data print json.dumps(row)
import numpy as np red = np.array((1., 0, 0, 1.),'f4') orange = np.array((1., 0.498, 0, 1),'f4') yellow = np.array((1, 1, 0, 1.),'f4') green = np.array((0, 1, 0, 1.),'f4') cyan = np.array((0, 1., 1., 1.),'f4') blue = np.array((0, 0, 1., 1.),'f4') purple = np.array((1., 0, 1., 1.),'f4') white = np.array((1.,1,1,1),'f4'...
from unittest.mock import patch from nose.tools import ok_, eq_, raises from moncli import MondayClient, entities as en from moncli.enums import BoardKind USERNAME = 'test.user@foobar.org' GET_ME_RETURN_VALUE = en.User(**{'creds': None, 'id': '1', 'email': USERNAME}) @patch.object(MondayClient, 'get_me') @patch('mo...
import sys import antlr3 import antlr3.tree from LangLexer import LangLexer from LangParser import LangParser from LangDumpDecl import LangDumpDecl cStream = antlr3.FileStream(sys.argv[1]) lexer = LangLexer(cStream) tStream = antlr3.CommonTokenStream(lexer) parser = LangParser(tStream) r = parser.start() print "tree: ...
import subprocess player = "vlc" returncode = subprocess.call(["which", "omxplayer"]) if returncode == 0: player = "omx" def play(path): if player == "vlc": subprocess.Popen(["cvlc", "--fullscreen", path]) elif player == "omx": subprocess.Popen(["omxplayer", path]) pass
import os OVERPASS = "https://overpass-api.de/api/interpreter/" DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(DIR, 'data') CACHE_DIR = os.path.join(DATA_DIR, 'cache') GEOMETRY_DIR = os.path.join(DATA_DIR, 'geometry') SPLIT_SIZE = 1.5 # optimal value for countries
"""Generate and work with PEP 425 Compatibility Tags. copied from pip-20.3.1 pip/tests/unit/test_utils_compatibility_tags.py download_url: https://raw.githubusercontent.com/pypa/pip/20.3.1/tests/unit/test_utils_compatibility_tags.py Copyright (c) 2008-2020 The pip developers (see AUTHORS.txt file) Permission is here...
from .models import * from app import CONFIG, app from flask import escape import copy from flask_login import current_user from werkzeug.utils import secure_filename import os import requests def form_to_event_object(form): eventData = {} eventData['title'] = escape(form.title.data) eventData['description'] = esca...
# MIT License # # Copyright (c) 2021 MrMat # # 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, modify, merge, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exchange_portal', '0002_auto_20170124_1858'), ] operations = [ migrations.AddField( model_name='school', ...
from django import forms from django.utils.translation import ugettext_lazy as _ from pretix.base.forms import SettingsForm class PublicRegistrationsForm(SettingsForm): public_registrations_items = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={'class': 'scrolling-multi...
import os from flask import Flask class ReverseProxied(object): '''Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind this to a URL other than / and to an HTTP scheme that is different than what is used locally. In nginx: ...
""" Test helpers. """ from xenserver.models import ( AddressPool, Project, Template, XenServer, XenVM, Zone) from xenserver.tests.fake_xen_server import FakeXenServer HOST_MEM = 64*1024 HOST_CPUS = 16 VM_MEM = 2048 VM_CPUS = 1 VM_DISK = 10240 DEFAULT_SUBNET = "192.168.199.0/24" DEFAULT_GATEWAY = "192.168.199.1" ...
# Apache License Version 2.0 # Copyright 2022 Xin Huang # # 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...
''' This is a multi-line comment Try making one at the end of the code file The IDE (this window) tries to help by adding the ending triple quotes automatically ''' #add code below this line print("Red") print("Orange") #the comment STARTS at the hash symbol #print("Yellow"); print("Green") print("Blue") print("I...
from __future__ import absolute_import from __future__ import division import time import logging import os import sys import numpy as np import tensorflow as tf from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import embedding_ops from evaluate import exact_match_score, f1_score fro...
"""Support for Litter-Robot switches.""" from homeassistant.helpers.entity import ToggleEntity from .const import DOMAIN from .hub import LitterRobotEntity class LitterRobotNightLightModeSwitch(LitterRobotEntity, ToggleEntity): """Litter-Robot Night Light Mode Switch.""" @property def is_on(self): ...
# coding=utf-8 from dateutil.easter import EASTER_WESTERN from holidata.utils import SmartDayArrow from .holidays import Locale, Holiday """ source: https://www.riksdagen.se/sv/dokument-lagar/dokument/svensk-forfattningssamling/lag-1989253-om-allmanna-helgdagar_sfs-1989-253 source: https://www.riksdagen.se/sv/dokumen...
################################################################ __author__='acgreyjo' # # The file handles and controls the post processing of the user # data and parsing the user configuration in order to determine # the type of analysis to perform. # ###########################################################...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Created on Mon Oct 30 19:00:00 2017 @author: gsutanto """ import numpy as np import os import sys import copy from CanonicalSystem import * class FunctionApproximator: "Base class for function approximators of DMPs." def __init__(self, dmp_num_di...
import os import re import shutil import sys from flask_unchained.cli import click from flask_unchained.click import default, skip_prompting from flask_unchained.string_utils import right_replace from jinja2 import Environment from typing import * JINJA_START_STR = '{#!' JINJA_END_STR = '#}' OTHER_START_STR = '#! ' ...
import random import pygame from . import settings from .object import Asteroid, PowerUp from .sound import SoundEffect class LevelDesign(pygame.sprite.Sprite): def __init__(self): super().__init__() self.current_level = 1 self.level_design = self.generate_level() self.font = pyg...
import gspread from oauth2client.service_account import ServiceAccountCredentials import sys class CloudSave: def __init__(self, sheet, credentials_file): try: scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credential...
from tir import Webapp import unittest class ATFA380(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup("SIGAATF", "01/04/2016", "T1", "M SP 01 ", "01") inst.oHelper.Program("ATFA380") def test_ATFA380_001(self): #INCLUI UM...
import datetime def log ( message ) : print(f"[ LOG ] status : {message} --> {datetime.datetime.now().strftime('%H:%M:%S')}")
"""Learning reward models using preference comparisons. Trains a reward model and optionally a policy based on preferences between trajectory fragments. """ import abc import math import pickle import random from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple, Union import numpy as np import to...
"""Module Partie""" import pygame import random from enums.Statut import Statut from enums.Menu import Menu from enums.Matiere import Matiere from enums.Filiere import Filiere from enums.EvenementsAleatoires import EvenementsAleatoires from Etudiant import Etudiant class Partie(): """Classe Partie : Gestion de l...
import sys inf = sys.maxsize N, K = map(int, input().split()) heights = list(map(int, input().split())) dp = [inf]*N dp[0] = 0 def chmin(a, b, diff): if dp[a] > dp[b] + diff: dp[a] = dp[b] + diff return for i in range(N): for j in range(1, K+1): if i-j >= 0: chmin(i, i-j, a...
import os import re from visnav.settings import * if False: for fn in os.listdir(CACHE_DIR): m = re.match('^(.*?)(hi|lo)(\d{4})\.nsm$', fn) nfn = None if m: nfn = m[1]+m[3]+'_'+m[2]+'.nsm' elif re.match('.*?\d\.nsm$', fn): nfn = fn[:-4]+'_lo.ns...
import sys as sys for word in sys.stdin: num_alph={} alph_index = {} repeated = set() palindromes = set() reverse_word = "" for i in range(1, len(word) + 1): reverse_word += word[-i] for letter in word: if letter not in num_alph: num_alph[letter] = 1 ...
from Calculator import Calculator compute = Calculator() print(compute.addition(10, 25)) print(compute.subtraction(5, 3)) print(compute.multiplication(5, 10)) print(compute.division(10, 2)) print(compute.exponent(5, 3)) print(compute.square_root(6)) print(compute.negate(200))
#Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e o seu antecessor n = int(input('Digite um número: ')) print('\033[7;30mO sucessor do número {} é {}, e o antecessor é {}\033[m'.format(n, n+1, n-1))
from random import uniform import numpy as np import math class Classifier: def __init__(self, input_size, learning_rate, momentum): self.input_size = input_size self.learning_rate = learning_rate self.momentum = momentum self.weights = np.random.uniform(-0.05, 0.05, self.input_siz...
# Copyright 2021 D-Wave Systems 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 or...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016 F5 Networks Inc. # # This file is part of Ansible # # Ansible 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 # ...
from datetime import datetime import io import os from absl import logging # noqa: F401 import tornado.web from icubam.db import store, synchronizer from icubam.www.handlers import base class DatasetHandler(base.APIKeyProtectedHandler): ROUTE = '/db/(.*)' API_COOKIE = 'api' ACCESS = [ store.AccessTypes.S...
""" Miscellaneous files used throughout the workflow. The static members of the class ``files`` are populated automatically as the workflow reads the user config. """ from sphinx_mock import * class files: """Houses lists of support files used throughout the workflow.""" #: The manually-uploaded datasets fo...
import requests import shutil import bz2 import os import hashlib import io from urllib.parse import urlparse import re from queue import Queue import itertools from functools import reduce __all__ = [ 'Repo', 'LocalRepo', 'RepoSet', 'Package', 'PkgReq', ] class HashTools: """ https://stackove...
# -*- coding: utf-8 -*- #from tst import testUnitarios from src import Controlador import unittest import os #runner = unittest.TextTestRunner() #result = runner.run(unittest.makeSuite(testUnitarios.TestUnitarios)) port = int(os.environ.get('PORT', 5000)) Controlador.app.run(threaded=True, host='0.0.0.0',...
""" Acme URL's """ # Django from django.urls import include, path # Django REST Framework from rest_framework.routers import DefaultRouter # Views from root.Acme.api.views import CategoryViewSet, ProductViewSet, OrdersViewSet, OperationsViewSet router = DefaultRouter(trailing_slash=False) router.register(r"categori...
#!/usr/bin/python ''' ''' from __future__ import print_function import urllib2 import sys import ssl if len(sys.argv) < 3: exit('Error: not enough arguments. Usage...') url = sys.argv[1] pwfile = sys.argv[2] user = sys.argv[3] # read in list of passwords with open(pwfile, 'r') as f: pwlist = f.read().splitline...
import argparse def main(args=None): parser = argparse.ArgumentParser() #add init parser for platform like package and simple package if __name__=='__main__': main()