text
stringlengths
38
1.54M
from setuptools import find_packages, setup setup( name='carnav', packages=['carnav'], version='0.0.1', include_package_data=True, install_requires=['gym', 'numpy', 'pillow', 'scipy', 'matplotlib'] )
# application constants # TELEGRAM_TOKEN = telegram token to access bot # (https://core.telegram.org/bots check point number 6) # API_ID = telegram api id to access telegram api # (https://core.telegram.org/api/obtaining_api_id) # API_HASH = telegram api hash to access telegram api #(https://core.telegram.org/api/obt...
x = int(input()) a = x // 100 b = x % 100 y = 5 c = [] while(b > 0 or y > 0): c.append(b // y) b = b % y y -= 1 print(int(sum(c) <= a))
# Import necessary packages import numpy as np import igraph as ig from scipy.special import gammaln from itertools import combinations, product import multiprocessing as mp import os import time def PlotGraph(G): # Plots graph G with appropriate positions of vertices layout = zip(G.vs["x"], -...
import os.path from setuptools import setup, find_packages import stun def main(): src = os.path.realpath(os.path.dirname(__file__)) README = open(os.path.join(src, 'README.rst')).read() setup( name='pystun3', version=stun.__version__, packages=find_packages(), zip_safe=F...
pw = "@@F\u0011\u0013\u0011\u0013XAE\u001a\u0011G\u0010\u0013\u0015\u0014F\u0015G\u001a\u001b\u0013\u0013\u001b\u0016BE\u0012\u0013B\u0017\u001a\u0011AF@\u0011E\u0016^" flag = "" for c in pw: flag += chr(ord(c) ^ 0x23) print(flag)
import os import sys from unittest import TestCase from werkzeug.datastructures import FileStorage sys.path.append(os.getcwd().split('\Tests')[0]) from Domain import FlightsManager import mock class TestUniformedFormat(TestCase): def setUp(self): self.data_with_GPS_point = (open("TestData/2021-01-08 17-...
import os USERNAME = os.environ.get('USERNAME') PASSWORD = os.environ.get('PASSWORD') AR_ENDPOINT = os.environ.get('ARX_ENDPOINT') AR11_ADVANCED_FEATURES = os.environ.get('AR11_ADVANCED_FEATURES', 'False') WIREMOCK_SERVER = os.environ.get('WIREMOCK_SERVER') WIREMOCK_START_RECORDING = '__admin/recordings/start' WIREMOC...
# 2534 - exame geral try: while True: n, q = map(int, input().split()) notas = [] for _ in range(n): notas.append(int(input())) notas.sort(reverse=True) for _ in range(q): pos = int(input())-1 print(notas[pos]) except EOFError: pass...
# Scoring functions # # Licensed under the BSD 3-Clause License # Copyright (c) 2020, Yuriy Sverchkov import numpy as np def gini_of_label_column(y): n: int = len(y) if n == 0: return 0 p = np.unique(y, return_counts=True)[1] / n return 1 - np.sum(p*p) def gini_of_p_matrix(pm: np.ndarra...
import random class Meteor(): def __init__(self): self.x = random.randint(0, 400) self.y = -40 self.change_x = random.randint(-5, 5) self.change_y = 1 self.height = 40 self.width = 40 def updateMeteor(self, speed, height, width, rocket, rocketValues): ...
!/usr/bin/env python from distutils.core import setup setup( name='dataset-shuft', packages=[], version='0.0.1', description='dataset-shift for a Python package', author='Abhilash Bokka', license=Null, author_email='abhilash.bokka@ucdenver.edu', url='https://github.com/ashabhi101/datase...
import dash import os import dash_html_components as html from flask_caching import Cache app = dash.Dash(__name__) server=app.server CACHE_CONFIG={ 'CACHE_TYPE':'redis', 'CACHE_REDIS_URL': os.environ.get('REDIS_URL','localhost:6379') } cache=Cache() cache.init_app(server,config=CACHE_CONFIG) app.config.su...
#!/usr/bin/env python from setuptools import setup setup(name='Pyda', version='0.1', author='Don Grote', author_email='don.grote@gmail.com', packages=['common','interfaces','mipsb'], test_suite='tests')
import pathManager.pathSetting as extPath from vanilla import FloatingWindow, RadioGroup, Button, HUDFloatingWindow, ImageButton, TextBox, EditText, CheckBox from groupingTool.tTopology import topologyButtonEvent as tbt from groupingTool.tMatrix import matrixButtonEvent as mbt from groupingTool.tMatrix.PhaseTool import...
import unittest from unittest.mock import patch from unittest.mock import Mock from unittest.mock import create_autospec from lxml import etree as ET from xliffdict import XLIFFDict class TestXliffDict(unittest.TestCase): def setUp(self): self.from_string = r'''<xliff version="1.2" xmlns="urn:oasis:names...
# Generated by Django 2.2.5 on 2020-02-26 06:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TreeHole', fields=[ ...
import datetime import sys import math import pandas as pd args = sys .argv f = open('monitoring.log', 'r') datalist = f.readlines() time_ip_ping = [] #故障しているサーバを一時的に記録 trouble = [] #故障したサーバを記録 trouble_record = [] #故障候補のサーバを記録 trouble_candidate = [] #ログに記録しているサーバのリスト ip_list = [] #ネットワークとIPアドレスの対応表 ip_subnet_list = ...
from abstract import AbstractRenderer from constants import * import pygame from pygame.locals import * TILE_WIDTH = 32 SPACING = 2 SCREEN_WIDTH = TILE_WIDTH * COLS + SPACING * (COLS+1) SCREEN_HEIGHT = TILE_WIDTH * ROWS + SPACING * (ROWS+1) KEY_REPEAT = 50 # Key repeat in milliseconds class DesktopRenderer(Abstr...
import json from main import main with open('input.json', 'r') as input_stream: parsed_input = json.loads(input_stream.read()) obj=main(parsed_input) print('\n') print(obj) """m=folium.Map(location=[35.300048416948435 , -120.65977871417999] , zoom_start=13) jsonFile=open('input.json','r') jsonData=jsonFi...
ADDRESS = 'sb://####.servicebus.windows.net/#####' USER = '##########' KEY = '##################################' CONSUMER_GROUP = "$default" OFFSET = Offset("-1") PARTITION = "1" total = 0 last_sn = -1 last_offset = "-1" try: if not ADDRESS: raise ValueError("No EventHubs URL supplied.") client = EventHub...
import random from django.db import models from django.utils.translation import gettext_lazy as _ from django_common_utils.libraries.models.mixins import RandomIDMixin from django_lifecycle import BEFORE_CREATE, hook, LifecycleModel from apps.django.utils.fields import ColorField from ..constants import DEFAULT_COLOR...
import os, sys, shutil, glob from subprocess import check_call API = "/home/vagrant/openkim-api" CODE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) REPO2 = CODE_DIR + "/tests/repo" def test_cleanup(): os.chdir(API) os.system("(. /tmp/env; make clean >> /dev/null 2>&1)") assert not o...
from django.shortcuts import render, get_object_or_404 from django.contrib.auth import login, logout, authenticate from django.http import HttpResponse, Http404, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required, user_passes_test from django.contr...
# Copyright 2018 Samsung Electronics # 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 requi...
from typing import List from cache import CacheUser from common.enums import EnumResponse from common.line.classes import Event from loguru import logger from machine import MACHINE from machine.classes import Machine # pylint: disable=E0611 from pydantic import BaseModel # pylint: enable=E0611 DOC = { 200: En...
# zad 5 ################################## n1 = int(input('wpisz ilosc liczb ')) print(n1) arr = [] for i in range(n1): arr.append(int(input())) arr.sort() print('podaj pszedzial\n') a3 = int(input('od elementu - ')) b3 = int(input('do elementu - ')) print(arr[a3:b3+1]) # zad 4 ########...
import threading threads = 4 nth_fibonacci_term = 38 class WorkerThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) print "Initialising", self.getName() def run(self): print self.getName(), "started!" self.f(nth_fibonacci_term) print self.ge...
import os, pathlib, logging import numpy as np log = logging.getLogger(__name__) def get_full_path(subpath): """Gets full path using the current directory (of this script) + the subpath Args: subpath (str): subpath in current directory Returns: str: the full path """ cur_dir = p...
import dpkt import re import socket import sys from traceroute.fragment import DatagramFragment from traceroute.ip_protocols import ip_protocol_map from traceroute.packet import Packet from traceroute.results_logger import print_results from typing import Dict, List def read_trace_file(filename: str) -> (str, str, Lis...
# -*- coding: utf-8 -*- # # python-netfilter - Python modules for manipulating netfilter rules # Copyright (C) 2007-2009 Bolloré Telecom # See AUTHORS file for a full list of contributors. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
from pyomo.core import Var import pandas as pd from argparse import ArgumentTypeError def model_res_to_dict(m): '''Function to save the output of the model in a 2-levels dictionary: first level are the variables, second level are countries-time periods keys''' res_dict = {str(v): {index: getattr(m, str(v)...
ASSIGN = 'ASSIGN' COMMA = 'COMMA' COLON = 'COLON' DIVIDE = 'DIVIDE' DOT = 'DOT' EQUAL = 'EQUAL' GREATER_THAN = 'GREATER_THAN' GREATER_THAN_EQUAL = 'GREATER_THAN_EQUAL' LESS_THAN = 'LESS_THAN' LESS_THAN_EQUAL = 'LESS_THAN_EQUAL' NOT_EQUAL = 'NOT_EQUAL' LPAREN = 'LPAREN' RPAREN = 'RPAREN' MINUS = 'MINUS' MODULO = 'MO...
#!/usr/bin/env python3 import psutil import shutil import emails import socket import os sender = 'automation@example.com' recipient = '{}@example.com'.format(os.environ.get('USER')) body_msg = 'Please check your system and resolve the issue as soon as possible.' def check_cpu(): try: CPU_PCT...
LINK = 'link' class LeaveException (RuntimeError): pass class Link (object): def reorder (self, l): """ Flips a list of Links so that this node is first in each """ return Link.order(l, self) @staticmethod def order (links, n): """ Give a list of Links that each contain node n, flips...
from game_master import GameMaster from read import * from util import * class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Returns: A Fact object ...
class ResultSet(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def fetchone(self): return self.__getitem__(0) if self.__len__() > 0 else None
from school import get_int from sys import exit num = get_int("Enter a number: ", force=True) total = 0 sums = 0 begin_num = 1 next_num = 1 while next_num != num: total += next_num # Если сумма стала больше введенного числа if total > num: begin_num += 1 next_num = begin_num tota...
#Open API 공공데이터 import requests import urllib.parse as p from urllib.request import Request,urlopen import re import csv from datetime import date import time import pandas as pd import os def getTimeTuple(startTimeStr, endTimeStr, rangeType): #init vars startTime = '' endTime = ''...
class SistemaDeAudio(object): """ Sistema de audio. """ def configurar_frequencia(self): """ Configura a frequência do audio. """ print("Frequência configurada") def configurar_volume(self): """ Configura o volume do audio. """ prin...
from utils import * from User import User from Project import Project from Sprint import Sprint from stasis.Singleton import get as db class Availability: def __init__(self, sprint): self.sprint = sprint def get(self, user, timestamp): table = db()['availability'] if self.sprint.id in table: data = table[...
# Cesar Hernandez 1835494 lem_juice = float(input('Enter amount of lemon juice (in cups):\n')) water = float(input('Enter amount of water (in cups):\n')) agave_nect = float(input('Enter amount of agave nectar (in cups):\n')) servings = float(input('How many servings does this make?\n')) print('\nLemonade ingredien...
#!/usr/bin/env python # encoding: utf-8 try: from unittest import mock except Exception: import mock import pytest from translate import Translator from translate.exceptions import InvalidProviderError, TranslationError from translate.providers import MyMemoryProvider from .vcr_conf import vcr def test_tra...
#!/usr/bin/env python2 import dlock13 import sys, time def open(topic, duration): name = 'nada' doors = {} doors[name] = topic lock = dlock13.Opener(doors) try: return lock.open(name, duration) except Exception, e: lock = None raise e def main(): prog, args = sys...
# Created by MechAviv # Quest ID :: 21001 # Find the Missing Kid 2 sm.setSpeakerID(1209006) if sm.sendAskAccept("*Sniff sniff* I was so scared... Please take me to Athena Pierce."): sm.giveItem(4001271) sm.startQuest(parentID) sm.warp(914000500, 1) else: sm.setSpeakerID(1209006) sm.sendNext("*Sob* ...
from sql_alchemy import banco class LivroModel(banco.Model): #mapeando que essa classe é uma tabela no db __tablename__='livros' livro_id = banco.Column(banco.Float, primary_key=True) nome = banco.Column(banco.String(80)) preco = banco.Column(banco.Float(precision=1)) quantidade = banco.Column(banco.F...
import pprint from time import sleep from InstagramAPI import InstagramAPI api = InstagramAPI ( "username", "password") api.USER_AGENT = 'Instagram 10.34.0 Android (18/4.3; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)' users_list = [] following_users = [] def get_likes_list(username): """ Function: ...
from concurrent import futures from google.cloud import pubsub_v1 from random import randint from datetime import datetime import json # TODO(developer) project_id = "packt-data-eng-on-gcp" topic_id = "bike-sharing-trips" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) ...
import logging import pickle import math import abc import numpy as np from copy import deepcopy from sklearn.metrics import mean_absolute_error, mean_squared_error from sample_sim.data_model.gp_wrapper import TorchSparseUncertainGPModel, TorchExactGp, GPWrapper from sample_sim.data_model.workspace import Workspace f...
'''tk_mouse_click_shape1.py show xy coordinates of mouse click position relative to root or relative within a shape tested with Python27/Python33 by vegaseat ''' try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk def showxy(event): ''' show x, y coordinates...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'KernelVersion.pretty_kernel_version_name' db.delete_col...
""" PythonAEM error, contains a message and PythonAEM Result object """ class Error(RuntimeError): """ PythonAEM error, contains a message and PythonAEM Result object useful for debugging the result and response when an error occurs """ def __init__(self, message, result): """ Ini...
from PyQt5 import QtWidgets from Pantallas.Serializables import modificacionMaxMinIngreso from Pantallas.Serializables import modificacionMaxMin class ModificacionMaxMinIngresoSerializables(QtWidgets.QWidget, modificacionMaxMinIngreso.Ui_Form): def __init__(self, *args, **kwargs): QtWidgets.QWidget._...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c ) import random """ Sim for Ultimatum/Two-Stage Bargaining Game """ class Constants(BaseConstants): name_in_url = 'ultimatum' players_per_group = 2 num_rounds = 4 instructions_template = ...
import fpdf import csv import os d="path" parent="C:\Python33" pat=os.path.join(parent,d) data=os.listdir(pat) new=[] for i in range(len(data)): with open (data[i]) as f1: dirc=list(csv.reader(f1)) for j in range(len(data)): ...
import os import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from collections import * from itertools import * from Properties import * from scipy.interpolate import * from FunkyFuncs import * from MiscFunctions import * from Nodes import * from collections im...
# Copyright (c) 2015, Warren Weckesser. All rights reserved. # This software is licensed according to the "BSD 2-clause" license. # # Use pyqtgraph to display the eye diagram computed by eyediagram.grid_count. import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np from eyediagram.demo_data ...
from flask import Flask, request, make_response from currencyExchange import * import argparse import os import json app = Flask(__name__) ## # Confirms the service is working on a browser # @return {dict} a symbolic confirmation of the service ## @app.route("/", methods=["GET"]) def retornodummy(): r = make_resp...
#! python3 # -*- coding: utf-8 -*- # 演習プロジェクト 18.13.2 Googleハングアウトの自動操作 # # Google Talkがサービス終了のため、代わりにGoogleハングアウトを使って # 複数ユーザにメッセージを送信するプログラム。 # # あらかじめ、Googleハングアウトの画面から、送信する相手のアイコンや名前の # 部分を切り取って、user1.png、user2.png、... という名前のPNGファイルとして保存してください。 # 切り取る箇所は、guide.pngの赤い枠の部分を参照してください。 # このとき、ユーザを選択せず...
# 1) Вручную создать текстовый файл с данными (например, марка авто, модель авто, расход топлива, стоимость). print(' 1) Вручную создать текстовый файл с данными') print(' Я создал фаил template') # 2) Создать doc шаблон, где будут использованы данные параметры. print(' 2) Создать doc шаблон, где будут использова...
# -*-coding:utf8-*- import sys from room_central_corridor import CentralCorridor from room_laser_weapon_armory import LaserWeaponArmory from room_the_bridge import TheBridge from room_escape_pod import EscapePod class Game(object): def __init__(self): print("---Game start---\n") self.rooms = {} ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: """无序链表的排序常见的做法是mergesort,merge的部分其实就是21. Merge Two Sorted Lists合并两个有序链表, 现在核心是完成sort那一部分,sort用slow,fast两个指针把head分成差不多均等的两部分,然后对这两部分再调用sortList函数, 最后merge. 仔细想一...
def RemoveImplicitSubtitle(title): if title == '': return title sublist = ['--', '~~', '()', '[]', '<>', '""'] for s, e in sublist: if title[-1] == e: ind = title[:-1].rfind(s) if ind == -1: return title.strip() else: retur...
# Copyright (c) 2015-2018 Cisco Systems, Inc. # 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,...
#! /usr/bin/env python3 def replace_problematic_characters(string_list, character_dict): fixed_string_list = [] problem_pointer_list = [] for char in string_list: if character_dict.get(char) != None: swap_char = character_dict[char] fixed_string_list.append(swap_char) ...
import tkinter as tk from proba.config import Config from proba.exercise1 import Exercise1 from proba.exercise2 import Exercise2 from proba.menu import Menu '''This module manages the display of the different frames used in the program.''' class Application(tk.Tk): def __init__(self): super().__init__...
from django.shortcuts import render , HttpResponse from django.contrib.auth.decorators import login_required from grpcheckerview import group_required from club import datahandler as dataconn # Create your views here. @login_required(login_url = '/user/login/') @group_required("Techgrp") def adminLanding(request): ...
import base64 import json import os import cv2 import requests from django.http import JsonResponse from django.shortcuts import render from . import settings MAX_NM_CNT = 5 # max no mask SEC = 10 URL_PREFIX = "http://3.36.161.101:8080/predictions" PROJ_MODELS = {1: 'faster_rcnn', 2: 'cascade_rcnn'} def index(re...
import time import pymysql import win32api import win32con import win32gui from selenium import webdriver from explicit_wait import explicit_wait from ins_pymsql import fetch_one_sql, oprt_mysql class Main(): def __init__(self): self.conn = pymysql.connect(host='localhost', port=3306, ...
from flask import Flask, request, jsonify, g, render_template from .settings import access_key_id, secret_access_key, acl, bucket_name, bucket_region from .email_settings import mail_server, mail_port, mail_username, mail_password from .shipping_settings import shipping_address, shipping_zip, shipping_city, shipping_st...
from .eval import eval from .train import train from .learncurve import learning_curve from .predict import predict from .prep import prep def cli(command, config_file): """command-line interface Parameters ---------- command : string One of {'prep', 'train', 'eval', 'predict', 'finetune', 'l...
from django.db import models class PriorityHospitalArea(models.Model): # CHOICES PRIORITY_AREA_OPTIONS = ( ("Resusciation Area", "Resusciation Area"), ("Major Wound Area", "Major Wound Area") ) area = models.CharField(choices=PRIORITY_AREA_OPTIONS, max_length=20) def __str__...
# coding: utf-8 # In[1]: import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import pickle import time import random import tensorflow as tf from scipy import spatial import os import json import argparse import scipy import copy # In[2]: parser = argparse.ArgumentParser(...
# OTCalcMethods.py - This version will use the correlations to form time series, # then do time series forecasting # # This is an implementation of the code at: # # https://machinelearningmastery.com/random-forest-for-time-series-forecasting/ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010-2012 Tianwei Workshop # Copyright (C) 2010-2012 Dalian University of Technology # # Authors: Tianwei Liu <liutianweidlut@gmail.com> # Created: 2012-6-7 # This program is free software; you can redistribute it and/or modify # it under...
''' nucleotide_alignment Module for the representation of nucleotide alignments. ''' import os from typing import Iterable, Tuple import numpy import pyckmeans.distance from .c_interop import encode_nucleotides # Base encoding as used by R package ape. # See http://ape-package.ird.fr/misc/BitLevelCodingScheme.h...
__author__ = 'erwin' import web urls = ( '/world(/.*)', 'World', '/(.*)', 'Hallo', ) app = web.application(urls, globals()) class Hallo: def GET(self, name): if not name: name = 'Hallo' return 'hello, ' + name class World: def GET(self, name): if not name: ...
"""Provides class to wrap existing models in different frameworks so that they provide a unified API to the attacks. """ from .keras_yolov3 import KerasYOLOv3Model from .keras_ssd300 import KerasSSD300Model from .keras_retina_resnet50 import KerasResNet50RetinaNetModel
# Read output from pdflatex/latex, after doconce grab # doconce grab --from- '\*File List\*' --to- '\*\*\*\*' tmp.txt > tmp.txt # and find all styles files with full path dont_copy = [] import sys, commands, os f = open(sys.argv[1], 'r') lines = f.readlines() paths = [] for line in lines: words = line.split() ...
""" Storage containers for durable queues and (planned) durable topics. """ import abc import logging import threading from coilmq.util.concurrency import synchronized __authors__ = ['"Hans Lellelid" <hans@xmpl.org>'] __copyright__ = "Copyright 2009 Hans Lellelid" __license__ = """Licensed under the Apache License, V...
# from sqlalchemy import create_engine # from sqlalchemy.ext.declarative import declarative_base # from sqlalchemy.orm import sessionmaker # SQLALCHEMY_DATABASE_URL = "sqlite:///./proxymall.db" # # SQLALCHEMY_DATABASE_URL = "postgresql://postgres:root@localhost/protech?" # engine = create_engine( # SQLALCHEMY_DAT...
""" LAMBDAS: ->São funções sem nome, ou seja, anônimas ->sao criadas com somante uma linha """ #exemplo de simples op = lambda x: x*2 + 1 #Estrutura: lambda parâmetro: operação que irá ser retornada da função print(op(2)) #mais exemplos autores = ['Monteiro Lobato','José de Alencar','Cecília Meireles',...
import Recursividad.EjemploRecursividad as ej import unittest class Pruebas(unittest.TestCase): def test_factorial(self): self.assertEqual(120, ej.factorial_recursivo(5)) self.assertEqual(1, ej.factorial_recursivo(0)) self.assertEqual(24, ej.factorial_recursivo(4))
# Class object for event type 'CUSTOMER' class Customer: def __init__(self, key, verb, event_time, last_name, adr_city, adr_state): self.key = key self.verb = verb self.insert_time = event_time self.last_name = last_name self.adr_city = adr_city self.adr_state = adr_s...
import numpy as np import matplotlib.pyplot as plt from matplotlib import patches from sklearn import datasets from sklearn.mixture import GMM from sklearn.cross_validation import StratifiedKFold import warnings warnings.simplefilter("ignore", DeprecationWarning) iris = datasets.load_iris() indices = StratifiedKFol...
def BinarySearch(array, element): low = 0 high = len(array)-1 while low <= high: mid = int((low+high)/2) if element < array[mid]: high = mid-1 elif element > array[mid]: low = mid+1 else: return mid return -1 # function call print(Bin...
""" https://edabit.com/challenge/iasdc3ihqt9hkZWfi """ def can_give_blood(donor, receiver) -> bool: if '+' in donor and '+' not in receiver: return False elif donor[:-1] in receiver or 'O' in donor: return True else: return False tests = [ (("O+", "A+"), True), (("A-", "B...
def package(N,W,cost,value): f = [0] * (W + 1) for i in range(N): for j in range(W,cost[i] - 1,-1): f[j] = max(f[j],f[j - cost[i]] + value[i]) return f N,W = map(int,input().split(" ")) listB = [] listC = [] for i in range(N): listA = input().split() listB.append(int...
import time import random import sys from sys import stdout # List of responses response = ["Yes, most definitely!", "The chances are high!", "Not likely!", "May the odds be ever in your favor.", "You got no shot, kid.", "Try it out and see!", "23% of working", "99.9% success rate", ...
""" The MIT License Copyright (c) 2010 Sugestio.com 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, publi...
words = lambda t : list(map(t, input().split())) n = int(input()) a = words(int) a.sort() cur = a[0] for i in range(1,len(a)): cur = (cur + a[i]) / 2 print(cur)
#https://codeforces.com/contest/127/problem/A import math n,k=map(int,input().split()) x1,y1=map(int,input().split()) time=0 for _ in range(n-1): x2,y2=map(int,input().split()) dis=math.sqrt((x2-x1)**2+(y2-y1)**2) t=dis/50 time+=t x1,y1=x2,y2 time*=k print('%.9f'%time)
t=input() for i in range(t): a=input() b=str(a) sum=0 for x in b: c=int(x) sum+=c if a%sum==0: print '1' else: print '0'
listOfNumbers = [] even = 0 odd = 0 while True: number = int(input("Favor ingrese un número, o para dejar de ingresar números ingrese 0: ")) if number == 0: break listOfNumbers.append(number) if number % 2 == 0: even = even + 1 else: odd = odd + 1 print (f"El número de pare...
# Copyright 2014,2016 Hewlett Packard Enterprise Development Company, L.P. # # 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 b...
# -*- coding: utf-8 -*- import sqlite3 class dataobj(object): """ 연습삼아 만들어본 ORM 객체 입니다. 데이터베이스 테이블과 1:1 연결되는 기본 객체 입니다. TABLE_FIELDS 에 데이터베이스 필드 리스트를 초기화 해주면 dataobjmanager에서 query_obj, query_obj_one메서드를 이용해 데이터를 자동으로 채울 수 있습니다. """ TABLE_FIELDS = [] def __repr__(self): return...
import urllib2 def noHTML(definition): command = False while command is False: lessOpen = definition.find('<') greatClose = definition.find('>') if lessOpen > -1 and greatClose > -1: definition = definition[0:lessOpen] + definition[greatClose+1:] else: c...
from pathlib import Path from scipy.sparse import csc_matrix from sklearn.externals import joblib from sklearn.feature_extraction.text import CountVectorizer from nerds.features.base import BOWFeatureExtractor, UNKNOWN_WORD from nerds.util.file import mkdir from nerds.util.logging import get_logger, log_progress from...
from sys import stdin input = stdin.readline def palindrome(s): for i in range(len(s) // 2): if s[i] != s[-i - 1]: return 'no' return 'yes' if __name__ == "__main__": while True: number = input().strip() if number == '0': break res = palindrome(nu...
import requests import threading import time import re import socket import sys import argparse import random from requests.exceptions import HTTPError from collections import deque # This optional argument decides which bot to call parser = argparse.ArgumentParser() parser.add_argument("-b", type=str) args = parser.pa...