text
stringlengths
38
1.54M
import numpy as np, matplotlib.pyplot as plt d = np.load('2457548.45923.npz') NOT_REAL_ANTS="0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67...
""" This problem was asked by Amazon. Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". Implement run-length encoding and decoding....
In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc. soln: from string import ascii_lowercase LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lo...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # (C) w:fa:User:Reza1615, 2020 # (C) w:fa:User:Huji, 2020 # Distributed under the terms of the CC-BY-SA 3.0 import pywikibot from persiantools import digits from datetime import datetime month_names = [ "ژانویه", "فوریه", "مارس", "آوریل",...
import os.path import shutil import sys import numpy as np import gc import tensorflow as tf from nets import nets from data import data from runs import preprocessing import pickle def evaluate_network(opt): # Initialize dataset and creates TF records if they do not exist dataset = data.ImagenetDataset(opt) ...
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def print_singly_linked_list(node, sep, fptr): wh...
from scipy import signal import numpy as np # linear algebra import matplotlib.pyplot as plt DeltaQ = 150 #Internal heat gain difference between day and night #day_DeltaQ = DeltaQ #Day Delta Q internal [W] Qday = 400 #Day internal heat gain W nightQ ...
#!usr/bin/pytthon # coding:utf-8 from numpy import * # 已知用户物品矩阵为dataMat ,行为物品,列为用户 # 计算用户相似度 # ----------------- # 余弦相似度计算 # 欧式距离计算 def eulidSim(inA, inB): return 1.0 / (1.0 + linalg.norm(inA, inB)) # 皮尔逊系数计算 def pearsSim(inA, inB): if len(inA) <3 : return 1.0 # 将值从[-1, 1]映射到[0, 1] return 0.5+0.5*corr...
#!/usr/bin/python3 # import socket programming library import socket import json import time import csv import hadoop import pandas from io import StringIO # import thread module from _thread import * import threading print_lock = threading.Lock() def processJobInfo(stats): statsstr = '\n'.join(stats) p...
import cv2 import cvzone from cvzone.SelfiSegmentationModule import SelfiSegmentation import os cap = cv2.VideoCapture('1.avi') cap.set(3, 640) cap.set(4, 480) cap.set(cv2.CAP_PROP_FPS, 60) segmentor = SelfiSegmentation() fpsReader = cvzone.FPS() imgBg = cv2.imread('Images/1.jpg') imgBg = cv2.resize(imgBg,(640, 480)) ...
import tensorflow as tf import models.bert_util.bert_utils from explain.explain_model import CrossEntropyModeling, CorrelationModeling from explain.pairing.match_predictor import build_model from tf_util.tf_logging import tf_logging from trainer.multi_gpu_support import get_multiple_models, get_avg_loss, get_avg_tenso...
def try5(): d = Definer() m = d.matcher f1 = CFunc(PrimTypes.INT) f1.add(CPtr(CPtr(PrimTypes.VOID))) m.add_rule(CPtr(PrimTypes.VOID), 'PVOID') m.add_rule(PrimTypes.INT, 'INT') m.tree_names_list.append('MYSTRUC') # m.add_rule(CPtr(f1), 'MY_PROC') s1 = CStruct() s1.add(PrimTypes.UI...
from uncertainties import ufloat from uncertainties.umath import * print print '*************Values *********************' print H = ufloat(67.4000000, 1.40000000) # H = 67.4+/-1.4 h = H/100.0 print 'h = ', h obh2 = ufloat(0.0220700000, 0.000330000000) print 'obh2 = ' , obh2 ob = obh2/h**2 ErrorLnOb = 0.00124 LnOb =...
numList = [] for x in range(5): numList.append(int(input("Number " + str(x+1) + ": "))) print("You entered: " + str(numList)) avg = 0 for x in numList: avg += int(x) avg = avg / len(numList) print("The average is: " + str(avg)) print("The range is: " + str(len(numList))) rem = int(input("Which item do you want ...
# -*- mode: Python; -*- '''Implementation of vrt-data.''' import os from subprocess import Popen, PIPE from libvrt.args import BadData from libvrt.args import transput_args # TODO here AND rel-tools to RAISE not EXIT on failure from libvrt.bins import SORT from libvrt.dataline import valuegetter # remnants of vrt...
# Regex ''' You have a test string S. Your task is to match the string hackerrank. This is case sensitive. ''' Regex_Pattern = r'hackerrank' # Do not delete 'r'. import re Test_String = input() match = re.findall(Regex_Pattern, Test_String) print("Number of matches :", len(match)) # Matching Anything But a Newlin...
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' data = np.genfromtxt(path,delimiter=",",skip_header=1) print ("\nData: \n\n",data) print ("\nTypeof data: \n\n",type(data)) #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] census...
import os #declarar variables Comensal,Azafata,precio1,precio2,precio3="","",0,0,0 #INPUT Comensal=os.sys.argv[1] Azafata=os.sys.argv[2] precio1=int(os.sys.argv[3]) precio2=int(os.sys.argv[4]) precio3=int(os.sys.argv[5]) #PROCESSING total =int(precio1 + precio2 + precio3) #OUTPUT print(" ############################...
from typing import Dict, List, Optional from pydantic import BaseModel class RecognitionModel(BaseModel): error: bool = False error_msg: str = "" data: Dict = {}
from django.db import models # Create your models here. class Employee(models.Model): fullname = models.CharField(max_length=30) job = models.CharField(max_length=15) salary = models.IntegerField() email = models.EmailField(max_length=50) def __str__(self): return self.fullname + "," + se...
from .distributions import GMMDiag, GMMFull, MoE import tensorflow as tf import tensorflow.compat.v1 as tf1 from ..utils.tf_utils import log_normalize class GMMApprox(object): def __init__(self, log_unnormalized_prob, gmm=None, k=10, loc=0., std=1., ndim=None, loc_tril=None, samples=20, temp=1., cov_type='diag')...
# -*- coding:utf-8 -*- import sys sys.path.append('..') from Model.BookModel import BookModel from Model.ISBNBookModel import IsbnBookModel from View.BookView import BookView class BookController(object): def __init__(self): self.Model = BookModel() self.View = BookView() #上传图书ISBN信息 '...
max = 1000000 primes = [True]*max for i in range(2,max): x = 2*i while x < max: primes[x] = False x += i print(primes[:30]) count = 1 x = 2 while count < 10001: x += 1 if primes[x]: count += 1 print(x)
import re, time, json, threading, requests, traceback from datetime import datetime import paho.mqtt.client as mqtt import DAN, SA def df_func_name(df_name): return re.sub(r'-', r'_', df_name) MQTT_broker = getattr(SA,'MQTT_broker', None) MQTT_port = getattr(SA,'MQTT_port', 1883) MQTT_User = getattr(SA,'MQTT_User...
from histogram_functions import get_words from histogram_lists import count_words import random def sample_by_frequency(histogram): # Find the most any word appears and set max_frequency equal to that value max_frequency = 0 for item in histogram: if item[1] > max_frequency: max_freque...
from hwt.hdlObjects.operator import Operator from hwt.hdlObjects.operatorDefs import AllOps from hwt.hdlObjects.types.defs import BOOL from hwt.hdlObjects.value import Value class EventCapableVal(Value): def _hasEvent__val(self, now): BoolVal = BOOL.getValueCls() return BoolVal(self.updateTime == ...
import logging class LastLogsHandler(logging.Handler): def __init__(self, size): logging.Handler.__init__(self) self.strA = [] self.i = 0 self.len = size for i in range(self.len): self.strA.append(None) def emit(self, record): self.strA[self.i] = re...
from numpy import * import pylab from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plot set_printoptions(precision = 3) #Datos: distribución normal multivariada en 3d mean = [1,5,10] cov = [[-1,1,2], [-2,3,1],[4,0,3]] d = random.multivariada_normal(mean,cov,1000) #representació gráfica de los dato...
#1/2/3 import numpy as np import pandas as pd site=('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/Students_Alcohol_Consumption/student-mat.csv') df = pd.read_csv(site) #4 df_slice = df.loc[:,'school':'guardian'] #5/6/8 str_func = lambda x: x.capitalize() df['Mj...
import os #imput densidad=int(os.sys.argv[1]) altura=int(os.sys.argv[2]) gravedad=float(os.sys.argv[3]) #processing presion=(densidad*altura*gravedad) #output if (presion>42): print("presion en estado critico para el producto") if(presion<42 and presion>30): print("tengan cuidado") if(presion<20): print("to...
#!/usr/bin/python """ unpickle.py: A subset of unpickling code from pickle.py. - We don't want to ship the pickler. - We only need to handle the v2 protocol - We only need to handle the parts of the protocol that we use. For reference, the _RuntimeType hierarchy seems to require 15 unique instructions + PROTO and STO...
from random import choice from time import sleep STUDENTS = [ 'Name 1', 'Name 2', 'Name 3', ] def rien_ne_va_plus(hot_seats, safe_students): if hot_seats == []: hot_seats = STUDENTS.copy() safe_students = [] print(f"Students on the hot seats for the next question:\n\t{', '.join(hot_seats)}\n")...
rzymskie ={ 1:'I', 2:'II', 3:'III', 4:"IV", 5:"V", 6:"VI", 7:"VII", 8:"VIII", 9:'IX', 10:"X"} cyfra = input("podaj liczbę: ") #po_rzymsku = rzymskie[liczba] #print(po_rzymsku) #cyfra 28 cyfra_dziesiatek = int(cyfra[-2])# przedostatnia cyfra, przdostatni znak zamieniona na cyfrę cyfra_jedności= int(cyfra[-1]) jednosci...
#!/usr/bin/python """ Script to make light budget calculations for permitted cable lengths for a given TAP or appropriate TAP for current link. """ from decimal import Decimal, getcontext def menu(): """ High level menu for available options. """ option = raw_input("""\nWhat would you like to do: 1 -...
class Node(object): def __init__(self, data = None, next_node = None): self.data = data self.next = next_node def __str__(self): return str(self.data) def get_data(self): return self.data def print_list(node): while node: print(node.get_data()) ...
class Config(object): DEBUG = True SQLALCHEMY_DATABASE_URI = "mysql://dev:dev@localhost/ssi" SQLALCHEMY_ECHO = False SECRET_KEY = "secret"
from StringIO import StringIO import tornado.gen import tornado.testing import tornado.web from tornado.httpclient import HTTPResponse, HTTPRequest from mainhandler import MainHandler class MainHandlerTest(tornado.testing.AsyncHTTPTestCase): "Test fixture for MainHandler class" def __init__(self, *args, **kw...
import hashlib import imghdr import sec import db_op __all__ = ['get_type_by_stream', 'save_file', 'get_hashcode', 'get_default', 'get_image'] _SAVE_PATH = '/Yagra/upload/' _DEFAULT_IMG = '/Yagra/web/static/rex.jpeg' def get_type_by_stream(stream): """Check the data stream and return what type of ima...
# Linear Regression Machine Learning Program # # Sources used: # - https://towardsdatascience.com/master-machine-learning-multiple-linear-regression-from-scratch-with-python-ac716a9b78a4 # Sean Taylor Thomas import numpy as np import matplotlib.pyplot as plt # from matplotlib import rcParams # rcParams['figure.figsize...
from collections import deque queue = deque(["Eric", "John", "Michael"]) queue.append("Ben") queue.append("Helen") print queue print queue.popleft() print queue
import numpy as np # Creating an 1d - array li = [1, 2, 3] arr = np.array(li) print(arr) # Creating an 2d - array li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] arr = np.array(li) print(arr) # Creating an array of a number sequence arr = np.arange(0, 10) print(arr) arr = np.arange(0, 10, step=2) print(arr) # Creating an 1-...
def is_palindrome_permutation(strng): cache = set() for char in strng.lower(): if char in cache: cache.remove(char) else: cache.add(char) return len(cache) <= 1 is_palindrome_permutation('RACECAR')
import cv2 def bgr8_to_jpeg(value): if value is None: return bytes() return bytes(cv2.imencode('.jpg', value)[1])
from soda.execution.table import Table class Column: def __init__(self, table: "Table", column_name: str): from soda.sodacl.column_configurations_cfg import ColumnConfigurationsCfg self.data_source_scan = table.data_source_scan self.table = table self.column_name = str(column_name...
import numpy as np import sys from ..mike_model.tariff import Tariff class Customer: """Can be resident, strata body, or ENO representing aggregation of residents.""" def __init__(self, name, study, timeseries): self.name = name self.study = study self.ts = timeseries self.t...
from django.db.models.signals import class_prepared def patch_user(sender, *args, **kwargs): authmodels = 'django.contrib.auth.models' if sender.__name__ == 'User' and sender.__module__ == authmodels: # patch the length sender._meta.get_field('username').max_length = 80 # patch the ...
# Created by MechAviv # Quest ID :: 61145 # Mysterious Merchant Matilda sm.setSpeakerID(9201451) sm.removeEscapeButton() sm.flipDialogue() sm.sendNext("Hi! My name is #bMatilda#k.\r\nI sell lots of handy stuff. And not like those OTHER people that say that.\r\n You have the look of someone about to do something stu...
from django.db import models from django.contrib.auth.models import User class Ban( models.Model ): id = models.AutoField( primary_key = True ) user = models.OneToOneField( User ) ip_address = models.IPAddressField() start_dtm = models.DateTimeField() end_dtm = models.DateTimeField() permaban =...
# 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다. # 예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 # array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다. # 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다. # 2에서 나온 배열의 3번째 숫자는 5입니다. # 배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, # commands의 모든 원소에 대해 앞서 설명한 연산을...
import gym import gym.spaces as spaces import Game class CustomEnv(gym.Env): def __init__(self): self.pygame = Game.Pygame2D() self.action_space = spaces.Discrete(180) rows_player_obs = [5] * 15 penality_player_obs = [1] * 7 board_player_obs = [1] * 25 n...
from details.models import Person from django.forms import Textarea, CheckboxSelectMultiple from django.forms.models import ModelMultipleChoiceField from django.utils.translation import ugettext as _ from django.contrib import admin from django.conf import settings from django.db import models from common.admintools i...
""" Model for the adventure. """ # pylint: disable=too-few-public-methods from django.db import models from .mixins import TimestampMixin, DescriptionNotesMixin class Adventure(models.Model, TimestampMixin, DescriptionNotesMixin): """ Model for the adventure. """ name = models.CharField(max_length=12...
import json import pandas as pd import numpy as np from tqdm import tqdm def get_spdat_feat_types(df): ''' Get lists of features containing the single-valued categorical and noncategorical feature names in the SPDAT data :param df: Pandas DataFrame containing client SPDAT question info :return: List of...
## Ch09 P9.6 from car import Car myCar = Car(50) myCar.addGas(20) myCar.drive(100) print(myCar.getGasLevel())
def spiralNumbers(m): mx = [[0 for i in range(m)] for j in range(m)] cnt = 1 for i in range(m): mx[0][i] = cnt cnt += 1 n = m - 1 while cnt < m ** 2: for j in range(m // 2): for i in range(n): mx[i + j + 1][m - j - 1] = cnt cnt += ...
#!/usr/bin/env python # coding: utf-8 # In[17]: import cv2 import numpy as np import glob import matplotlib.pyplot as plt import PIL import time import os # In[49]: img_dir = os.path.join(r"Images","*g") img_dir = glob.glob(img_dir) image_l = [] # In[50]: def MSE(image1_gray_resized_np,image2_gray_resized_np...
# Handle all the exceptions! #Setup actor = {"name": "John Cleese", "rank": "awesome"} #Function to modify, should return the last name of the actor [try except block] def get_last_name(): try: return actor["last_name"] except: namelist=[] namelist= actor["name"].split() return ...
HTTP_HEADER_LIST = [ "REMOTE_ADDR", "REMOTE_HOST", "X_FORWARDED_FOR", "TZ", "QUERY_STRING", "CONTENT_LENGTH", "CONTENT_TYPE", "LC_CTYPE", "SERVER_PROTOCOL", "SERVER_SOFTWARE", ] MASKED_DATA = "XXXXXXXXX" CONTENT_TYPE_JSON = "application/json" CONTENT_TYPE_METHOD_MAP = {CONTENT_...
# Copyright (c) 2010 Jeremy Thurgood <firxen+boto@gmail.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, mod...
''' Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 14 + 64 + 34 + 44 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers ...
# Prim algorithm # input where n is weight of each edge # 0,2,1,0,0 # 2,0,1,2,3 # 1,1,0,0,4 # 0,2,0,0,2 # 0,3,4,2,0 import random as rand def printGraph(g): for row in g: print (row) print ("---------------------------\n") def fillGraph (inputfile): graph = [] f = open(inputfile,"r+") n...
from setuptools import setup, find_packages setup( name='pyIID', version='', packages=find_packages(exclude=['doc', 'benchmarks', 'extra', 'scripts', 'examples' ,]), url='', license='', author='christopher', author_email='', description='', requires=['scipy'] )
import torch a = torch.rand((16, 1024, 14, 24)) b = torch.rand((16, 1024, 14, 24)) c = torch.cat([a, b], dim=1) print(c.shape)
import torch import torch.nn as nn from torch.autograd import Variable """ Generator network """ class _netG(nn.Module): def __init__(self, opt, nclasses): super(_netG, self).__init__() self.ndim = 2*opt.ndf self.ngf = opt.ngf self.nz = opt.nz self.gpu = opt.gpu ...
# -*- coding=utf-8 -*- #--------------------------------------- # 程序:豆瓣相册爬虫 # 版本:0.2 # 作者:Will # 日期:2014-07-17 # 语言:Python 2.7 # 功能:将相册中照片全部抓下来 # 改进:优先抓取大图;用户只需输入相册编号,自动计算所有页 #--------------------------------------- import urllib import re import datetime import time import urllib2 impor...
import sys n = int(sys.stdin.readline()) for i in range(n): a, b = list(sys.stdin.readline().strip()) a = ord(a) - ord('a') b = int(b) - 1 t = 0 if 0<=a+2<=7 and 0<=b+1<=7: t+=1 if 0<=a+2<=7 and 0<=b-1<=7: t+=1 if 0<=a-2<=7 and 0<=b+1<=7: t+=1 if 0<=a-2<=7 and 0<=b-1<=7: t+=1 if 0<=a+1<=7 and 0<=b+2<=...
from rest_framework import mixins from rest_framework import viewsets class CreateListRetrieveViewset( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): pass class CreateViewset( mixins.CreateModelMixin, viewsets.GenericViewSet, ): pas...
#!/usr/bin/env python """ The n^(th) term of the sequence of triangle numbers is given by, t_(n) = 1/2n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a w...
# -*- coding: utf-8 -*- import numpy as np """Function used to compute the loss.""" def compute_loss_mse(y, tx, w): """MAE""" e = y - tx.dot(w) return (np.linalg.norm(e) ** 2) / len(y) def compute_loss_mae(y, tx, w): """MSE""" e = y - tx.dot(w) mae = 0.5 * (np.linalg.norm(e, 1)) / len(y) ...
API_HOSTS = { "test": "http://192.168.1.100:11002/wp-json/wc/v3/", "dev": "", "prod": "" } DB_HOST = { }
import sys #sys is built in library(the bread and butter) try: #underneath the block try block, you "try" a piece of code that you think might give you an error #In my case, I didn't install request when running import requests except ImportError: #Write specific error #We are looking for an I...
#!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2017 Massimiliano Patacchiola # # 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 ...
from django.shortcuts import render, redirect from django.http import Http404 from django.contrib import messages from django.core.mail import send_mail from Modelos.models import ( empresas, activi_comerciales, productos, servicios, usuarios, ) from Global.usuario import Usuario from Cliente.carri...
from pathlib import Path from django.urls import path from . import views from .models import Record activity_short = Path(__file__).parts[-2] app_name = activity_short urlpatterns = [ path('', views.FilterRecord.as_view(), name='index'), path('record/', views.GetRecord.as_view(), name='grecord'), path('f...
""" delete.py """ import requests from .exceptions import AgaveFilesError from ..utils import handle_bad_response_status_code def files_delete(tenant_url, access_token, file_path): """ Remove a file or direcotry from a remote system """ # Set request url. endpoint = "{0}/{1}/{2}".format(tenant_url...
def numPaths(y, x): if y==0 and x==0: return 1 if y<0 or x<0: return 0 right = numPaths(y, x-1) down = numPaths(y-1, x) return right+down def test1(): y = 2 x = 3 res = numPaths(y, x) print("res: ", res) test1()
from tqdm import tqdm import numpy as np import os ; os.environ['HDF5_DISABLE_VERSION_CHECK']='2' import tensorflow as tf import tensorflow_datasets as tfds # from codecs import open ds, info = tfds.load('imdb_reviews/subwords8k', with_info=True, as_supervised=True) train_ex...
import random a = [4,5,2] #값에 access a[0] a[1] a[2] # 리스트에 랜덤한 value 5 insert append ''' Data Structure 자료구조 지만 많이 사용되기 때문에 basic part에서 설명함. 선형구조 -initialiaztion -init a = [] a = [1, 2, 3, 4] -Data add append 함수를 사용 for i in range(1,101): a.append(i) -check length len(a) -delete del a[2] -insert a.insert(...
#!/usr/bin/env python3 """ Takes input a relatedness file, a fam file, and a list of individuals and extracts the sub-matrix from the relatedness file for the given individuals Jean-Tristan Brandenburg """ import sys import pandas as pd import numpy as np import argparse EOL=chr(10) def errorMessage10(phe): ...
# -*- coding: utf-8 -*- import h5py import numpy as np from sklearn.utils import shuffle from keras.models import * from keras.layers import * import pandas as pd from keras.preprocessing.image import * # bottleneck产生测试特征 np.random.seed(2017) X_train = [] X_test = [] y_pred = [] for filename in ["gap_InceptionV3.h5...
list=["a","e","i","o","u","A","E","I","O","U"] a=str(input("enter the value:")) if (a in list): print ("vowel") else: print ("consonant")
import pygame class Settings(): '''Класс для хранения всех настроек классификатора рукописных чисел''' def __init__(self): '''Инициализирует настройки классификатора''' #Параметры экрана self.screen_width = 415 self.screen_height = 250 self.bg_color = (100, 150, 255) #Параметры доски для рисования sel...
""" TIME LIMIT PER TEST: 3 seconds MEMORY LIMIT PER TEST: 256 megabytes INPUT: standard input OUTPUT: standard output "Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a posit...
import os def clear(): return os.system('cls') should_continue = True def cipherUnrestricted(message, direction, caesarNumber): cipheredMessage = "" if direction == 'e': for letter in message: if letter.isalpha(): cipheredMessage += chr((ord(letter) - ...
from random import * from metodusok import * from targy import * targyak = Targy("teritve", "troli") print(targyak) also = bekerszam("Alsóhatár?: ",1,7) felso = bekerszam("Felsőhatár?: ",5,10) darab = bekerszam("Darab?: ",1,5) szamok = [] for i in range(darab): #veletlenszam = randint(also,felso) szamok.append...
aa8=int(input()) b6=[int(x) for x in input().split()] zzz=0 for x in range(aa8): for y in range(x): if b6[y]<b6[x]: yyy+=b6[j] print(zzz)
# Created by Brian Mascitello to calculate a specific polynomial's root. def mathproblem(x0): """ function mathproblem(x0) finds a root of the nonlinear function specified by f and fprime. y = 2 ** x - 3 ** (x / 2) - 1; yprime = 0.693147 * (2 ** x) - (1.098612 * 3 ** (x / 2)) / 2; Result x ...
from flask import Flask import bot_nmap as botmap import json app = Flask(__name__) @app.route('/nmap/<ip>',methods=['GET']) def nmap(ip): return json.dumps(botmap.getPorts(ip)) app.run(host='0.0.0.0',use_reloader=False)
import imp, os.path, sys, time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import mockingbeat class MyHandler(PatternMatchingEventHandler): patterns = [] @staticmethod def dispatch(event): if event.src_path == ifn: load() ifn = ofn = None def load(): stdo...
# Необходимо набрать из каждый пары ровно одно число так, чтобы сумма всех выбранных числе не делилась на 31 # и при этом была максимально возможной. f = open("27v01_B.txt", 'r') f_len = int(f.readline()) a = [] for i in range(f_len): j, k = map(int, f.readline().split()) a.append([max(j, k), min(j, k), abs(j-k...
from .views import AccessViewSet def register(router): router.register(r'access', AccessViewSet, base_name='access')
import math import numpy as np, cv2 width = 640 height = 480 referencePoints = np.float32( [[width/4,height/4], [3*width/4,height/4], [3*width/4,3*height/4], [width/4,3*height/4]]) currentPoint = -1 calibrating = True fullScreen = False names = ['0', 'A risada mais engraçada Pânico na TV.avi', 'Sabe de nada inoce...
# Dependencies import requests from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager import pandas as pd from flask_pymongo import PyMongo from pymongo import MongoClient from bs4 import BeautifulSoup as bs def get_mars_table(): #Get Mars Facts mars_facts_url = 'https://space-fa...
# Strings ####################################################################################################################### # # Anton and Artur are old friends. Today they practice in writing strings. Anton must write each string # with the lengths exactly N , based on the alphabet of size M . And Arthur, on...
from notes.infraestructure.adapter.sqlalchemy import SqlAlchemyAdapter from notes.domain.entity.notes import Notes class NotesSqlAlchemyRepository: def __init__(self): self.__adapter = SqlAlchemyAdapter() self.__adapter.entity = Notes def create(self, notes: Notes): try: ...
import unittest from google_finance import GoogleFinance class TddInPythonExample_Plotter(unittest.TestCase): def test_savepng(self): gf = GoogleFinance() gf.plot() def test_addidxcolumn(self): gf = GoogleFinance() reshaped = gf.addidxcolumn([ [-1, 240, 239, 240, ...
from ScenarioHelper import * def main(): CreateScenaFile( "t1310_1.bin", # FileName "t1310", # MapName "t1310", # Location 0x00BD, # MapIndex "ed7161", 0x00002000, # Flags ...
import nltk from urllib.request import urlopen from nltk import word_tokenize Single_PMID = "24964572" PMIDs = ["28483577", "24964572", "27283605"] Pubtator_Info_URL = "https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/export/pubtator?pmids=24964572" Pubtator_Info = urlopen(Pubtator_Info_URL, None, t...
if 'c' in 'Python': print 'YES' else: print 'NO' #http://www.hacksparrow.com/python-check-if-a-character-or-substring-is-in-a-string.html
# -*- coding: utf-8 -*- # cython: language_level=3, always_allow_keywords=True ## Copyright 2007-2018 by LivingLogic AG, Bayreuth/Germany ## Copyright 2007-2018 by Walter Dörwald ## ## All Rights Reserved ## ## See ll/xist/__init__.py for the license """ This namespace module implements Atom 1.0 as specified by :rfc...