text
stringlengths
8
6.05M
from animal import Animal class Lion(Animal): def __init__(self, name, age, habitat, heath_level, hapiness_level, melena): super().__init__(name, age, habitat, heath_level, hapiness_level) self.melena = melena def eating(self, eat): super().eating() if eat < 5: self...
# The following program is the solution to the Binary Search Tree Practice quiz of the Data Structures & Algorithms class by Grow with Google/Udacity class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(sel...
import os from os.path import join, dirname from dotenv import load_dotenv from datetime import datetime from functools import partial from threading import Thread from bokeh.models import ColumnDataSource from bokeh.plotting import figure, curdoc from tornado import gen from proton.reactor import Container from am...
class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. """ num = 0 r_str="" for c in longUrl: num = num*128 + ord(c) return str(hex(num).rstrip("L")) def decode(self, shortUrl): """Decodes a shortened URL to its...
#-*-coding=utf-8-*- from django.core.urlresolvers import reverse from admin_tools.menu import items, Menu class CustomMenu(Menu): def __init__(self, **kwargs): super(CustomMenu, self).__init__(**kwargs) self.children.append( items.MenuItem(title=u'Main', url=reverse('admin:index')) ...
import sys def sum(n, array): arraysum = 0; for i in range(n): print i arraysum += array[i] print arraysum def main(): input1 = [45, 368, 527, 525, 209, 206, 174, 625, 1216, 206, 554, 930, 1101, 239, 591, 371, 971, 659, 620, 903, 424, 488, 590, 514, 807, 252, 394, 898, 557, 137, 165, 592, 495, 682, ...
import pandas as pd import datetime def read_tweets(): """ 读取twitter生成user列表 :return: user列表 """ user_tweet_list = [] with open('Tweets/R_DeodorantCancer.txt') as f2: for line, column in enumerate(f2): column = column.replace('\n', '') user_t_id, tweet_id, conte...
# coding=utf-8 import pymysql from tkinter import * class loginPage(object): def __init__(self, master, info='欢迎进入注册页面'): self.master = master self.mainlabel = Label(master, text=info, justify=CENTER) self.mainlabel.grid(row=0, columnspan=3) self.user = Label(master, text...
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 23:27:36 2021 @author: mtran """ from Patient import * import matplotlib.pyplot as plt if __name__ == "__main__": # Enter the file path to the patient here foldername = "../../histopathology_dataset/" # Enter the patients number here patient_id = "8863...
import pandas as pd def truncate_cell_line_names(data, index=True, separator='_', preserve_str_location=0): ''' This is for truncating cell line names such as 'CAL120_breast' to 'CAL120' Split the input Str by separator, and preserve the No. preserve_str_location th part. Input is DaraFrame, List, or ...
# -*- coding: utf-8 -*- """ Created on Mon May 25 13:25:00 2020 @author: logam """ from scipy import ndimage import matplotlib.pyplot as plt import numpy as np import kernel_function as kf import cv2 import random original = cv2.imread('test2.png')# img = cv2.imread('test2.png', cv2.IMREAD_GRAYSCALE)# plt.figure(dp...
# # @lc app=leetcode.cn id=7 lang=python3 # # [7] 整数反转 # # @lc code=start class Solution: def reverse(self, x: int) -> int: # 1032/1032 cases passed (32 ms) # Your runtime beats 92.87 % of python3 submissions # Your memory usage beats 16.12 % of python3 submissions (15 MB) if x >= 0...
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from config import config app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://'+config.DBUSER+':'+config.DBPASSWD+'@'+config.DBHOST+'/'+config.DBNAME db = SQLAlchemy(app) event_organizers_table = db.Table('event_organizers', ...
#!/usr/bin/env python3 """\ Quickly show test inputs and outputs. Usage: show_test_cases.py [<cases>]... [options] Arguments: <cases> The test cases to show. By default, all cases will be shown. Options: -l --load Only show test cases for the load() function. -d --dump Only...
from mailsend import Mailsend
import os import static.train_model as train # A function to do it def gender_predictor_mnb(a, cv, clf): test_name = [a] vector = cv.transform(test_name).toarray() if clf.predict(vector) == 0: return "Female" else: return "Male" def gender_predictor_dt(a, dv, dclf): # Build Features...
#!/usr/bin/env python # Lists all flavours available import os import pyrax # Credentials pyrax.set_setting("identity_type", "rackspace") creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) cs = pyrax.cloudservers # Gets flavours flvs = cs.flavors.list() # Prints...
import datetime import tempfile import pathlib ### Configuration GOAL = 4500 ### Calculations data = GC.seasonMetrics() # Keep only runs. Don't use GC filters cause that makes it HELLA slow distances = [x for i, x in enumerate(data["Distance"]) if data["Sport"][i] == "Run"] today_distance = sum(distances) today = da...
#!/usr/bin/python3 """Platform for light integration.""" from datetime import timedelta import logging # Import the device class from the component that you want to support from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, PLATFORM_SCHEMA, SUPPORT_BRIGH...
# Generated by Django 2.1.7 on 2019-06-28 08:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contact', '0001_initial'), ] operations = [ migrations.RenameField( model_name='contact', old_name='hone', new_n...
import tensorflow as tf def create_unet(in_shape=[256, 256, 3], out_channels=1, depth=5, training=True, name='UNET'): ''' Creates a UNET model. # Params: in_shape = [batch_size, height, width, channels] depth = number of downsample blocks training = whether or not model is training ...
import unittest import numpy.testing as testing import numpy as np import tempfile import shutil import os import healsparse from healsparse.fits_shim import HealSparseFits class FitsShimTestCase(unittest.TestCase): def test_read_header(self): """ Test reading a fits header """ se...
# Generated by Django 3.0.8 on 2020-08-09 16:09 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('gallery', '0001_initial'), ] operations = [ migrations.CreateModel( ...
from flask import Flask, jsonify, request import sqlalchemy as db from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base import dotenv from flask_jwt_extended import JWTManager from .config import Config from apispec.ext.marsh...
from ABC.Instruction import Instruction from ABC.NodeAST import NodeAST from ST.Type import getTypeString class Primitive(Instruction): def __init__(self, type, value, line, column): self.type = type self.value = value self.line = line self.column = column self.array = False...
''' This is a tic tac toe game for 2 players player 1 = X player 2 = O type start() to start the game The game splits the board into 9 squares, and players enter which square they'd like to mark next 1 | 2 | 3 --------- 4 | 5 | 6 --------- 7 | 8 | 9 ''' board = dict.fromkeys([1, 2, 3, 4, 5, 6, 7, 8, 9], ' ') def pri...
import os import random def load_dataset(path_dataset): """Load dataset into memory from text file""" dataset = [] with open(path_dataset) as f: words, tags = [], [] # Each line of the file corresponds to one word and tag for line in f: if line != '\n': ...
# Make School OOP Coding Challenge Python Problem 7 import sys # Zookeeper class contains a name instance variable class Zookeeper(object): # Initializer def __init__(self, name): self.name = name # Takes a list of animals and food to feed prints out message and # feeds and puts to sleep all...
# Set(集合) # 集合(set)是一个无序不重复元素的序列。 # 基本功能是进行成员关系测试和删除重复元素。 # 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # 输出集合,重复的元素被自动去掉 if('Rose' in student) : print("Rose 在集合中") else : print("Rose 不在集合中") # set可以进行集...
""" ---TASK DETAILS--- --- Day 1: No Time for a Taxicab --- You're airdropped near Easter Bunny Headquarters in a city somewhere. "Near", unfortunately, is as close as you can get. The Document indicates that you should start at the given coordinates (where you just landed) and face North. Then, follow the provided s...
import json import logging from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import InventoryCreationForm, InventoryEditFromAdmin, ToolDistributionForm, ToolDistributionFromAdmin from .handler import InventoryManag...
#!/usr/bin/env python from experiment.artifacts import ExperimentArtifacts from experiment.experiment import Experiment from experiment.model import ProjectModel from utils.arg_parser import TrainArgParser from utils.logger import logger if __name__ == '__main__': logger.info(f"Begin train.py") arg_parser =...
# -*- python -*- # Create an instance of the Dragon, have it: # - walk() three times, # - run() twice, # - fly() twice, # - displayHealth(). # When the Dragon's displayHealth() function is called, it should say 'this is a dragon!' before it displays the default information. # You can achieve this by calling the parent...
"""JOB_PORTAL URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import xgboost as xgb data = pd.read_csv('Data/train.csv', sep=',', header=0) GRADES = ['Ex', 'Gd', 'TA', 'Fa', 'Po'] data['LotF...
print j,g print i,h from skimage import img_as_ubyte print out.min(), imgr.min(), out.max(), img.max(), type(out[0,0]), type(imgr[0,0]) print type(op), op.shape, type(op[0,0]) print op.max(), op.min() boole= imgr < 188 ac=img_as_ubyte(boole) plt.imshow(boole,cmap='gray') print 'lol', ac.shape, type(ac), ac...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ iCEBreaker Platform definitions. The iCEBreaker Bitsy is a non-core board. To use it, you'll need to set your LUNA_PLATFORM variable: > export LUNA_PLATFORM="luna.gat...
#5 Список стипендиатов name = ['Войкин Владимир','Разенко Виктория','Ложкина Юлия','Калинина Татьяна', 'Тишина Дарья', 'Самостроенко Алена'] x = [[2,4,3,3],[5,5,4,5],[3,5,4,4],[4,4,4,5],[4,3,4,4],[4,5,4,5]] w = ['Русский язык','Математика','Физика', 'История'] y = 0 print('Стипендиаты:') for i in range(len(name)): ...
from django.contrib import admin from . models import ClienteBD admin.site.register(ClienteBD) # Register your models here.
#!/usr/bin/env python3 # Advent of code Year 2019 Day 4 solution # Author = seven # Date = December 2019 with open((__file__.rstrip("code.py") + "input.txt"), 'r') as input_file: input = input_file.read() start, end = tuple([int(i) for i in input.split('-')]) def int_to_list(num): return [int(d) for d in s...
from datetime import datetime, timedelta from os import environ from pytz import utc from rq.decorators import job from qmk_redis import redis from qmk_storage import list_objects, delete # Configuration STORAGE_TIME_HOURS = int(environ.get('S3_STORAGE_TIME', 24)) @job('default', connection=redis) def cleanup_stor...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 11:21 # @Author : Administrator # @Site : # @File : collections_overview # @Software: PyCharm from collections import *
from __future__ import unicode_literals from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='tilereduce', version='0.0.1', description="Run tile-reduce map jobs in Python ", ...
#!/usr/bin/python ######################################## # Patch/descriptor extraction utility. # # # # Author: ilja.kuzborskij@idiap.ch # ######################################## from argparse import ArgumentParser from glob import glob from os.path import splitext, join, b...
#cleaning data in python #full_stack data analysis #data analysis is more than just fitting models 1.understand, 2.Tidy/reshape, 3.clean, 4.combine #steps of data cleaning #look at your data,Tiday/reshape your data, clean and prepare your data #data analysis #the course focuses on cleaning data #End goal:produ...
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404, redirect from annoying.decorators import render_to from django.contrib.auth.decorators import login_required from Aluno.views.utils import aluno_exist from Avaliacao.Questao.models import QuestaoDeAvaliacao @aluno_exist @login_required @render_t...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 """ import Explicator.explicator as e def typemsg(msg): """ Fonction qui analyse le type du message, et reconnait si c'est une question ou une exclamation. Si c'est une question, on renvoi s...
import json import unittest import pyyoutube import responses class ApiChannelSectionTest(unittest.TestCase): BASE_PATH = "testdata/apidata/channel_sections/" BASE_URL = "https://www.googleapis.com/youtube/v3/channelSections" with open(BASE_PATH + "channel_sections_by_id.json", "rb") as f: CHANN...
import sys sys.path.insert(0, '/home/graphicsminer/Projects/image-captioning/data-prepare/coco/PythonAPI') import matplotlib matplotlib.use('Agg') from pycocotools.coco import COCO import matplotlib.image as mpimg import matplotlib.pylab as plt import scipy.misc from LayerProvider import * from NeuralNet import * impo...
import unittest # self.assertEqual(a, b) # self.assertNotEqual(a, b) # self.assertTrue(x) # self.assertFalse(x) # self.assertRaises(TypeError) # assertIs(a, b) # assertIsNot(a, b) # assertIsNone(x) # assertIsNotNone(x) # assertIn(a, b) # assertNotIn(a, b) # assertListEqual(a, b) # assertTupleEqual(a, b) # assertDictEq...
def build_map(fileLocation): mapFile = open(fileLocation, 'r') linesOfFile = mapFile.readlines() for index in range(len(linesOfFile)): linesOfFile[index] = linesOfFile[index].strip() linesOfFile[index] = linesOfFile[index].split() #removing the bad lines nuList = [] for line in ...
# coding: utf-8 # In[86]: import pandas as pd df_ori = pd.read_csv('data\\dw_cl_jl_high_value.csv',delimiter='|') df_user = pd.read_csv('data\\all_user_7in8not.csv') data=pd.merge(df_user,df_ori,how='left',left_on='USER_ID_7in8not',right_on='USER_ID') data.head() # In[87]: category_cols=['CITY_DESC','DESC_1ST',...
from getpass import getpass from time import sleep from subprocess import Popen import urllib.error from urllib.parse import urlencode, urlparse, parse_qs, unquote from urllib.request import urlopen, build_opener, HTTPCookieProcessor, urlretrieve from http.cookiejar import CookieJar from bs4 import BeautifulSoup as BS ...
#!/usr/bin/python #File name: if.py number = 23 guess = int(input('Enter an integer:')) if guess == number: print ('Congurations, you guessed it.') print ('But you do not win any prizes!') elif guess < number: print ('No, it is a litter higher than that') else: print ('No, it is a litter lower than that') print...
from ficha import Ficha from casilla import Casilla class Othelo: N = 8 def __init__(self, turno = 1): self.tablero_ = [[Casilla(X,Y) for Y in range(0, self.N)] for X in range(0, self.N)] self.confInicial() self.NroFichas = 4 #inicializar las 4 fichas self.turno_ = 1 ...
#!/usr/bin/env python """ okdist.py ============= Used from Opticks okdist- bash functions. """ import os, logging, argparse log = logging.getLogger(__name__) from opticks.bin.dist import Dist class OKDist(Dist): """ Creates a mostly binary tarball of the Opticks build products along with some txt file...
from pylab import * from scipy import signal from scipy.optimize import curve_fit from . import base as wl class Light(wl.Fringes): """ パラメータ ------------ wl_c : (val) 中心波長[um] wl_bw : (val) 波長のバンド幅[um] wl_step : (val) 波長のステップ幅[um] 属性 ------------ scale_ : (array) 走査鏡の変位[um] f...
import boto3 def create_launch_config(conig_name, image_id, inst_type): """ A function to create a launch configuration """ client = boto3.client('autoscaling', region_name='ap-south-1') # creating the launch configuration response = client.create_launch_configuration( LaunchConfigurat...
from kademlia.network import Server from nkms.crypto import api as API from nkms.crypto.constants import NOT_SIGNED, NO_DECRYPTION_PERFORMED from nkms.crypto.powers import CryptoPower, SigningPower, EncryptingPower from nkms.network.server import NuCypherDHTServer, NuCypherSeedOnlyDHTServer class Character(object): ...
from threading import Thread from src.utils.templates.workerprocess import WorkerProcess class MovementControl(WorkerProcess): # ===================================== INIT ========================================= def __init__(self, inPs, outPs): """Controls the speed and steering of the vehicle ...
""" script to analyze the PSD cut for IBD events and NC events, that pass all cuts (except of PSD cut): not all events are analyzed like in analyze_PSD_cut.py, but only the events that pass all cuts (analyzed with analyze_spectrum_v2.py) For each time window, the TTR values of events that pass all cuts (e...
# Generated by Django 2.1.3 on 2019-03-02 07:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0011_auto_20190225_1931'), ] operations = [ migrations.AddField( model_name='companystuff', name='role', ...
from rest_framework import serializers from api.models import APIInfo class APIInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = APIInfo fields = "__all__" class APISerializer(serializers.ModelSerializer): class Meta: model = APIInfo fields = "__all__...
from datetime import datetime, timedelta from substrateinterface import SubstrateInterface from substrateinterface.extensions import SubstrateNodeExtension import logging logging.basicConfig(level=logging.DEBUG) substrate = SubstrateInterface(url="wss://rpc.polkadot.io") substrate.register_extension(SubstrateNodeEx...
import warnings import logging import sklearn from asl_data import SinglesData logging.basicConfig(level=logging.INFO) def recognize(models: dict, test_set: SinglesData): """ Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object,...
from abc import ABC, abstractmethod class Instruction(ABC): def __init__(self, line, column): self.line = line self.column = column self.array = False super().__init__() @abstractmethod def interpreter(self, tree, table): pass @abstractmethod def getNode(s...
''' Utility methods allowing to reconfigure UNICORE components easily. Low level interface, rather not used directly in configurators. @organization: ICM UW @author: K.Benedyczak @: golbi@icm.edu.pl @author: R.Kluszczynski @: klusi@icm.edu.pl ''' import tempfile, os import sys import stat import sh...
# 0709 - 조별실습 import csv import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as func import torch.optim as optim from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from torch.utils.data import Dataset, DataLoader class Net(nn....
from django.contrib import admin import xadmin from .models import CustomSelection,CustomBacktest # Register your models here. @xadmin.sites.register(CustomSelection) class CustomSelectionAdmin(object): pass @xadmin.sites.register(CustomBacktest) class CustomBacktestAdmin(object): pass
# -*- coding: utf-8 -*- REQUIRED_INPUT_INFO = { "target": "Target temperature mode value.", "logs": [ { "file": "*** SEND A LOG FILE AS BASE64 STRING ***", "sensors_count": "How many sensors to parse from the file.", } ], "sensors_total": "How many sensors to us...
from spotibot.base.auth import OAuth
def vowel_shift(text, n): if not text: return text non_vowels = [] only_vowels = [] vowels = set('aeiouAEIOU') for a in text: if a in vowels: only_vowels.append(a) non_vowels.append('{}') else: non_vowels.append(a) if not only_vowels: ...
# ============================================================================== # Copyright (c) 2019, Deutsches HörZentrum Hannover, Medizinische Hochschule Hannover # Author: , Waldo Nogueira (NogueiraVazquez.Waldo@mh-hannover.de), Hanna Dolhopiatenko (Dolhopiatenko.Hanna@mh-hannover.de) # All rights reserved. ...
#!/usr/bin/python # coding: utf-8 from Aparelho import * class SOM(Aparelho): pass
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('civ_5_tracker', '0005_auto_20150205_1128'), ] operations = [ migrations.AlterModelOptions( name='game', ...
""" Example program using IBM_DB_DBI against Db2""" # import os import sys import getpass import platform import ibm_db_dbi from db2_helpers import db_load_settings # -------------------------------------------------- # Database Connection Settings # -------------------------------------------------- database = "sampl...
import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import time BROKER_IP = "192.168.178.61" # this is my local mqtt broker BROKER_PORT = 1883 # standard mqtt broker port BROKER_TOPIC = "Games/Pong" CLIENT_ID = int(time.time()*1000) # use time as id # The callback for when the client re...
import socket # 默认是 family=AF_INET, type=SOCK_STREAM # type: # SOCK_STREAM : TCP # SOCK_Dgram: UDP # family # family=AF_INET :服务器之间的通信 # family=AF_UNIX : unix 不同进程间的通信 # 1) 创建socket,使用默认参数 # ss = socket.socket() # # # 2) 为socket绑定ip地址和端口 # # address=('127.0.0.1',8000) # ss.bind(address) # # ...
from ctypes import * from numpy.ctypeslib import ndpointer import numpy as np ############### lib definitions ############### mysofa_lib = cdll.LoadLibrary("libmysofa.so") mysofa_open = mysofa_lib.mysofa_open mysofa_open.restype = c_void_p mysofa_open.argtypes = [c_char_p, c_float, POINTER(c_int), POINTER(c_int)] mys...
from .base import * DEBUG = True ALLOWED_HOSTS = ['*'] DEV = DEBUG INSTALLED_APPS += ('debug_toolbar',) {% if cookiecutter.postgres == "y" or cookiecutter.postgres == "Y" %} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', ...
import os import flask import json from flask import Flask, _app_ctx_stack, render_template, request, jsonify, Response from flask_cors import CORS, cross_origin from flask_mail import Mail from whitenoise import WhiteNoise import jwt from functools import wraps, update_wrapper from sqlalchemy.orm import scoped_session...
from __future__ import print_function, division import pygame import OpenGL.GL as gl import numpy as np import itertools import neurodot_present as npr class TrueBrightnessPatch: def __init__(self, width, # OpenGL units height, # OpenGL units pix_w, # OpenGL unit...
import sys import nltk import sklearn import pandas import numpy # for checking the versions print('Python: {}'.format(sys.version)) print('NLTK: {}'.format(nltk.__version__)) print('Scikit-learn: {}'.format(sklearn.__version__)) print('pandas: {}'.format(pandas.__version__)) print('numpy: {}'.format(numpy.__version__...
#pip install paho-mqtt import paho.mqtt.publish as publish import Adafruit_DHT import time import datetime import busio import digitalio import board import adafruit_mcp3xxx.mcp3008 as MCP from adafruit_mcp3xxx.analog_in import AnalogIn # colocamos el channelID de nuestro canal de thingspeak channelID="1326958" # colo...
from cryptography.fernet import Fernet import sys import os # Key generation cipher_suite = Fernet(os.environ['FERNET_KEY'].encode()) def encode(text: str) -> str: return cipher_suite.encrypt(text.encode()).decode('utf-8') def decode(text: str) -> str: return cipher_suite.decrypt(text.encode()).decode('utf-8...
from flask import Flask from flask import jsonify from flask import request from flask_pymongo import PyMongo from flask import Response from flask import request from flask import json import urllib from math import sqrt import numpy as np from sklearn.metrics.pairwise import pairwise_distances from bson.json_util imp...
class Calculator(): # METORY - FUNKCJE KTORE SA CZESCI AKLASY def __init__(self): # metoda magiczna, to taka ktora ma __ przed i po sobie - wykonywne przez pythona print("init") def __del__(self): print("DEL")# służy żeby pozamykac pliki pootwierane # def __str__(self):# zwr...
import sys import os f = open("C:/Users/user/Documents/python/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- n,a,b,c = map(int,input().split()) l = [] for i in range(0,n): l.append(input()); map(int,l)
#!/usr/bin/env python2.6 # # Copyright (c) Members of the EGEE Collaboration. 2006-2009. # See http://www.eu-egee.org/partners/ for details on the copyright holders. # # 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 ...
#!/usr/bin/python3 import sys print(sys.argv) print(sys.argv[1]) sys.stderr.write("i am stderr!\n") sys.stderr.flush() sys.stdout.write("i am stdout\n")
from django.contrib import admin from .models import Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): search_fields= ['message'] list_display=['pk','message','author']
#!/usr/bin/env python from __future__ import print_function from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image from matplotlib import pyplot as plt from joblib import load from sklearn.svm import SVC from exercise6.srv import * import sklearn import cv2 import rospy import numpy as np impo...
#Method 1 def armstrong1(num): temp_1=temp_2=num string=list() def noOfDigits(temp_1): count=0 while temp_1!=0: temp_1=temp_1//10 count+=1 return count n=noOfDigits(temp_1) armstrong=0 while temp_2!=0: r=temp_2%10 ...
__all__ = ["Applicant", "BaseModel" "City", "Interviewer", "InterviewSlot", "Mentor", "School"]
import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn import svm from sklearn.semi_supervised import label_propagation from sklearn import decomposition mark = pd.read_csv("C:/Users/ASUS/Desktop/3f/4c.csv") marks=mark.v...
#!_*_conding_*_ if __name__ == "__main_": pass
from django.http import HttpResponse from django.shortcuts import render def homepage(request): #when someone looks for this home page, it will send this request. Which url they are looking return HttpResponse("<h1>Homepage</h1>") def eggs(request): return HttpResponse("<h1>Eggs are great</h1>")
# delete_nth=[1,1,1,1] # def remove(a): # delete_nth.pop(-1) # print(delete_nth) # remove(2) # def delete(a): # list1=[1,1,2,3] # i=0 # while i<len(list1): # list1.remove(list1[-i]) # i=i+1 # print(list1) # delete(2) # list1=[1,1,2,3] # list2 = [] # num = int(input("number : "...
#encoding=utf-8 import cv2 #导入opencv2库 img = cv2.imread("./images/beach.jpg") #载入图片,图片路径有两种斜杠 cv2.imshow("HelloCV", img) #显示图像 cv2.imwrite("D:/save1.jpg", img)#保存图片 cv2.waitKey(0) #等待用户输入键,退出
from time import gmtime, strftime class Log: # flags disponible pour les logs LOG_INFO_ENABLE = 1 << 0 LOG_DEBUG_ENABLE = 1 << 1 LOG_WARNING_ENABLE = 1 << 2 LOG_ERROR_ENABLE = 1 << 3 LOG_ALL_ENABLE = 15 # variable a setter avec les valeurs ci-dessus pour choisir quel type de log afficherflags = 0 flags = 0 @...