text
stringlengths
38
1.54M
#!/usr/env/bin python """ Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ class Solution: ...
# content of test_assert1.py ''' def f(): return 3 def test_function(): assert f() == 4 ''' import pytest def test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0
# -*- coding: utf-8 -*- from __future__ import unicode_literals RULE_STRATEGY_RES_SMS = 'RES_SMS' RULE_STRATEGY_LISTEN_LOG = 'LIS_LOG' RULE_STRATEGY_CHOICES = ( (RULE_STRATEGY_RES_SMS, 'Respond SMS'), (RULE_STRATEGY_LISTEN_LOG, 'Listen SMS & CALL'), ) RULE_TYPE_DEVICE = 'DEV' RULE_TYPE_ACTION = 'ACT' RULE_TYP...
from typing import Iterable from xml.etree import ElementTree as ET from upnpavcontrol.core import didllite ET.register_namespace('upnp', 'urn:schemas-upnp-org:metadata-1-0/upnp/') ET.register_namespace('dc', 'http://purl.org/dc/elements/1.1/') ET.register_namespace('avt-event', 'urn:schemas-upnp-org:metadata-1-0/AVT/...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 20 09:51:20 2018 @author: philippe """ # import bempp modules import bempp.api from bempp.api.operators.potential import helmholtz as helmholtz_potential # import usual python librairies bempp.api.global_parameters.assembly.boundary_operator_assemb...
#!C:\Users\amham\AppData\Local\Programs\Python\Python38-32\python.exe #!python print("Content-Type: text/html") print() #number print(1) #string print('hello world') #boolean print(True) print(False) #expression print(1+1) print('hello'+'world') #hello world #comparison operator print(1==1) print(1<2) ...
#!/usr/bin/env python import tkinter as tk import seaborn as sns import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt def create_plot(color): #create plot sns.set(style = 'white') data = np.random.rand(...
from django.shortcuts import render from products.models import * from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def catalog_all(request): products_list = ProductImage.objects.filter(is_active=True, is_main=True, product__is_active=True).order_by("-id") paginator = Paginator(pro...
from Stack import Stack my_stack = Stack() my_stack.push(1) my_stack.push(3) print(my_stack) print(my_stack.pop()) print(my_stack.peek()) print(my_stack.pop()) print(my_stack.pop())
#!/user/bin/even Python3 # -*- coding:utf-8 -*- # utils.py # 工具类 # author:zhaohexin # time:2020/2/19 3:11 下午 import datetime from django.db.models import Count from testcase.models import Testcases from configures.models import Configures def get_count_by_project(datas): """ 1、计算当前接口所关联的配置数及用例数 2、对时间进行格式化...
#Given an open file that maps group names to object names, get maps of group -> object, object -> group #Each line of the file should be a tab-separated list of names, where object names follow group name #For example: #[...
""" Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.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, m...
import tensorflow as tf def weight_variable(name, shape): """ Create a weight variable with appropriate initialization :param name: weight name :param shape: weight shape :return: initialized weight variable """ initer = tf.contrib.layers.xavier_initializer(uniform=False) return tf.get...
import sys import os import re import numpy as np import adagram import multiprocessing from functools import partial import warnings import argparse warnings.filterwarnings("ignore") WINDOW_SIZE = 3 def find_context(ind, words, window=WINDOW_SIZE): if ind - window < 0: start = 0 else: start ...
import re with open('8.in') as f: instructions = [x.strip() for x in f.readlines()] acc, ip, executed = 0, 0, set() while True: if ip in executed: print(acc) break executed.add(ip) cmd, val = re.match(r'(acc|jmp|nop) ([+\-][\d]+)', instructions[ip]).groups() ...
# -*- coding: utf-8 -*- from core.views.helpers.Helper import Helper class Html(Helper): """Html Helper Class for rendering well formatted html elements""" charset = "UTF-8" tags = { 'meta' : '<meta{0}/>', 'metalink' : '<link href="{0}"{1}/>', 'link' : '<a href="{0}"{0}>{2}</a>',...
import numpy as np def conv_forward(input_data, filters, bias, padding=0, stride=1): """ :param input_data: input m x nc x iw x ih :param filters: filter nf x nc x fw x fh n为filter数量 :param bias: bias 每一filter对应一个实数b nf x 1 :param padding: padding layer:l :param stride: stride layer:l :r...
""" 《邢不行-2020新版|Python数字货币量化投资课程》 无需编程基础,助教答疑服务,专属策略网站,一旦加入,永续更新。 课程详细介绍:https://quantclass.cn/crypto/class 邢不行微信: xbx9025 本程序作者: 邢不行/西蒙斯 # 课程内容 - 列表介绍 - 列表常见操作 功能:本程序主要介绍python的常用内置数据结果,如list、dict、str等。希望以后大家只要看这个程序,就能回想起相关的基础知识。 """ # =====list介绍 # 使用[]中括号就可以新建一个数组。 # list_var = [] # 这是一个空list # print(list_var, ...
from django.test import TestCase, Client from student.models import Student class StudentTestCase(TestCase): def setUp(self): Student.objects.create( name='wei', sex=1, email='wei@123.com', profession='程序员', qq='333', phone='3222', ...
import os import SCons #Env = Environment() ProjectName="SMFC4B0" OutFile="./Out\\"+ProjectName # name of the final executable. LibFile="./Lib\\" # name of the final executable. DllFile="./Dll\\" # name of the final executable. ObjDir=str("./Obj/") # Directory for the obj files. IncDir=str("./Inc/") Recurs...
import sys from PyQt5 import QtWidgets, QtCore, QtGui from GuiLayOut2 import Ui_MainWindow from SerialConnect import SerialConnect class AppWindow(QtWidgets.QMainWindow): serialCom = SerialConnect() def __init__(self): super(AppWindow, self).__init__() self.ui = Ui_MainWindow() self.ui...
#Anna Wójcik import numpy as np import math A =np.matrix([[1, 2/3, 2, 5/2, 5/3, 5], [3/2,1,3,10/3,3,9], [1/2,1/3,1,4/3,7/8,5/2], [2/5,3/10,3/4,1,5/6,12/5], [3/5,1/3,8/7,6/5,1,3], [1/5,1/9,2/5,5/12,1/3,1]]) B= np.matrix([[1, 2/5,3,7/3,1/2,1], [5/2,1,4/7,5/8,1/3,3], [1/3,7/4,1,1/2,2,1/2], ...
#!/usr/bin/env python import os, sys import time import devicemanagerSUT as devicemanager from sut_lib import clearFlag, setFlag, checkDeviceRoot, stopProcess, checkStalled, waitForDevice if (len(sys.argv) <> 2): print "usage: cleanup.py <ip address>" sys.exit(1) cwd = os.getcwd() pidDir = os.path....
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Jun 17 206) ## http://www.wxformbuilder.org/ ## ## PLEASE DO "NOT" EDIT THIS FILE! ########################################################################### impor...
from ESD import EnumSubDomain import requests import os class subdomain(object): def __init__(self): self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36', 'Referer':'https://www.baidu.com', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from outis_post.models import OutisPost from outis_user.models import OutisUser class OutisPostCollection(models.Model): user_id = models.ForeignKey(OutisUser, on_delete=models.CASCADE) post_id = models.ForeignKey(Ou...
import numpy as np class CylinderModel(): def __init__(self, distance_threshold, tuple_radius_minmax, tuple_theta_phi): #TODO: change theta phi behaviour self.n = 2 self.name = 'cylinder' self.t = distance_threshold self.minradius = tuple_radius_minmax[0] self.maxradius = t...
#Crea un programa que pida: Nombre, Edad, Teléfono, Dirección, Email y Nacionalidad e imprima un #mensaje personalizado para él donde diga algo similar a lo siguiente: #Hola Luis, me dijiste que tienes 43 años de edad y que tu teléfono es el 3315648790, además sé que #tu dirección es Independencia #23 y tu correo e...
a = [] s = input() while s != "end": s = s.replace(" ","") a.append(s) s = input() b = [i for i in a[0::4]] c = [i for i in a[1::4]] d = [i for i in a[2::4]] e = [i for i in a[3::4]] print(b) print(c) print(d) print(e)
""" Listas Tipos de elementos en una lista Acceder y modificar lo elementos de una lista """ miLista = ["uno", "dos", "tres", "cuatro", "cinco"] print(miLista[-1]) print(miLista[-2]) print(miLista[-3]) #miLista[-1] = 14 #miLista[-1] = "String" print(miLista[-1]) #miLista[1] print(miLista[3:]) # ["cuatro", "cinco"]...
import unittest import json import iris.server as server def to_json(data): return json.dumps(data) def response_json(response): return json.loads(response.data.decode("utf-8")) class IrisInputValidationTest(unittest.TestCase): request_url = '/iris/v1/predict' def setUp(self): self.app = ser...
# job class class TableJob(object): def __init__(self, sql_list): self.sql_list = sql_list self.id = '' self.t_year = '' self.t_month = '' self.t_day = '' self.t_hour = '' self.t_minute = '' self.t_second = '' self.function_name = '' se...
# Simple Function # Parts ; 'def' 'function_name''(parameters & arguments)' def plus(x, y): print(x+y) # plus(4, 5)
Global = None WIDTH = 300 HEIGHT = 300 def _init(): global Global Global = {} def set_value(key: str, value): global Global Global[key] = value def get_value(key: str): global Global return Global[key]
import argparse import random def euro_lotto(): numbers = random.sample(xrange(1,50),5) lucky = random.sample(xrange(1,11),2) numbers.sort() lucky.sort() print "Chosen numbers are %s, %s, %s, %s and %s" % ( numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]) print "Lucky stars a...
from django.urls import path, include from rest_framework.authtoken import views as auth_views from rest_framework.routers import DefaultRouter, SimpleRouter from . import views router = DefaultRouter() router.register('profile', views.UserProfileViewSet) router.register('incidents', views.IncidentsViewSet)...
# 06_is_palindrome def is_palindrome(s): if s == '': return True else: if s[0] == s[-1]: return True and is_palindrome(s[1:-1]) else: return False print is_palindrome('abba')
# -*- coding:utf-8 -*- from __future__ import division import time import numpy as np import pycrfsuite as crf from sklearn.cross_validation import KFold from sklearn.grid_search import ParameterGrid from metrics import scorer, f1_score class GridSearch(object): def __init__(self, param_searches, param_base=...
""" Search harder for service dependencies. The APT, Yum, and files backends have already found the services of note but the file and package resources which need to trigger restarts have not been fully enumerated. """ from collections import defaultdict import logging import os.path import re import subprocess # P...
from django.contrib import admin from .models import * admin.site.register(Book) admin.site.register(Reviews) admin.site.register(Borrower) admin.site.register(Genre) admin.site.register(Language) admin.site.register(Status) admin.site.register(Borrowing_duration) admin.site.register(Late_return_charge)
''' Project Euler Problem #30 Approach: get all possible combinations of digits and find answer ''' import itertools nums = range(10) #change combination to numbers def inNum(p, s): if len(p) != len(s): return False st = list(p) for c in s: if int(c) in st: st.remove(int(c)) ...
class Solution: def minRemoveToMakeValid(self, s: str) -> str: sym = 0 ans = '' temp = [-1] for index in range(len(s)): if s[index] == '(': temp.append(index) sym += 1 elif s[index] == ')': if sym > 0: ...
from invoke import task, Collection from . import build, deploy, provision @task(aliases=['ipython']) def shell(c): "Load a REPL with project state already set up." pass @task(aliases=['run_tests'], default=True) def test(c): "Run the test suite with baked-in args." pass ns = Collection(shell, test,...
import os from ..ReportGitDownload import * # Report how much data is downloaded from the GHE instance for a specific repository class ReportGitHubGitDownload(ReportGitDownload): def name(self): return "github-git-download" def metaName(self): return self.repository + "/" + self.name() def fileName(self): ...
from PyQt5.QtWidgets import QTextEdit, QHBoxLayout class OutputText(QTextEdit): name = 'output_frame' def __init__(self, parent, output: str): super().__init__(parent=parent) self.parent = parent self.setObjectName(OutputText.name) self.output = output self.insertPlainText(output) self.setReadOnly(Tr...
import requests BASE = "http://127.0.0.1:5000/" response = requests.get("http://monikaantwan.pythonanywhere.com/destinationList/1/1") print(response.json())
from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from Bikes import models, forms ...
import matplotlib.pyplot as plt import numpy as np def reduce_array(array, n): idx = np.arange(0, len(array), n) return array[idx] def format_time(array): array = array - min(array) return array / 60 def save_plot(x, tensione, corrente, temperatura, data_path): plt.style.use('bmh') x = for...
""" An asynchronous client for Google Cloud KMS """ import json import os from typing import Any from typing import AnyStr from typing import Dict from typing import IO from typing import Optional from typing import Tuple from typing import Union from gcloud.aio.auth import AioSession # pylint: disable=no-name-in-mod...
#object:-if card matches it will speak Permission Granted #sudo apt-get install espeak ...to install espeak import serial from time import sleep ser = serial.Serial("/dev/serial0",9600,timeout=1) from os import system i = 0 while True: val = ser.read(12) sleep(.1) if len( val.strip() ) =...
import pytest from votesmart.methods.measure import * def test_Measure(): method = Measure(api_instance='test')
from django.db import migrations pizza_type_master_data = [ {"type": "Regular"}, {"type": "Square"} ] pizza_size_master_data = [ {"size": "Small"}, {"size": "Medium"}, {"size": "Large"} ] pizza_topping_master_data = [ {"topping": "Onion"}, {"topping": "Tomato"}, {"topping": "Corn"}, ...
# Generated by Django 2.0 on 2018-01-10 06:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('org', '0006_auto_20180110_0631'), ] operations = [ migrations.RemoveField( model_name='user_con_company', name='Company', ...
from src.database import SQLDatabase from src.outlier_model import OutlierModel import pandas as pd from pathlib import Path import os import logging import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html import dash_table from dash.dependencies import Input, Outp...
# -*- coding: utf-8 -*- prev = [1, 2]; sum = 2; now = 0; while (now <= 4000000): now = prev[0] + prev[1]; prev[0] = prev[1]; prev[1] = now; if (now % 2) == 0: sum += now; print sum;
''' Quick sort using list comprehension. ''' def quick_sort(lst): # Checks length of list. if len(lst) <= 1: return(lst) # Sets pivot in the middle pivot= lst[(len(lst) // 2)] # Sort numbers less than pivot. left = [x for x in lst if x < pivot] middle = [x for x i...
# -*- python -*- # Copyright (C) 2013, MagicLinux. # Author: Yang Zhang <zy.netsec@gmail.com> # All rights reserved. # # This program 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 2, or (at y...
import sqlite3 import mysql.connector # TODO: Write proper documentation class DatabaseHandler: def __init__(self): self.conn = sqlite3.connect('rass.db') self.cur = self.conn.cursor() self.cur.execute(""" CREATE TABLE IF NOT EXISTS emails( id INT PRIMARY KEY, ...
def letters(digit): if digit in (1, 2, 6): return 3 elif digit in (4, 5, 9): return 4 elif digit in (3, 7, 8): return 5 elif digit == 0: return 0 def tens_letters(digit): if digit in (4,5,6): return 5 elif digit in (2,3,8,9): return 6 elif dig...
# -*- coding: UTF-8 -*- import html5lib, requests import mysql.connector import re import time from bs4 import BeautifulSoup # database info username = 'root' password = '' host = 'localhost' dbase = 'doctor_rating' class crawlYelp: def __init__(self): self.dbconn = mysql.connector.connect(user=usernam...
# coding:utf8 import numpy as np import codecs import torch import torch.utils.data as D from torch.autograd import Variable from collections import deque import pandas as pd word2id = {} # word2id的字典 id2relation = {} # id转关系的字典 max_len = 50 # 字向量的长度 word2id_file = './data/people-relation/word2id.txt' id2re...
import scrapy from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.selector import Selector # from scrapy.contrib.linkextractors import LinkExtractor from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor from kcrawler.items import KcrawlerItem class bzhealthSpider(CrawlSpider): name = 'b...
# -*- python -*- """ MINT - Mimetic INTerpolation on the Sphere MINT computes line/flux integrals of edge/face staggered vector fields. The line and flux integrals are conserved in the sense that closed line integrals of a vector field deriving from a potential or streamfunction are zero to near machine accuracy. MI...
import requests import json import pickle import time from datetime import datetime import logging def save_obj(obj, name): with open('obj/'+ name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name): with open('obj/' + name + '.pkl', 'rb') as f: ...
class ComputeProcessorBase(): #define interface of server action def ServerAction(self, tenat_id, server_id, action): #do nothing just define interface pass
def ans(s): cnt = 0 for i in range(n): if(s[i] in ['2', '4', '6', '8']): cnt += i + 1 return cnt if __name__ == '__main__': n = int(input()) s = input() print(ans(s))
class Stack: def __init__(self): self.items = [] def push(self, data): self.items.append(data) def pop(self): self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) new_stack = Stack() new_stack.p...
from training import Mode from guppy import hpy class SparsifyBase: def __init__( self, model_train_obj, sparsification_weight=5, threshold=1e-3, relaxed_constraints=False, mean_threshold=False, ): self.model_train = model_train_obj self.threshol...
import logging as log import cfnresponse import boto3 import hashlib import uuid log.getLogger().setLevel(log.INFO) secretsmanager = boto3.client('secretsmanager') def main(event, context): fqn = event['StackId'] + event['LogicalResourceId'] physical_id = hashlib.md5(fqn.encode('utf-8')).hexdigest() log.info(p...
from mcpi.minecraft import Minecraft import time as t mc=Minecraft.create() while True: pos = mc.player.getPos() underwater= (mc.getBlock(pos.x, pos.y+1, pos.z) in [8, 9]) if underwater: mc.postToChat("You are underwater") while underwater: t.sleep(0.001) pos = mc.player.getPos() underwater= (mc.getBlo...
import pil import streamlit as st import src.pages.about import src.pages.dataAnalysis import src.pages.dashboard import src.pages.homePage PAGE_PY = { "Home": src.pages.homePage, "About": src.pages.about, "Statistics About COVID": src.pages.dataAnalysis, "Dashboard": src.pages.dashboard } ...
import os import fnmatch import subprocess dic1 = {} dic2 = {} d = {} for dirname,dirs,files in os.walk('/var/bigbluebutton/published/presentation',topdown = False): list1 = [] for name in files: var1 = os.path.join(dirname,name) if fnmatch.fnmatch(name,'*.ogg'): audio_outpu...
import argparse from bitstring import BitArray from PIL import Image argparser = argparse.ArgumentParser(description="Converts 24-bit BMP image to 8-bit RRRGGGBB pixels in COE format") argparser.add_argument("INPUT", help="Input file path") argparser.add_argument("OUTPUT", help="Output file path") args = argparser.par...
import requests from logger import log_error, log_warning, log_info page_id = 104173088514235 access_token = 'EAA6FiKzFv1MBAEJFttTi5hkBN6TbL3rNx9ATFg7Psh1YOCZA15bELbysfu0WZADA9oZAnLDpblvQZAS6FlZAxRWwY05UldU6knrbdZAE0FD54y1MTAiwwpZBmZBv58WgNIs1MLgXiWUqTzZByMCfIilNXs1SQ4jgSC6lZB7ZBCxxJamxP4W2Lh5oJK1' def post_to_fb(i...
class LeveldbDemo(): pass class Leveldb(): def __init__(self, filename="db"): self.db = {} self.filename = filename def open(self): self.file = open(self.filename, 'w+') print self.file se = self.file.read() print se while len(se) > 0: k...
import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle from sklearn.preprocessing import normalize import matplotlib import pylab import random def sigmoid(scores): return 1 / (1 + np.exp(-scores)) def logistic_predict(x, coefficients, label=False): y_predicted = coefficients[0...
import sys n = int(input()) l = [] for line in range(n): l.append(int(sys.stdin.readline())) l1 = list(set(l)) c = len(l1) lc = [l.count(l1[i]) for i in range(c)] mx1 = max(lc) s = lc[:] s.remove(mx1) mx2 = max(s) s1 = set() s2 = set() for i in range(c): if lc[i] == mx1: s1.add(l1[i]) if lc[i] == mx2: ...
# Copyright (c) 2012 United States Government as represented by # the National Aeronautics and Space Administration. No copyright # is claimed in the United States under Title 17, U.S.Code. All Other # Rights Reserved. # # The software in this package has been released as open-source software # under the NASA Open So...
import dash import dash_core_components as dcc import dash_html_components as html from dash_database import DashDatabase class SDBTab: def __init__(self, name, app, db): self.app = app self.db = db self.name = name self.children = [] def tab(self): return dcc.Tab(label=...
import cv2 import matplotlib.pyplot as plt def imreadgray(arquivo): imagem = cv2.imread(arquivo,0) plt.imshow(imagem,cmap='gray') plt.title='Imagem em preto e branco' plt.show() arquivo = input('Arquivo: ') imreadgray('imagens/'+arquivo)
# Generated by Django 3.1.4 on 2021-02-11 16:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pnr', '0020_auto_20210128_1621'), ] operations = [ migrations.AddField( model_name='pnr', name='carrier_code', ...
#!/usr/bin/env python3 # coding: utf-8 import os,sys import tkinter as tk import tkinter.font as font root = tk.Tk() print(font.families()) my_font = font.Font(root,family="渦筆",size="64",weight="normal") # fc-list, wight=normal|bold edit = tk.Text(root, wrap=tk.WORD, font=my_font) # wrap=NONE|CHAR|WORD edit.grid(colu...
"""""" # Standard library modules. import os import sys import glob import shutil import zipfile import tarfile import fnmatch import subprocess from distutils import sysconfig from distutils.ccompiler import new_compiler import logging logger = logging.getLogger(__name__) # Third party modules. import requests impor...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wyxbcga', '0001_initial'), ] run_before = [ ('yiupu', '0002_delete_jpmwh'), ] operations = [ migrations.Rem...
#!/usr/bin/env python # VHDL linter for OHWR coding style import sys import vhdllint.rulesexec import libghdl.thin import libghdl.iirs as iirs # Import all rules from vhdllint.filerules.check_line_length import CheckLineLength from vhdllint.filerules.check_no_blank_line_at_eof import CheckNoBlankLineAtEOF from vhdll...
from utime import sleep_us """ ->See the datasheet ____|___________________________________|_____ | power_off -> 0x00 | | power_on -> 0x01 | | reset -> 0x07 | | cont_h_res_mode -> 0x10 | | cont_h_res...
a=int(input()) n=a reverse=0 while(n!=0): b=n%10 reverse=reverse*10+b n=n//10 print(reverse)
#!/usr/bin/python3 # -*- coding: utf-8 -*- #import python packages #install --> (sudo) apt-get install python-pip --> (sudo) pip install pillow python-ev3dev #running --> run (sudo) python pythonfilename.py imagefilename.png (jpg will work along with others types) --> # you will be given a dialogue --...
import os from RingPy import Ring r = Ring.Ring() user = input("username: ") password = input("password: ") r.Authenticate(user, password) r.EstablishSession() r.GetDevices() outputDir = "data" if not os.path.exists(outputDir): os.mkdir(outputDir) history = r.GetHistory() for h in history: r.GetRecording(h["...
# Compare two files and add the diffs to each other # Nothing will be removed, then program will only add tags # Run using python compare.py file1 file2 # Imports import sys def checker(index, lis, string): for i in range(index, len(lis)): if lis[i] == string: return i return False print ...
"""a collection of context managers that modify file discovery on importings""" import importnb import tingle __all__ = "Markdown", "RST", "YAML", "YML" class LiterateMixin(importnb.Notebook): format = None def get_data(self, path): if self.path.endswith(self.format): return self.code(s...
# -*- coding: utf-8 -*- """ Created on Tue Aug 28 21:10:56 2018 @author: Abhishek """ #import datetime #print("'hello india it's" + str(datetime.datetime.now()))
class Car(object): def __init__(self, price, speed, fuel, mileage, tax): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage self.tax = tax def display_all(self): return '{} {} {} {} {}'.format(self.price, self.speed, self.fuel, self.mile...
def sum_matrix(m): sum1 = 0 for n in m: sum1 += sum(n) return(sum1) print sum_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
import pytest import strawberry from strawberry_django import ModelResolver from .app.models import User, Group @pytest.fixture(autouse=True) def testdata(db): User.objects.bulk_create([ User(name='a', age=10), User(name='b', age=20), User(name='c', age=20), ]) Group.objects.create(...
import random import matplotlib.pyplot import numpy from Tkinter import * import scipy.special def zipf(a): if a <= 1: raise ValueError("The parameter should be greater than 1") a = float(a) b = (2 ** (a - 1)) u = random.random() v = random.random() x = int(u ** (-1/(a-1))) t = (1 + 1/x) ** (a - 1) while v *...
__author__ = 'Swolfod' # -*- coding: utf-8 -*- from utilities.djangoUtils import * from Lushu.models import * from operator import attrgetter from random import randint from django.core.urlresolvers import reverse from Lushu.consts import * def showHome(): majorCities = [city for city in MajorCity.objects.order_b...
import re import urllib import help_fns from hoster import streamcloud from hoster import ecostream from hoster import filenuke from hoster import movshare from sites import movie urlHost = "http://www.movie4k.to/" regexSearchResult = '<TR id="(coverPreview\d{6,7})">\n\W*<TD width="550" id="tdmovies">\n\W*<a href=...
sentence = input("Sentence kiriting: ") for i in range(len(sentence)): if i % 2 == 1: print(sentence[i])
import copy import itertools import os from collections import Counter """ The facts: 174k words ~ in words.txt awk '{print length}' words.txt | sort -n | uniq -c // words length 96 2 978 3 3919 4 8672 5 15290 6 23208 7 28558 8 25011 9 20404 10 15581 11 11382 12 7835 13 5134 14 3198 15 1938 16 112...