text
stringlengths
8
6.05M
#!/usr/bin/python3 # DEVELOPER: https://github.com/undefinedvalue0103/nullcore-1.0/ import vklogging, vk, config, time, vkroot, traceback, pinput, hashlib, threading try: import commands, utils except: print(vklogging._colorize('$FR'+traceback.format_exc())) quit() def null_fnc(): pass vk.log_func=null_fn...
'''' ----------------------------- EJERCICIO N°1 Literales de Python ----------------------------- Escribe una sola línea de código para obtener esta salida de 3 líneas: "Estoy" ""aprendiendo"" """Python""" ----------------------------- '''
import sys, os import pandas as pd import datetime from shutil import move import csv ## write functions based on audio or not audio def create_merged(file_old, file_new, file_merged, mode="audio"): print(mode) print(file_old) bl_value = "***FIX ME***" # """ if mode=="audio": annotid_col =...
print 'Create a module without any parent in your repo.. Done?', raw_input() print "--------------------------------------------------" print "Step 1: Prepare the Project POM" print "--------------------------------------------------" print 'Add two dependencies along with build and repository tags' print '1) your con...
#!/usr/bin/python3 # EASY-INSTALL-ENTRY-SCRIPT: 'demo-py==0.0.0','console_scripts','demo' __requires__ = 'demo-py==0.0.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_poi...
from sonic import * import time def setDir(): time.sleep(0.02) SS1 = printsonic(1) SS2 = printsonic(2) SS3 = printsonic(3) print("SS1 = ",SS1 ,"SS2 = ",SS2 ,"SS3 = " ,SS3) res = 0 if SS1+SS2+SS3 == 0 : res = 1 elif SS2 <=5 and SS2!=0 : ...
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> x =1 #int >>> y=2.8 #float >>> z=1j #complex >>> print (type(x))) SyntaxError: invalid syntax >>> print (type (x) ) <class 'int'> >>> print(type (y) ) <clas...
import os class Card: def __init__(self, name): self.name=name self.image="" self.prix=0.0 self.capacite="" self.extension="None" def save(self, path): if path[len(path)-1]!='/': path=path+'/' path=path+self.extension+".txt" file=open(path,"a"); buffer=self.name+","+str(sel...
import torch import torch.nn as nn from torch.nn.functional import mse_loss, smooth_l1_loss from torch.autograd import Variable import torch.optim as optim from collections import namedtuple import random import numpy as np from model import model from ReplayMemory import ReplayMemory Transition = namedtuple('Transi...
def example_function(): print("THIS IS AN EXAMPLE FUNCTION") def read_antibiotics_file_and_print(): """ Open the file. Note: this assumes the filename and that it exits. If the file doesn't exist, this will cause an error. """ with open("antibiotics.csv") as antibiotics_file: """ ...
from spack import * import shutil import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class OracleocciAbiHackCms(Package): """An ABI hack to occi.h with std=c++17""" homepage = "https://github.com/cms-sw" url = "https://gith...
""" """ from collections import OrderedDict, namedtuple from typing import List, Union, Tuple, Dict Dependency = namedtuple('Dep', 'dependent arc') # int, str class DependencyParse: def is_arc_present_below(self, token_id: int, arc: str) -> bool: raise NotImplementedError @property def style(...
import json import os import luigi import pandas as pd from luigi.contrib.spark import PySparkTask from pyspark.sql import SparkSession from pyspark.sql.functions import max as max_ from bicis.etl.raw_data.unify import UnifyRawData from bicis.lib.data_paths import data_dir class DatasetSplitter(PySparkTask): # ...
# -*- coding:utf-8 -*- import os import sys import time import threading import requests from lxml import etree import urllib reload(sys) sys.setdefaultencoding('utf-8') global flag flag = 1 tag_list = ["热歌","新歌"] # 写dict def writedict(dict): with open('dict.txt','w') as f: f.write...
#!/usr/bin/env python3 import pwn # Set up pwntools for the correct architecture exe = pwn.context.binary = pwn.ELF('../calc') # Run this python script inside tmux like this: # $> tmux # $> ./exploit GDB # It will spawn a separate window with the GDB session pwn.context.terminal = ["tmux", "splitw", "-h"] # Specify ...
import tensorflow as tf import matplotlib import matplotlib.pyplot as plt '''  加载数据集 ''' mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() # 将(-1,28,28)的图片变成(-1,28,28,1) x_train = x_train.reshape((-1,28,28,1)) x_test = x_test.reshape((-1,28,28,1)) # 归一化处理 x_train, x_test = x_tr...
import time from typing import List, Tuple, Union from selenium.common.exceptions import ( NoSuchElementException, TimeoutException, ) from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from sele...
# Copyright 2017 The Forseti Security Authors. 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 required by ap...
# Generated by Django 2.0.1 on 2018-07-21 14:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0005_auto_20180721_1604'), ] operations = [ migrations.RenameField( model_name='course', old_name='degress', ...
# Generated by Django 2.0.5 on 2018-05-24 01:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Animal', fields=[ ...
"""Runs protoc with the gRPC plugin to generate messages and gRPC stubs.""" from grpc_tools import protoc protoc.main(( '', '-I./protos', '--python_out=./protos', '--grpc_python_out=./protos', './protos/raft.proto', )) print('foo')
# -*- coding: utf-8 -*- # @Author : wjn # @File : get_value.py # @describe: 配置文件读取 from common.read_config import ReadIni class GetValue(object): # 读取配置文件 # 获取debug开关的状态 is_debug = ReadIni(node='MODEL').get_value("debug")
from django.apps import AppConfig class QuicklookConfig(AppConfig): name = 'quicklook'
from PIL import Image from os import path, makedirs from argparse import ArgumentParser import cv2 def get_arguments(): parser = ArgumentParser(description='Utility to resize images while keeping aspect ratio') #parser.add_argument("image_path", help="Path to image") parser.add_argument("input_folder", he...
import csv import numpy as np import matplotlib.pyplot as plt import math import scipy.stats from math import * from scipy import interpolate import scipy.signal from scipy.integrate import simps thresholds = np.arange(70) def heaviside(actual): return thresholds >= actual def erfcc(x): """Complementary error...
#!/usr/bin/env python # -*- coding: utf-8 -*- 'Django settings for labman2 project.' DEBUG = True TEMPLATE_DEBUG = DEBUG #ALLOWED_HOSTS = ['127.0.0.1', 'localhost',] import os from os.path import join, abspath, dirname, sep PROJECT_ROOT = abspath(join(dirname(__file__), ".")) def root(*x): "Absolute path to a ...
#CALCULATOR BY:GJAYZ import sys from tkinter import * from tkinter import messagebox #winDows Calculator = Tk() Calculator.geometry() Calculator.title("Calculator By:Gjayz") Calculator.configure() #VARLABLE text_Input = StringVar() operator = "" #FRAME CALCULATOR Calculator_Function = Frame(Calcula...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to parse MacOS keychain database files.""" import argparse import logging import sys from dtformats import keychain from dtformats import output_writers ATTRIBUTE_DATA_TYPES = { 0: 'String with size', 1: 'Integer 32-bit signed', 2: 'Integer 32-bit ...
# # here we are going to define a list # # # name = str(input("Enter your name : ")) # # for i in range(len(name)): # print("Your name {}. letter: {}".format(i, name[i])) website1 = "www.google.com" website2 = "www.istihza.com" website3 = "www.facebook.com" website4 = "www.guru99.com" for names in website1, webs...
""" Python re-implementation of "Learning Background-Aware Correlation Filters for Visual Tracking" @article{Galoogahi2017Learning, title={Learning Background-Aware Correlation Filters for Visual Tracking}, author={Galoogahi, Hamed Kiani and Fagg, Ashton and Lucey, Simon}, year={2017}, } """ import numpy ...
# 4-1 print('4-1') pizzas = ["cheese", "pepperoni", "anchovies", "mushroom"] for topping in pizzas: print('I love ' + topping + ' on my pizza.') print('I really love pizza!') print("\r") # 4-2 print('4-2') animals = ['dogs', 'cats', 'frogs', 'rabbits', 'moles', 'capybaras', 'birds'] for animal in animals: print('A...
from appium import webdriver import pytest from Page_Object_Pro.Page.search import Search_Page from Page_Object_Pro.Base.base import Base class Test_Searchx: def setup_class(self): desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '8.0.0' ...
# Given an array of unique integers salary where salary[i] is the salary # of the employee i. # # Return the average salary of employees excluding the # minimum and maximum salary. class Solution: def average(self, salary): return sum(sorted(salary)[1:len(salary)-1]) / (len(salary) - 2) if _...
# @see https://adventofcode.com/2015/day/10 import re data = '1113122113' def step(n: str): m = re.findall(r'([1]+|[2]+|[3]+|[4]+|[5]+|[6]+|[7]+|[8]+|[9]+|[0]+)', n) nxt = '' for s in m: nxt += str(len(s)) + s[0] return nxt def seq(d: str, steps: int): for _ in range(steps): d = step(d) retur...
#!/usr/bin/env python3 """A daemon that prevents OOM in Linux systems.""" import os from ctypes import CDLL from time import sleep, monotonic, process_time from operator import itemgetter from sys import stdout, stderr, argv, exit from re import search from sre_constants import error as invalid_re from signal import s...
''' Created on Jan 24, 2016 @author: Andrei Padnevici @note: This is an exercise: 6.4 ''' str = input("Please enter a string: ") char = input("Please enter a character: ") print(str.count(char))
import json import os import sys import pandas.io.sql as psql import requests crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/' sys.path.append(crypto_tools_dir) from crypto_tools import * class PopulateCryptoBitstamp(object): """ """ def __init__(self): """ """ ...
from persian_captcha import PersianCaptchaField from captcha.conf import settings as captcha_settings from captcha.models import CaptchaStore, get_safe_now from captcha.fields import CaptchaField, CaptchaTextInput from django import forms class ProducerRegisterForm1(forms.Form): c...
import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_nam...
# # @lc app=leetcode.cn id=187 lang=python3 # # [187] 重复的DNA序列 # # @lc code=start class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: res = [] left, right = 0, 0 window, seen = [], {} while right < len(s): # 扩大窗口,加入s[right] window.append(...
import argparse import time import pandas as pd from sklearn.cluster import DBSCAN from PROJECT import * def main(): parser = argparse.ArgumentParser(description='DBSCAN in Python') parser.add_argument('-f', '--filename', help='Name of the file', required=True) parser.add_argument('-s', '--eps', help='R...
def sumofdigits(num): int_to_string = str(num) test = list(map(int, int_to_string.strip())) return (sum(test)) num = int(input()) sum_of_digits = sumofdigits(num) for i in range(num-1, 10, -1): if(sumofdigits(i) > sum_of_digits): print(i) break else: if(i == 11): ...
#!_*_coding:utf-8_*_ import optparse import socket import json import os class FTPClient: """Ftp Client""" MSG_SIZE = 1024 def __init__(self): self.username = None self.terminal_display = None parser = optparse.OptionParser() parser.add_option("-s","--server",dest="server"...
#!/usr/bin/env python import sys import os import time import ConfigParser import serial from buspirate import BusPirate HIGH = 1 LOW = 0 INPUT = 0 OUTPUT = 1 class SPIClass: def __init__(self, bus): self.bus = bus def begin(self): self.bus.set_mode("spi") # First read byte is h...
from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.directnotify import DirectNotifyGlobal class DistributedTunnelAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedTunnelAI') def __init__(self, air): DistributedObjectAI.__init__(se...
import logging def get_logger(): logger = logging.getLogger(__name__) handler = logging.FileHandler('offers.log') handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) ...
from functools import reduce def f(N,A,B): return print (reduce(lambda a,x:a+1 if x in A else a-1 if x in B else a,N,0))
from utils import read_file def count_trees(right:int, down:int, treemapfile:str): tree_map = read_file(treemapfile) encounters = 0 x = 0 skip = down # print(tree_map[0]) for n in range(1, len(tree_map)): line = tree_map[n] if skip != 1: skip -= 1 # pri...
#!/usr/bin/env python """ pyjld.amqp.client_0_8.layers.frame """ __author__ = "Jean-Lou Dupont" __email = "python (at) jldupont.com" __fileid = "$Id$" __all__ = ['FrameException', 'FrameLayer', ] from pyjld.amqp.client_0_8.base import BaseException from pyjld.amqp.client_0_8.l...
from string import Template from datetime import datetime from sage.matrix.constructor import matrix from sage.calculus.var import var def write_tikz_lines_to_file(lines, filename='new_results.tex', joiner='\n'): joiner = None if isinstance(lines, str) else joiner with open(filename,'w') as fp: ...
######################################## # Name: Joyce Moon # # Andrew ID: seojinm # # Section: B # ######################################## #################### # Question 0 # # Study the notes! # #################### ''' Carefully go over the r...
#!/bin/env python # conding:utf-8
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: """ https://leetcode.com/problems/triangle/ use dp. start from the bottom row. """ n = len(triangle) dp = [[0]*len(triangle[i]) for i in range(n)] dp[-1] = triangle[-1] print(dp)...
from django.views.generic import TemplateView from .models import TextAnimate # Create your views here. class HomeView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) text_animate = TextAnimate.objects.all() ...
from __future__ import division from __future__ import absolute_import import scipy as sp speed_of_light = 299792.458 # Speed of light in km/s class plummer: def __init__(self, a, lum): self.a = a self.lum = lum def nu(self, x): a = self.a return (3/(4*sp.pi * se...
# ============================================================================= # #Programming Assignment 1 - Eliza Chatbot # # #Team Members - Abhishek Shambhu , Jeyamurugan Krishnakumar & Shreyans Singh # # #Team Name - Team Bots # # #Description - We started by importing the regular expression(re), random, d...
import pandas as pd import requests from collections import namedtuple OVERALL_LEAGUE = 314 LEAGUE_API = 'https://fantasy.premierleague.com/api/leagues-classic/' STANDINGS = '/standings/?page_standings=' NUM_MANAGERS = 500 # 10000 def parse_standings_page(standings_page): Entry = namedtuple('Entry', standings_p...
"""Manages Treadmill applications lifecycle. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import os import enum from treadmill import appevents from treadmill import fs from treadmill import su...
#Conditionals "Python conditionals are pretty much like java and javascript the operators are relatively the same and function in the same way" "Python relies on indentation to to define scope so this must be used in python to start an if" if 2>1: print("true") "Elif is pretty much like else if in other language...
# -*- coding: utf-8 -*- from collections import Counter class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: counts1, counts2 = Counter(word1), Counter(word2) return self._check(counts1, counts2) and self._check(counts2, counts1) def _check(self, counts1: dict, co...
from PIL import Image from n1_local_image_descriptors import sift from numpy import * from pylab import * import os def process_image_dsift(imagename, resultname, size=20, steps=10, force_orientation=False, resize=None): """ Process an image with densely sampled SIFT descriptors an...
from typing import List from base.Event import Event class PartialMatch: """ A partial match created at some intermediate stage during evaluation. """ def __init__(self, events: List[Event]): self.events = events self.last_timestamp = max(events, key=lambda x: x.timestamp).timestamp ...
import cv2 import numpy as np def mke_coordinate(image,line_param): slope, intecept = line_param y1 = int(image.shape[0]) y2 = int(y1 *(3/5)) x1 = int((y1-intecept)/slope) x2 = int((y2-intecept)/slope) return np.array([x1, y1, x2, y2]) def avarage_line_intercept(image,lines): l...
from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin (UserAdmin): add_form =CustomUserCreationForm form =CustomUserChangeForm ...
import json from app import db class Game(db.Model): __tablename__ = 'games' id = db.Column(db.String, primary_key=True) state = db.Column(db.Text) song = db.Column(db.Text) scores = db.Column(db.Text) difficulty = db.Column(db.Text) def __init__(self, chatId, state, song=None, scores...
from app import db from app.models import User, Post def cleanAll(): users = User.query.all() deletedUsers = 0 deletedPosts = 0 for u in users: db.session.delete(u) deletedUsers = deletedUsers + 1 posts = Post.query.all() for p in posts: db.session.delete(p) deletedPosts = deletedPosts + 1...
print "hallo" print "test"
from fake_useragent import UserAgent import json from . import module_helpers class DnsServers(module_helpers.RequestsHelpers): """ A set of functions to find resolvers to use of high quality. """ def __init__(self): """ Init class structure. """ module_helpers.R...
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/recipes/') def recipe_list(): return 'list goes here' #@app.route('/recipes/<recipe>') @app.route('/recipes/recipe') def display_recipe(): #return 'Recipe %d', recipe return re...
from django.db import models class User(models.Model): ID = models.AutoField(primary_key = True) Name = models.CharField(max_length = 30) OpenID = models.CharField(max_length = 100, unique = True) Session = models.CharField(max_length = 100) class Education(models.Model): EDUCATION_TYPE = ( ...
import threading from sklearn.externals import joblib from tag_from_text_model import LogisticRegressionIntentClassifier from logger import Logger class TextClassifier: def __init__(self, model_filename='model.joblib'): self.key_logger = Logger(1920, 1080) self.classifier = LogisticRegressionInte...
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-07-27 20:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('siwedeeapp', '0001_initial'), ] operations = [ ...
import numpy as np import pickle import copy import matplotlib.pyplot as plt import statistics from os import listdir from PIL import Image config = {} config['layer_specs'] = [784,50,10] # The length of list denotes number of hidden layers; each element denotes number of neurons in that layer; first element is the ...
# 使用 `ipython --matplotlib=qt` 启动 IPython console,避免输入 `plt.show()` # 为了每次只显示一张图,在下面标记出来的3行处加断点,例如: # >>> run -d -b23 visual_cnn.py # ipdb> b 32 # ipdb> b 44 from keras.models import load_model from keras.preprocessing import image from keras import models import numpy as np import matplotlib.pyplot as plt model = lo...
import os import signal import random import time import sys import cgi import io addTo = False listedOptions = False addResp = False improvingAI = False inCrisis = False whatMatter = False sendLocation = False storeStr = "" storeFilepath = "" userName = "" namePrime = False knowName = False def printSys(inputTxt): ...
import socketserver import http.server import logging import cgi from selenium import webdriver PORT = 80 driver = webdriver.Chrome("chromedriver.exe") class ServerHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): logging.error(self.headers) http.server.SimpleHTTPRequest...
from django.shortcuts import render, get_object_or_404, redirect from .models import blog from django.utils import timezone # Create your views here. def home(request): blogs = blog.objects.filter(updated_at__lte=timezone.datetime.now()).order_by("-updated_at") return render(request, 'home.html', {'blogs':blog...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # py_squirrel.py # # Copyright 2012 Wolf Halton <wolf@sourcefreedom.com> # # 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; eithe...
# inicializa o vetor de notas com 0 notas = [0] * 5 soma = 0 #preeche vetor de notas sem usar append for i in range(5): notas[i] = eval(input('Digite a nota do aluno '+ str(i) +': ')) soma = soma + notas[i] media = soma / 5 print ('A media da turma é: ', media)
import requests if __name__=='__main__': for i in range(1,2048): try: file=open("htmls\\"+str(i)+".txt",'r') except: print("###"+str(i))
from Classes import Student student_list = [ Student.Student("Melissa", "Atmaca"), Student.Student("Jacob J", "Aylmer"), Student.Student("Kayla Joy", "Batzer"), Student.Student("Philip Joseph, III", "Brendel"), Student.Student("Samuel Victor", "Bunis"), Student.Student("Jacob Richard", "Buurma...
#Leo Li #11/16/2018 #Description: This is the sobel filter. It traces out the edge of an image and blacks out everything else #source:http://homepages.inf.ed.ac.uk/rbf/HIPR2/sobel.htm from PIL import Image import sys import math def main(): global img,j,w img = Image.open(sys.argv[1])#using the commandline argume...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class Libxml2Toolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0176...
{ 'name': 'Cooperation With Top Managers ', 'version': '1.0', 'category': 'E-Commerce', 'description': """ This is a general module for Cooperation With Top Managers for Project Development """, 'author': 'Ismaylov Rufat', 'depends': ['base','project'], 'data': ['proposal_development.xml','wizard/project_task_reevaluat...
from rest_framework import serializers from .models import Category, Product class CategorySerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) class Meta: model = Category fields = '__all__' def get_url(self, obj): return obj.get_absol...
import pygame.mixer sounds=pygame.mixer sounds.init() def wait_finish(channel): while channel.get_busy():#get_busy()检查声音是否在被播放 pass#不做任何事情 correct_s=sounds.Sound("correct.wav") wrong_s=sounds.Sound("wrong.wav") prompt="1 is correct, 2 is wrong, 3 is over: " asked_number=0 correct_number=0 ...
from django.contrib import admin from .models import Room, Player # Register your models here. admin.site.register(Room) admin.site.register(Player)
#!/usr/bin/env python3 # create dictionary of farms farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] nonveg =...
from .add_accents import *
import os, sys, random, time, string import input as key_input import characters import info import entities import monsters import console import json # Writing JSON data def save_settings(data): data = ['a', 't', 'd', ',', ' ', 'up', 'down', 'left', 'right', 'q', 'i'] with open('settings.json', 'w') as f: js...
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql import func from forms import BookingForm, RequestForm, MsgForm import json app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tutors2.db' app.c...
cities = ["Karachi","Lahore","Islamabad","Quetta","Pehawar","Hyderabad","Sialkot","Gawadar","Mardan"] del cities[8] # print(cities[8]) index out of range error because now the list size is of 7 index cities.remove("Gawadar") #print(cities[7]) index out of range error because now the list size is of 6 index
from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db.models import Q from django.template.defaultfilters import pluralize from humanresources.utils import send_mail class Command(BaseCommand): help = "Inspect all Orders in ...
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # fmt: off # isort: skip_file # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" imp...
#!/usr/bin/python def kadanes(A): B = [A[0]] msub = B[0] for i in range(1, len(A)): B.append(max(A[i], B[i - 1] + A[i])) msub = max(msub, B[i]) return msub # TEST CASES print(kadanes([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6 print(kadanes([2, 3, -1, -20, 5, 10])) # 15
from bs4 import BeautifulSoup import requests url = input("Enter the website name: ") response = requests.get('http://' + url) data = response.content soup = BeautifulSoup(data, 'html5lib') for link in soup.find_all('a'): try: if not link.get("href").startswith("http"): link = 'https://' + u...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 10 21:02:21 2017 @author: xueyan """ import re key = r"javapythonhtmlvhdl"#这是源文本 p1 = r"python"#这是我们写的正则表达式 pattern1 = re.compile(p1)#同样是编译 matcher1 = re.search(pattern1,key)#同样是查询 print(matcher1.group(0)) p = re.compile('[a-z]+') p.match("") p...
from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from .models import Project # Create your views here. def home(request): return render_to_response('web/company_zh/home.html',{},context_instance=RequestContext(request)) def contact(requ...
""" Programa feito em base a um desafio proposto por https://github.com/13Ax0 Todos os créditos vão á ele 13Ax0. """ from time import sleep lista = ['2 Turtle Doves', '3 French hens', '4 calling birds', '5 golden rings', '6 geese a-laying', \ '7 swans a-swimming', '8 maids a-milking', '9 ladies danci...
#!/usr/bin/env python from ase import io import numpy as np from scipy import integrate import pymc as pm from scipy.signal import hilbert import pickle, time, math from chemisorption import namodel from ase.db import connect # load in data db = connect('bayeschem.db') List = [row.label for row in db.select()] Vak2 ...