text
stringlengths
38
1.54M
#!/usr/bin/env python #coding=utf-8 def BinarySearch(a, target): low = 0 high = len(a) - 1 # 在其它语言中,如果low + high的和大于Integer的最大值,比如2 ** 31 - 1, # 计算便会发生溢出,使它成为一个负数,然后被2除时结果仍为负数。 # 方法之一是用减法而不是加法——来实现:mid = low + ((high - low) / 2)。 while low <= high: mid = low + ((high - low) / 2) ...
# encoding: utf-8 import os import re from contextlib import closing import datetime import urllib import json from flask import Flask from flask import Markup from flask import render_template from flask import request from flask import session from flask import redirect from flask import url_for from flask import es...
# This example describe how to integrate ODEs with scipy.integrate module, and how # to use the matplotlib module to plot trajectories, direction fields and other # useful information. # # == Presentation of the Lokta-Volterra Model == # # We will have a look at the Lokta-Volterra model, also known as the # predator-pr...
import sys sys.path.append('Config/') import config from abc import ABCMeta, abstractmethod import threading, time, logging, datetime, json import gspread, cls_GSS from oauth2client.service_account import ServiceAccountCredentials logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(messag...
import csv; numbers = """Zaika:+919116666156 Yo Zing:+917983653992 ChaapHut:+919950699999 Tea Tradition: +917340000547 Tandoor:+911416530007 Saras:+917357549601 Login:+919116666156 Let's Go Live:+917742603072 Kebab Nation:+919983087222 HealthBar:+917073991323 Dev Sweets and Snacks:+919001641663 Delight:+917240422018 Cr...
from timer import slee from multiprocessing import Pool def start_function_for_processing(n): sleep(0.5) result_sent_back_to_parent = n * n return result_sent_back_to_parent if __name__ == '__main__': with Pool(process=5) as p: results = p.map(start_function_for_processing, range(200), chunksize=10) print resu...
import torch import torch.nn as nn import matplotlib matplotlib.use('agg') ############################################################################ # Helper Utilities ############################################################################ def weights_init_normal(m): # Set initial state of weights ...
"""analyze.py: """ __author__ = "Dilawar Singh" __copyright__ = "Copyright 2017-, Dilawar Singh" __version__ = "1.0.0" __maintainer__ = "Dilawar Singh" __email__ = "dilawars@ncbs.res.in" __status__ = "Development" import sys import os import matplotlib.pyplot...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Oriëntatie op AI Opgave: recursie (c) 2019 Hogeschool Utrecht Tijmen Muller (tijmen.muller@hu.nl) Let op! Je mag voor deze opgave geen extra modules importeren met 'import'. """ def faculteit(n): """ Bereken n! op recursieve wijze. """ # Base case if ...
from django.conf.urls import patterns, include, url from django.contrib import admin import ma.views.user import ma.views.driver admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'jiaoke.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', includ...
# Fibonacci數列f1,f2,….,fn ,f1 =1; f2 =1;當n>2時,fn = fn-1+fn-2 ;設計一程式輸入 # 一整數n(1<n<100),找出fn 。(請上傳 Fibonacci.py) n = int(input("輸入n:")) f=[1,1] for i in range(2,n): f.append(f[i-1] + f[i-2]) print(f[n-1])
s = [int(_) for _ in list(input())] for i in range(len(s)): if 9-s[i] < s[i]: if (i == 0 and 9-s[i] == 0): continue s[i] = 9-s[i] print(int(''.join([str(_) for _ in s])))
import json import math import Functions with open('urls.json', 'r') as file_handle: links = json.load(file_handle) with open('inverted_index.json', 'r') as file_handle: inverted_index = json.load(file_handle) doc_count = len(links) lemmas = {} for filename in links: print(filename) f = open(filena...
from flask import Flask, render_template, request, redirect from flask_table import Table, Col from PyDictionary import PyDictionary import json import time import sys import sqlite3 as sql import random from mw_get_def import ProcessWords app = Flask(__name__) @app.route('/') def home(): return render_template(...
def read_sudoku(filename: str) -> List[List[str]]: """ Прочитать Судоку из указанного файла """ with open(filename) as f: content = f.read() digits = [c for c in content if c in '123456789.'] grid = group(digits, 9) return grid def display(grid: List[List[str]]) -> None: """Вывод Судоку...
# # @lc app=leetcode.cn id=26 lang=python3 # # [26] 删除排序数组中的重复项 # # @lc code=start class Solution: # * 一次循环,统计重复的数字个数n,然后将下一个数字往前移动n个位置。 # 36ms 98% 86% 14.3MB def removeDuplicates1(self, nums: List[int]) -> int: duplicate_count = 0 for i in range(1,len(nums)): if(nums[i-1] == ...
import pyodbc import connections as conn cursor_new = conn.conn_new.cursor() cursor_old = conn.conn_old.cursor() oldMakeUp = cursor_old.execute('SELECT M.Makeup_ID, M.Makeup_Category_ID, M.Makeup_Brand_ID, M.Makeup_Attribute_ID, M.Makeup_Name, M.Makeup_Volume, M.ASIN, MA.Makeup_Attribute_Name, MB.Makeup_Brand_Name, ...
import os import onedrivesdk from django.conf import settings BASE_DIR = settings.BASE_DIR # Comment this line out when creating authentication without app running. ''' Configurations for the Microsoft One Drive API. API tokens are provided for convenient recreation of the web server. Please don't abuse the limits o...
from yourapplication import app @app.route('/') def index(): return 'Hello World!' @app.route("/blog") def blog(): return "This is the blog page"
import os.path import numpy as np from invoke import run import argparse import time """ This python script runs the pdal pipeline merge-pipe-v0.json for a list of ground and object las files. The top level directory must be specified by hand. merge-pipe-v0.json should be located in the directory from whi...
import websocket import sys import datetime def basic_test(): ws = websocket.create_connection(sys.argv[2]) print "* [Starting basic test]" print "* [Load string ~ 1kB]" hit_factor = 300 load_string = "LOAD_TEST"*100 then = datetime.datetime.now() for i in range(1,hit_factor): ...
import sys from skimage import io, transform, feature, img_as_ubyte import numpy as np def preprocess(filename): image = img_as_ubyte(io.imread(filename, as_grey = True)) if image.shape[0] != 768: print(image.shape) print("WARN: Resizing image to old iPad Size. TODO> Move forward to retina ima...
import pandas as pd import numpy as np df_sup = pd.read_csv('predictions_402.csv') df_sup = df_sup.iloc[:, 1:] df = pd.read_csv('arrange.csv') df = df.iloc[:, 1:] # for i in range(len(df)): # for j in range(len(df.iloc[i])): # df.iloc[i, j] = True if df.iloc[i, j] == 1 else False df_sup = df_sup.mask(np.arr...
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse, Http404 from account.decorator import unauthenticated_user, allowed_users, admin_only from . models imp...
#!/usr/bin/env python # vim:ts=4:sts=4:sw=4:et:wrap:ai:fileencoding=utf-8: __author__ = "Tiago Alves Macambira < first . last @ chaordicsystems.com>" __copyright__ = "Copyright (C) 2013 Chaordic Systems S/A" __license__ = "Public Domain" from mrjob.job import MRJob class TwitterNumFollowersApp(MRJob): def st...
from django import forms from Books.models import Book from django.forms import ModelForm #class BookCreateForm(ModelForm): # book_name = forms.CharField(max_length=120) # author = forms.CharField(max_length=120) # price = forms.IntegerField() # pages = forms.IntegerField() class BookCreateForm(ModelForm):...
''' Created on 12-mei-2012 @author: Erik Vandeputte ''' import pylast from pyechonest import song #API_KEY and API_SECRET API_KEY = "23d4d080ab66300840b2f6cc49151fbb" API_SECRET = "02b5d7e670df35c99b0c09f50e365239" def get_tempo(artist, title): "gets the tempo for a song" results = song.search(artist=artist,...
sum1=0 num1=int(input("enter the starting number ")) num2=int(input("enter the ending number ")) while num1<num2: sum1=sum1+num1; print(sum1) num1=num1+1 print("sum is",sum1);
"""Copyright 2014 Uli Fahrer 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 applicable law or agreed to in writing, software dist...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 2 18:25:33 2021 @author: jujharbedi """ # Importing flask framework to deploy project from flask import Flask, render_template, request, redirect, url_for, session, Response import requests from time import sleep from concurrent.futures import Thre...
# Generated by Django 2.2.5 on 2019-11-24 05:03 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('RSSG', '0010_auto_20191123_1132'), ] operations = [ migrations.AddField( model_name='operations', ...
#store a set of dictionaries in a list or a list of items as a value in a dictionary #can nest a set of dictionaries in a list, a list of items in a dictionary, or # a dictionary in a dictionary alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 1...
# Copyright 2017 The Cobalt 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 applicable ...
from collections import Counter import math from sympy import Symbol, factor, expand, Rational import numpy as np # Generating All Partitions: A Comparison Of Two Encodings # https://arxiv.org/abs/0909.2331 def accel_asc(n): a = [0 for unused_variable in range(n + 1)] k = 1 y = n - 1 while k != 0: ...
from rebase.common.database import DB, PermissionMixin class TalentPool(DB.Model, PermissionMixin): __pluralname__ = 'talent_pools' id = DB.Column(DB.Integer, primary_key=True) @classmethod def query_by_user(cls, user): return cls.query def allowed_to_be_created_by(self, user): ...
import os import unittest import numpy as np # by default, we don't run any actual s3 tests, # because this will not work in CI due to missing credentials. # set the environment variable "Z5PY_TEST_S3" to 1 in order to run tests TEST_S3 = bool(os.environ.get("Z5PY_S3_RUN_TEST", False)) BUCKET_NAME = os.environ.get("Z5...
import sys import requests import PyPDF2 from glob import glob import os import shutil crossref = 'http://api.crossref.org/' if __name__ == '__main__': dr = os.getcwd() ## Get directory nRenamedArticles = 0 files = glob(os.path.join(dr, "*.pdf")) nFiles = len(files) ## Lenght of list equal to total n...
import bs4 from requests import get from urllib.request import urlopen as ureq from urllib.request import urlretrieve as uret from bs4 import BeautifulSoup as soup from openpyxl import * from tkinter import * import time import re from selenium import webdriver import os import datetime #script for ...
# Generated by Django 2.0.1 on 2018-02-04 21:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('test_app', '0037_thirdobject_with_pk'), ] operations = [ migrations.RenameModel( old_name='ThirdObject', new_name='OtherObje...
from django.db import models # Create your models here. class BookInfoManager(models.Manager): '''图书模型管理器类''' # 1.改变原有查询的结果集 def all(self): # 1.调用父类的all方法,获取所有数据 books = super().all() # QuerySet # 2.对books中的数据进行过滤 books = books.filter(isDelete=False) # 返回books ...
#!/usr/bin/python3 #-*- coding: utf-8 -*- import os import time import RPi.GPIO as GPIO from config.variables import luz_hora_encendido, luz_hora_apagado #configurando GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) #GPIO.input(21) def comienza_dia(): GPIO.output(21, True) print("...
from django import forms from apps.post.models import PostModel, PostCommentModel from apps.user.models import VisitorModel class PostForm(forms.ModelForm): """ Post admin form """ class Meta: model = PostModel exclude = ('author', "created_at", "updated_at") class PostCommentForm(forms.Mode...
# Generated by Django 2.0 on 2020-11-23 11:22 import ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20201121_2244'), ] operations = [ ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # __author__ = '__JonPan__' from .app import Flask from flask import current_app from app.api.v1 import init_blueprint_v1 from app.libs.error import APIException, HTTPException from app.libs.error_handle import ServerError def register_blueprint(app): app....
from .trader import (update_trade_account, quote_detail, order, withdraw, transfer, trade_account_all, list_offers, apply_status, apply_offer, withdraw_apply) __all__ = ['update_trade_account', 'quote_detail', 'order', 'withdraw', 'transfer', 'trade_account_all', ...
# this is the base application file. # We import all the needed libraries and prep the server to be exported into run.py from flask import Flask, g from flask_cors import CORS from utils.config import config from db import connect_db server = Flask(__name__) server.secret_key = config['flask_login_secret'] cors = COR...
from model.sale_class import Sale def test_delete_sale(app): app.session.login_to_feefo('testmailnd@gmail.com', 'Dima!qa2ws1') app.sale.delete_sale(Sale(name='delete test name', email='testemail@gmail.com',order_ref='or_001', mobile='11111111111')) app.session.log_out()
from django.urls import path from .views import image_view, success app_name='task' urlpatterns = [ #path('', views.doc_list, name='doc_list'), path('', image_view, name = 'image_upload'), path('success', success, name = 'success'), ]
N, K = map(int, input().split()) A = list(map(int, input().split())) B = [1 for a in A] K = min(K, 500) for k in range(K): for i in range(N): for j in range(1, A[i]+1): if i - j >= 0: B[i-j] += 1 if i + j < N: B[i+j] += 1 A = [b for b in B] ...
import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker, get_backend, rc grey, gold, lightblue, green = '#808080', '#cab18c', '#0096d6', '#008367' pink, yellow, orange, purple = '#ef7b9d', '#fbd349', '#ffa500', '#a35cff' darkblue, brown, red = '#004065', '#731d1d', '#E31937' g = np.load("sam...
# -*- coding: utf8 -*- import telegram import requests import random from transitions import State from transitions.extensions import GraphMachine as mach from bs4 import BeautifulSoup bot = telegram.Bot(token='496063592:AAH9ux0XtCDTDQm2lANJE7Sg9F3SbQaiPFg') actorURL = 'http://www.imdb.com/search/name?gender=male,fem...
def remove_duplicates(l): l1 = [] [l1.append(i) for i in l if i not in l1] return l1 if __name__ == "__main__": l = [1,2,3,4,1,2,5,6,7,4,6,7,8,8,9,5,4,3,2,6,7,33,44,22,3,33,44] result = remove_duplicates(l) print result
import spruceData import Editor.UI.NounUI as NounUI from Editor.AbstractModel import abstractModel from PyQt4 import QtCore class NounModel(NounUI.Ui_Form,abstractModel): def setupUi(self): NounUI.Ui_Form.setupUi(self, self) abstractModel.setupUi(self) QtCore.QObject.connect(self.tSingular...
import pandas as pd import mlflow import mlflow.keras import flask import tensorflow as tf import keras as k def auc(y_true, y_pred): auc = tf.metrics.auc(y_true, y_pred)[1] k.backend.get_session().run(tf.local_variables_initializer()) return auc global graph graph = tf.get_default_graph() model_path = '...
from __future__ import division from DTLZ import * from Problem import * from hypervolume import * import random import math import sys def random_value(low, high, decimals=2): """ Generate a random number between low and high. decimals incidicate number of decimal places """ return round(random.un...
from flask import Flask __version__ = '1.0' app = Flask('satellite') app.config.from_object('config') app.debug = True from satellite.controllers import *
from __future__ import annotations from functools import partial from multiprocessing import Queue from pathlib import Path from typing import Iterable, Optional, Tuple from drsloader import DrsLoader from trigger.baseinterface.drstrigger import IDrsTrigger from .apibridge import ApiBridge from .localdb import DataCa...
#!/usr/bin/env python """ model tests """ # import model specific functions and variables from model import model_train from model import model_load from model import model_predict from pathlib import Path import os import unittest import warnings warnings.filterwarnings("ignore") # data_dir = os.path.join("..", "d...
#!/usr/bin/env python # Conversion Fahrenheit to Kelvin # Formula: K = (F - 32)/ 1.8 + 273.15 def fahrenheit_to_kelvin(fahrenheit): celsius = 5 / 9 * (fahrenheit - 32) return celsius + 273.15 print fahrenheit_to_kelvin(1)
#TRENTON MORGAN #CS 2200 #HW 1 #09/05/19 #This program performs the addition and subtraction of values represented with #Roman numerals. It takes in the specified number of inputs (between 2 and 10 #inclusive)in the form of valid Roman numerals, then directly calculates the #result and outputs it in the correct form. ...
from django.urls import path, include from rest_framework import routers from rest_framework_swagger.views import get_swagger_view from .viewsets import TodoListViewSet, ListItemViewSet app_name = "api" schema_view = get_swagger_view(title="Todovoodoo API") router = routers.DefaultRouter(trailing_slash=True) router...
TempStr = input() baseStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" for i in TempStr: if i in baseStr: result = result + i print(result)
from django.urls import path from appLivraria.views import index from . import views urlpatterns = ( path('index/', index.as_view(), name='index'), path('empresa/', views.EmpresaListView.as_view(), name='app_name_empresa_list'), path('empresa/formulario', views.questionario, name='questionario'), path...
''' Script to train the neural network for road labeling. Author: John ADAS Doe Email: john.adas.doe@gmail.com License: Apache-2.0 ''' import numpy as np from PIL import Image from data_loader import CityscapeDataset from network import Network from common import * import torch import torch.nn as nn import torch.op...
#!/usr/bin/python import xmlrpclib import sys from datetime import datetime try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from ConfigParser import SafeConfigParser as ConfigParser class NumbexDaemonController(object): def __init__(self, address): self.url ...
import unittest from model import prediction_with_model import pandas as pd import numpy as np class PredictionWithModel(unittest.TestCase): def test_prediction(self): d = pd.read_csv(r"C:\Users\Toan\Documents\GitHub\colossi\static\temp\cc7deed8140745d89f2f42f716f6fd1b\out_imac_atlas_expression_v7.1.tsv", ...
def myfunc(): mylst=[101,'siva',38000] return mylst eid,ename,sal=myfunc() print(eid,ename,sal) #print(ename) #print(sal)
import os import sys import csv import json import time import boto3 import numpy as np from keras.models import Sequential,load_model from keras.layers import Dense,Dropout,BatchNormalization from keras.callbacks import EarlyStopping def get_bucket(): s3 = boto3.resource("s3") myBucket=s3.Bucket('workspace.scitodat...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class PathItem(scrapy.Item): title = scrapy.Field() total_days = scrapy.Field() views = scrapy.Field() startTime = scrapy.Field() end...
# Copyright (c) 2020-2022, Manfred Moitzi # License: MIT License from __future__ import annotations from typing import ( Iterable, Iterator, cast, BinaryIO, Optional, Union, Any, ) from io import StringIO from pathlib import Path from ezdxf.lldxf.const import DXFStructureError from ezdxf.lld...
import mock_catalyst from mock_catalyst import EndOfApplication from vocollect_lut_odr_test.mock_server import MockServer, BOTH_SERVERS from main import main #create a simulated host server ms = MockServer(True,15004, 15005) ms.start_server(BOTH_SERVERS) #ms.set_pass_through_host('127.0.0.1', 15004, 15005) ms.load_ser...
# -*- coding: utf-8 -*- """ Created on Mon May 27 14:18:44 2019 @author: 张鹏举 """ import re import glob if __name__ == '__main__': path = '' else: path = 'trait\\' def trait_info(): file_list = glob.glob(path + '*.py') #print(file_list) file_list.remove(path + '__in...
import numpy as np from numpy.random.mtrand import RandomState import matplotlib.pyplot as plt import math from node import Sum, Product, NDProduct, Leaf, Bernoulli, Categorical, Gaussian from utils import get_nodes, get_topological_order_layers, sample, mpe, gradient_backward, sgd, add_ids_to_spn from learning impor...
from classCreation import main print("") print("") print("Welcome to our contact tracing program!") print("") print("What would you like to do? ") print("") print("Create Class (1) | Exit (2)") action = int(input()) print("") if action == 1: main() if action == 2: exit() print("") print("") print("What woul...
# #Copyright (c) 2018 Jie Zheng # from e3net.db.db_base import init_database from e3net.common.e3config import get_config from e3net.db.db_base import create_database_entries from e3net.common.e3log import get_e3loger from e3net.e3neta.db import invt_e3neta_database DB_NAME = 'e3net_agent' e3loger = get_e3loger('e3net...
import tqdm from multiprocessing import Pool import logging from dsrt.config.defaults import DataConfig class Filter: def __init__(self, properties, parallel=True, config=DataConfig()): self.properties = properties self.config = config self.parallel = parallel self.init_logger() ...
# code to calculate Rouge precision and recall for various texts, by taking the two text files # that have the original summaries and the new ones. # Inputs: # 1) File containing original summaries # 2) File containing new summaries # 3) n-gram model to use (1, 2, 3 ...) (Should be less than the total number of word...
Import('env') env = env.Clone() env.AppendUnique(CC=['-fsampler-scheme=bounds'], CCFLAGS=['-fassign-across-pointer']) enum = env.CBIProgram('enum.c') Alias('test:bounds', env.Expect([ env.CBIResolvedSamples(env.CBIReports(enum), objects=enum), ])) Alias('test', 'test:bounds') File(Glob('*.expected'))
# -*- coding: utf-8 -*- import hashlib import hmac import requests VERSION_KHIPU_SERVICE = '1.3' class KhipuService(object): """ A client for the Khipu API. """ # Url del servicio api_url = 'https://khipu.com/api/%s/' % VERSION_KHIPU_SERVICE # diccionario de datos que se enviarán al servicio ...
from django.db import models # Create your models here. class Attendance(models.Model): timestamp = models.DateTimeField(db_index=True,null=True,default=None) name = models.CharField(max_length=250) student_id = models.CharField(max_length=64) university_id = models.CharField(max_length=64) def __str__(self): ...
import numpy as np import torch def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if isinstance(pic, n...
from math import isnan import pytest import numpy as np from confseq.betting import * from confseq.misc import superMG_crossing_fraction, expand_grid from scipy.stats import binomtest @pytest.mark.random @pytest.mark.parametrize("theta", [0, 0.5, 1]) def test_betting_mart_crossing_probabilities(theta): # Note tha...
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
# -*- coding: utf-8 -*- import simple_draw as sd # Часть 1. # Написать функции рисования равносторонних геометрических фигур: # - треугольника # - квадрата # - пятиугольника # - шестиугольника # Все функции должны принимать 3 параметра: # - точка начала рисования # - угол наклона # - длина стороны # # Использование к...
from app import db class Cities(db.Model): id = db.Column(db.Integer, primary_key=True) city = db.Column(db.String(32), unique=True, nullable=False) regions = db.relationship("Regions", backref="city", cascade="delete") class Regions(db.Model): id = db.Column(db.Integer, primary_key=True) city_i...
#!/usr/bin/python import argparse import configparser import time from distutils.util import strtobool import os.path import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions...
from flask import Flask app = Flask(__name__) # app.config['DEBUG'] = True from flask import render_template # from app import app import os import json import re from flask import request from whoosh.lang.morph_en import variations from flask import jsonify @app.route('/') def my_form(): return render_template...
# -*- coding: utf-8 -*- """ Cleaner modules, it cleans raw text data """ from os import listdir from os.path import isfile, join import os, io class Cleaner: def findDoubleSign(self, line, simbleStart, simbleEnd): i = 0 start = -1 end = -1 char = simbleStart ...
""" Name: delete_files_from_folder.py Purpose: Delete all the files from the directory and sub-directories Usage: python delete_files_from_folder.py <source> Author: Rohan Nagalkar Created: 23/06/2016 Version: 0.1 Rohan Naga...
# -*- coding: utf-8 -*- from datetime import datetime, date from copy import deepcopy from django.http import HttpResponse from django.views.generic import ListView from django.views.generic.detail import DetailView from django.shortcuts import render, get_list_or_404,\ get_object_or_404, render_to_response, redir...
n=int(input()) m=[int(input()) for _ in range(n)] m.sort(reverse=True) for i in range(n): m[i]*=(i+1) print (max(m))
from Database import enc_table # p = number.getPrime(512) # q = number.getPrime(512) # p = 59 # q = 53 # e = 65537 # usually a large prime number, or calculated using gcd(e,phi(pq))=1 # n=p*q def retrieve_from_db(): """ Retrieves the public key and the prime numbers needed for the encryption :return: a ...
import sqlite3 as sq class PhoneBook: con = sq.connect('phonebook.sqlite3') def __init__(self): try: self.cur = self.con.cursor() self.cur.execute( 'Create table if not exists PHONEBOOK(name text,address text,mobile text unique) ') print(' Table cre...
__author__ = 'Noblesse Oblige' from tqdm import tqdm import numpy as np import nltk from nltk.corpus import cmudict from nltk.corpus import opinion_lexicon from nltk.corpus import wordnet as wn import string import os from nltk.parse import stanford from nltk.util import ngrams from nltk.util import skipgr...
# -*- coding: utf-8 -*- # 性别0男1女 import pymysql from bs4 import BeautifulSoup db = pymysql.connect("172.16.155.12","root","myzszx002","zszx2017",charset = "utf8") cursor = db.cursor() sql = "select id,Sex from expert2017_copy" try: cursor.execute(sql) results = cursor.fetchall() for row in results: if row[1]...
from model.common_dao import sql_execute, _insert_item, _get_item, _update_item_using_id, _delete_item_using_id, _delete_item_using_condition class ScenarioGroupDao: def create_scenario_group(scenario_group_name): condition = {'name': scenario_group_name} scenario_group_id = _insert_item('...
from socket import * import time import sys import helper import threading import random #python3 sender.py 127.0.0.1 6060 test.txt 100 50 0.6 0.1 5 #header src port num(2byte) dest port num(2byte) seq num(4 byte) ack num(4byte) 1bit syn #1 bit ack 1 bit fin #s is the socket for sending and receiving s = socket(AF_I...
''' Task: You are given the year, and you have to write a function to check if the year is leap or not. -------------------------------------------------------- Sample Input: 1990 Sample Output: False ''' def is_leap(year): leap = False # Write your logic here if year%4 == 0: leap = True i...
from typing import Optional, List, Union from dataclasses import dataclass from enum import Enum from elftools.construct.lib import Container from elftools.common.utils import struct_parse class SymbolType(Enum): FUNCTION = 'STT_FUNC' VARIABLE = 'STT_OBJECT' NOTYPE = 'STT_NOTYPE' class VisibilityType(...
class Solution: def alphabetBoardPath(self, target): """ Time Complexity: O(N) Space Complexity: O(N) """ m = {c: [i // 5, i % 5] for i, c in enumerate("abcdefghijklmnopqrstuvwxyz")} x0, y0 = 0, 0 res = [] for c in target: x, y = m[c] ...