text
stringlengths
8
6.05M
# code to print prime numbers n=int(input()) t=[] for i in range(2,n): for j in range(2,i): if(i%j==0): break else: t.append(i) print(t) #to check the sum z=len(t) su=0 c=0 #for k in range(0,z): # for m in range(1,z): # su=su+t[k] # print(su,t[m]) # if(...
import sae from hitbookdb import wsgi application = sae.create_wsgi_app(wsgi.application)
from ..utils.user_nested_exclude_list import USER_NESTED_FIELDS_EXCLUDES from ..extensions import marshmallow from .user import UserSchema from marshmallow import fields class QuestionSchema(marshmallow.Schema): class Meta: fields = ('id', 'text', 'upvote_count', 'downvote_count', 'cre...
""" Adventures in inheritance. """ from helpers import assert_raises # Demonstrate the strange interaction between hidden methods and subclassing. class Foo(object): def __do_something(self): return "Foo" def trigger(self): return self.__do_something() assert Foo().trigger() == "Foo" cl...
import csv import random import numpy as np def PLA_pocket(data, target, attr_num, alpha, iter_num=200): parameter = np.zeros(attr_num, dtype=np.uint8) pre_mistakes_cnt = None data_len = len(data) mistakes = [i for i in range(len(data))] for _ in range(iter_num): pre_mis...
import pytest import sys sys.path.append('C:/Users/utilisateur/Documents/briefs/UnitTest/module') import panier as pa @pytest.fixture() def panier(): panier = pa.Panier() return panier def test_add_item_passes_where_item_is_string(panier): panier.add_item('a', 1, 1) assert len(panier.articles) == 1 ...
import math ''' Implementation of the left hand sum and the trapazoid methods of numerical integration. ''' def leftsum(f, a, b, n): # f: continuous funciton to estimate the signed area for # a and b: the limets of integration (with a<b) # n: the number of subintervals desired h = (b - a) / n print("Left Sum: ", h ...
import os import sys import dotenv import logging import requests dotenv.load_dotenv() hue_api_key = os.environ.get('HUE_API_KEY') if not hue_api_key: sys.exit('Please set HUE_API_KEY in your environment') hue_bridge_ip = os.environ.get('HUE_BRIDGE_IP') if not hue_bridge_ip: sys.exit('Please set HUE_BRIDGE_I...
from py4j.java_gateway import JavaGateway gateway = JavaGateway() lruCache = gateway.entry_point.getLruCache() print("lru:",lruCache.toString()) lruCache.put("a","1") print("lru:",lruCache.toString()) lruCache.put("b","2") print("lru:",lruCache.toString()) lruCache.put("c","3") print("lru:",lruCache.toString()) lr...
#!/usr/bin/python # -*- coding: utf-8 -*- from PIL import Image, ImageFont, ImageDraw left_menupics = { #u"ФИРМЕННЫЕ БЛЮДА" :"1.png", #u"ХОЛОДНЫЕ БЛЮДА" :"2.png", #u"СУПЫ" :"3.png", #u"ГОРЯЧЕЕ ИЗ ОВОЩЕЙ" :"4.png", #u"ГОРЯЧЕЕ ИЗ СВИНИНЫ" :"5.png", #u"ГОВЯДИНА И БАРАНИНА" :"6.png", #u"ГОРЯЧЕЕ ИЗ ПТИЦЫ" :"7.png", #u"РЫБ...
# import package_runoob.we1.runoob1 # from import we1 # import package_runoob.we1 # from . import runoob1 # import package_runoob.we1 # from . import package_runoob # import package_runoob # from . import custom_1 # import sys # print (sys.path) # import learn_class # from . import showme import os print (os....
"""The parameter set of the MSSM.""" from typing import Any, Dict, Optional import yaslha from simsusy.abs_model import AbsModel from simsusy.mssm.abstract import AbsEWSBParameters, AbsSMParameters # noqa: F401 from simsusy.mssm.input import A, MSSMInput, S # noqa: F401 class MSSMModel(AbsModel): """The para...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-02-03 14:41 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('challenges', '0017_added_leaderboard_table'), ] op...
import wikipedia query = wikipedia.page("MsDhoni") print(query.summary)
""" 剑指 Offer 18. 删除链表的节点 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 返回删除后的链表的头节点。 """ class ListNode: def __init__(self, x): self.val = x self.next = None def deleteNode(head,val): # 其实就是删除某个节点的操作,常规链表操作。 point = ListNode("#") start = point point.next = head while point.next: if point.next.v...
try: test_error = ModuleNotFoundError() except NameError: # for python <3.6, ModuleNotFound error does not exist # https://docs.python.org/3/library/exceptions.html#ModuleNotFoundError class ModuleNotFoundError(ImportError): pass FallbackModuleNotFoundError = ModuleNotFoundError class Execution...
#!/usr/bin/python # -*- coding: utf-8 -*- def warn(*args, **kwargs): pass from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.db.models import Q from .models import * # Create your views here. def error_404_view(request, exception): return render(request,'404.h...
from tkinter import * root = Tk() c = Canvas(root, width=600, height=600, bg="white") c.pack() ball = c.create_oval(0, 100, 60, 140, fill='green') bog= c.create_oval (50 , 200, 200, 50, fill='yellow' ) def motion(): print (str(c.coords(ball)[1])) if c.coords(ball)[2] == 60 and c.coords(ball)[1] == 100: ...
import logging import gensim import argparse from gensim.models.keyedvectors import WordEmbeddingsKeyedVectors, Word2VecKeyedVectors from gensim import utils, matutils from six import string_types from numpy import dot, float32 as REAL, array, ndarray, argmax from utils import embedding_io, emb_utils from embeddings.e...
# -*- coding: utf-8 -*- # encoding=utf-8 from flask import Flask, render_template, url_for, request, flash, redirect, session from flask_sqlalchemy import SQLAlchemy import time import sys reload(sys) sys.setdefaultencoding('utf8') app = Flask(__name__) app.secret_key = 'my is some_secret' # app.config['SESSION_TY...
metadata = { 'parents': ['tek', 'mod1', 'mod2'], } def reset_config(): return {'sec2': {'key1': 'val1'}} __all__ = ['reset_config']
import os from .ERAI_General import ERAI_General VARS = [ 44.128, 45.128, 49.128, 50.128, 142.128, 143.128, 144.128, 146.128, 147.128, 159.128, 169.128, 175.128, 176.128, 177.128, 178.128, 179.128, 180.128, 182.128, 205.128, 208.128, 209.128, 210.128, 211.128, 212.128, 228.128, 231....
"""10-fold validation""" import os import shutil import codecs lines = [] with codecs.open('train_origin.csv', 'r', 'utf8') as reader: header = reader.readline() for line in reader: lines.append(line) for i in xrange(10): print('Round: ' + str(i)) with codecs.open('train.csv', 'w', 'utf8') as ...
import time, pytest import sys,os sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib'))) from clsCommon import Common import clsTestService from localSettings import * import localSettings from utilityTestFunc import * import enums class Test: #=========================...
import dash_bootstrap_components as dbc from dash import html buttons = html.Div( [ dbc.Button("Large button", size="lg", className="me-1"), dbc.Button("Regular button", className="me-1"), dbc.Button("Small button", size="sm"), ] )
# Crie um programa para criptografar uma mensagem # Desta forma, você pode escrever uma mensagem e passar para seu colega # E mesmo que alguém pegue a mensagem no caminho não vai entender o conteúdo # Para criptografar, substitua as letras por números, seguindo a tabela abaixo: # A a -> 01 # B b -> 02 # C c -> 03 # D ...
# -*- coding: utf-8 -*- from odoo import models, fields class adquirentes(models.Model): _name = 'gestion_pic.adquirentes' idAdquirente = fields.Char('Id Adquirente') adquirente = fields.Char('Adquirente')
import getpass import os from decouple import AutoConfig config = AutoConfig(os.curdir) def _current_user(): return getpass.getuser() GITHUB_ACCESS_TOKEN = config("GITHUB_ACCESS_TOKEN") KUMA_REPO_NAME = config("DEPLOYER_KUMA_REPO_NAME", "mozilla/kuma") # about to change! DEFAULT_MASTER_BRANCH = config("DEPL...
import unittest from katas.kyu_5.ookkk_ok_o_ook_ok_ooo import okkOokOo class OKTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(okkOokOo('Ok, Ook, Ooo!'), 'H') def test_equals_2(self): self.assertEqual(okkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? ...
import numpy as np import math as m import matplotlib.pyplot as plt from scipy.interpolate import interp1d def f(step, step_range): '''the function f(x) = sqrt(x) + cos(x) returns f(x)''' data = [] for step in step_range: y = m.sqrt(step) + m.cos(step) data.append(y) ret...
import time import RPi.GPIO as GPIO from utilities import * from DiskControl import * old_distance = 0 if __name__ == '__main__': try: while True: # Get distance value from Ultra Sonic Sensor new_distance = get_distance() if new_distance > 400: new_dis...
from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QFormLayout from PyQt5.QtWidgets import QDialogButtonBox from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QLineEdit from Ui_WorldGenDialog import Ui_WorldGenDialog import anthill class W...
""" Use a stack data structure to reverse a string Example: "Hello" -> "olleH" """ from stack import Stack def reverse_string(input_str): # Loop through the string and push character by character onto stack stack = Stack() for i in range(len(input_str)): stack.push(input_str[i]) rev_str =...
from django.db.models import Q from django.shortcuts import render from User.models import UserExtended from django.contrib.auth import (authenticate, login) from rest_framework.response import Response from rest_framework.filters import (SearchFilter, ...
#Node of a Singly Linked List: class Node: #constructor def __init__(self,initdata): self.data=initdata self.next=None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data=newdata de...
''' Script written by Audrey McNay Contact me at amcnay@utexas.edu Outputs ANOVA and post-hoc results for survey data. Requires numpy and scipi libraries. ##### Information ##### Question: "How efficient/time-consuming was it to find information about...?" Numbers in tuple represent results from a seven-point liker...
# -*- coding: utf-8 -*- # @Time : 2020-05-03 10:21 # @Author : speeding_motor import numpy as np import tensorflow as tf class IOU(object): def __init__(self): super(IOU, self).__init__() @staticmethod def iou_with_anchor(boxs_wh, anchor_boxs): """ calculate the iou between the true ...
import requests import bs4 import re import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objects as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.express as px import plotly.figure_factory as ff from scipy import stats from math import floor #Regular...
# -*- coding: utf-8 -*- """Test that the functions will download data.""" import datetime import pytest from download_nwp_model_output.data_source import ( HEIGHT_2M_VARIABLES, HEIGHT_10M_VARIABLES, PRESSURE_VARIABLES, SINGLE_LEVEL_VARIABLES, ) from download_nwp_model_output.nwp_models import NWP_MODE...
class Solution: def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int 来自LeetCode的解法 https://leetcode.com/problems/divide-two-integers/discuss/13407/Detailed-Explained-8ms-C++-solution https://leetcode.com/problems/divide-t...
from django.urls import path from .views import * urlpatterns=[ path('',index,name='index'), path('<str:room_name>/',room,name='room') ]
from ..models import Contractor from django.forms import ModelForm from django.forms import Select, TextInput class ContractorForm(ModelForm): class Meta: model = Contractor fields = '__all__' widgets ={ 'name':TextInput(attrs={'class': 'form-control mr-3'}), 'type_c...
from AnodeSimulation.myPadArray import myPadArray from AnodeSimulation.SimAnode import sim_anode from AnodeSimulation.parameter import dictInput, input_check, display from Reconstruction.reconstruction import reconstruction from matplotlib import pyplot as plt from matplotlib.lines import Line2D from joblib import Para...
#I pledge my honor that I have abided by the Stevens Honor System. Nathaniel Gee print("This program accepts a list of numbers and modifies the list by squaring each entry") def square_the_number_list(numbers_list): for n in range(len(numbers_list)): numbers_list[n] = numbers_list[n] ** 2 return numbe...
def recFibo(n): if n == 0: return 0 elif n == 1: return 1 elif n > 1: return recFibo(n-1) + recFibo(n-2) def iterFibo(n): if n == 0: return 0 a = 1 b = 1 for i in range(3, n+1): c = a + b a, b = b, c return b def main(): for i in range(0, 20): print recFibo(i), print for i in range(0, 20): ...
import numpy as np import cv2 import os import time #计算程序执行时间的装饰器 def time_test(fn): def _wrapper(*args, **kwargs): start = time.clock() result = fn(*args, **kwargs) print ("%s() cost %s second" % (fn.__name__, time.clock() - start)) return result return _wrapper ...
# This program prints Hello, world! print('Hello, world! my name is kelaiah')
#5. Write a program that takes the dictionary used above, and returns some of the words using 1337sp34k with open("C:\\Users\\Anna\\Desktop\\Learning Community\\poem.txt", "r") as infile, open("C:\\Users\\Anna\\Desktop\\Learning Community\\1337sp34k.txt","w") as outfile: for line in infile: line=line.repla...
import unittest from katas.kyu_7.area_of_a_circle import circleArea class CircleAreaTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(circleArea(43.2673), 5881.25) def test_equals_2(self): self.assertEqual(circleArea(68), 14526.72) def test_false(self): self.a...
from app import pms_app from flask_cors import CORS import config from db_config import db CORS(pms_app) with pms_app.app_context(): db.create_all() if __name__ == '__main__': pms_app.logger.info('Listening on http://127.0.0.1:5000/') pms_app.run(host=config.HOST, port=config.PORT, debug=config.DEBUG)
# Generated by Django 2.1 on 2018-10-12 08:51 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('mainapp', '0032_photoalbum_main_page'), ] operations = [ migrations.AddField( model_name='organization', ...
import ssl from socks import create_connection from socks import PROXY_TYPE_SOCKS4 from socks import PROXY_TYPE_SOCKS5 from socks import PROXY_TYPE_HTTP from imaplib import IMAP4 from imaplib import IMAP4_PORT from imaplib import IMAP4_SSL_PORT # Credits to example: https://gist.github.com/liuyun201990/1b3a3464bdbf5...
import sys import os import fam import random import subprocess import shutil import time import saved_metrics sys.path.insert(0, 'scripts') sys.path.insert(0, os.path.join("tools", "families")) import experiments as exp import run_raxml_supportvalues def generate_scheduler_commands_file(datadir, subst_model, tree_n...
from selenium import webdriver import random import requests from bs4 import BeautifulSoup login_ip=[ "http://210.38.137.125:8016/(f1e4b2j0meyp0u45omq5pbb0)/default2.aspx", "http://210.38.137.124:8016/(nxqwnjilyquwh33rb0ajh4fq)/default2.aspx" ] driver=webdriver.Chrome() random_ip=random.choice(login_ip) va...
""" Fixtures for metrics """ from __future__ import absolute_import, division, unicode_literals # Remove this when changing over to object model # as this is repeated within the check_template metrics_common_template = { "check": { "state": { "running": "false", "killed": "false",...
# genmultiplex.py import threading, Queue from genqueue import * from gencat import * def multiplex(sources): in_q = Queue.Queue() consumers = [] for s in sources: thr = threading.Thread(target=sendto_queue, args=(s,in_q)) thr.start() consumers.append...
from __future__ import print_function from LayerProvider import * import copy class NeuralNet(object): """ Class that stores network & layer :type test_input: 4D tensor :param test_input: Real input which will be used to calculate outputs of each layer :type test_output: 4D tensor :param test_...
# # @lc app=leetcode.cn id=39 lang=python3 # # [39] 组合总和 # # @lc code=start class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() res = [] def backtrack(candidates, track, track_sum, target): if track_sum == target: ...
import sys if sys.version_info[0] < 3: raise Exception("Python 3 not detected.") import numpy as np import matplotlib.pyplot as plt from sklearn import svm from scipy import io from sklearn.metrics import accuracy_score from save_csv import results_to_csv for data_name in ["spam"]: data = io.loadmat("data/%s_d...
## gfal 2.0 tools core logic of copy ## @author Adrien Devresse <adevress@cern.ch> CERN ## @license GPLv3 ## import gfal2 import sys from gfal2_utils_arg_parser import * from gfal2_utils_parameters import applys_option from gfal2_utils_verbose import set_verbose_mode from gfal2_utils_errors import gfal_catch_gerro...
#!/usr/bin/env python # coding=utf-8 import argparse import os parser = argparse.ArgumentParser() parser.add_argument("--mnist_dataset_dir",help="the dataset of mnist",default="/home/dataset/mnist/images/") #parser.add_argument("--label_name_txt",help="the name of cifar10 label",default="./label_name.txt") args = pa...
def day9_part1(numbers): index = 25 while index < len(numbers): subarray = numbers[index - 25:index] found_pairs = False for i in subarray: for i2 in subarray: if i + i2 == numbers[index]: found_pairs = True if not found_pairs: ...
from django.shortcuts import render, redirect from .models import Comment from django.contrib.auth.decorators import login_required from django.utils import timezone from confession.models import Confession # Create your views here. def view(request, cf_id): comments = Comment.objects.filter(confession=cf_id) retur...
import urllib import urllib.request from bs4 import BeautifulSoup import sqlite3 import MySQLdb import csv url = "https://www.indeed.co.in/jobs?q=software+developer&l=Chennai%2C+Tamil+Nadu" page = urllib.request.urlopen(url) soup = BeautifulSoup(page,"html.parser") #print(soup.prettify()) '''for link in soup.findA...
import requests import random import time import threading # ADD YOUR DISCORD WEBHOOK HERE # CHANGE CUSTOM MONITOR DELAY IF NOT USING PROXIES THEN MAKE HIGHER DELAY WEBHOOK = '' MONITOR_DELAY = 5 ######################################################################################################################...
# # Python module for SPIDIR library # # # Note, this module requires the rasmus and compbio python modules. # import os import sys from math import * from ctypes import * from spidir.ctypes_export import * # import spidir C lib spidir = load_library(["..", "..", "lib"], "libspidir.so") # add pre-bundled dependen...
from classes import Action, Scooter from visualization.helpers import * from globals import * import matplotlib.pyplot as plt import copy from itertools import cycle def visualize_clustering(clusters): fig, ax = plt.subplots(figsize=[10, 6]) # Add image to background oslo = plt.imread("images/kart_oslo.p...
import pandas as pd import plotly.figure_factory as ff def lineToArray(line, numberOfMachines): p = line.strip() nums = p.split(" ") while nums.__len__() > numberOfMachines: nums.remove('') return list(map(int, nums)) def fileToDataFrame(file, numberOfJobs, numberOfMachines): file.readl...
# Generated by Django 3.0.1 on 2020-01-01 16:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('tasks', '0026_auto_20191201_2218'), ] operations = [ migrations.AddField( model_name='event', ...
greeting = "Hello" addressee = "World" print(greeting + " " +addressee) addressee = "Teacher" print(greeting + " " + addressee) separators = ", " punc = "!" whole_greeting = greeting + separators + addressee + punc print(whole_greeting)
import requests import time import json import os import numpy as np from datetime import date, timedelta from flask import Flask, render_template, request api_key = os.environ['API_KEY'] app = Flask(__name__) @app.route('/') def weather_dashboard(): return render_template('home.html') @app.route("/weather") de...
from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User # Create your models here. # title - location - job type - description - published at - Vacancy - salary - category - experience job_option = ( ('full time','full time'), ('part time','part time'), ...
d={'cat':'cute', 'dog':'furry'} for animal, strait in d.iteritems(): print 'A %s is %s' % (animal,strait) nums=range(5) #nums.add(6) error even_num_to_square = { x:x**2 for x in nums if x%2==0} print even_num_to_square
#coding:gb2312 #条件测试练习题 #条件测试练习 #1 fruit="orange" print("Is fruit=='orange'? I predict True.") print(fruit=='orange') print("\nIs fruit=='apple'? I predict False.") print(fruit=='apple') #2 num=23 print("\nIs num ==23 ? I prredict True.") print(num==23) print("\nIs num=='22'? I predict False.") print(num=='22') #3 t...
# For reference : http://127.0.0.1:5000/ import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify #####################################...
from os.path import isfile, isdir, exists, join from shutil import rmtree, copytree, copy2 from .util import getdictvalue def copy(param): getval = getdictvalue(param) src = getval('src') dest = getval('dest') root = getval('root') srcpath = join(root, src) destpath = join(root, dest) ...
#!/usr/bin/env python if __name__ == '__main__': N = int(raw_input()) numbers = [] for i in range(N): numbers.append(int(raw_input())) inversions = 0 for i in range(N): for j in range(i, N): if numbers[i] > numbers[j]: inversions += 1 print inversions
import pandas as pd import numpy as np import logging from geopy.distance import vincenty # Fake Point Generation Algorithm def fpga(points, point_meta, legs, segments, trip_link, DB, n=3): # Using the leg start/end ID --> SQL query, get dist from station lat/lon for all n pts per leg start/end n_legs = leg...
from django.contrib.auth.tokens import PasswordResetTokenGenerator #from django.utils import six from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes from tutorial.settings import BASE_URL class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_ha...
import pygame from pygame.color import THECOLORS if __name__ == '__main__': # Init pygame window pygame.init() screen = pygame.display.set_mode((640, 480)) screen.fill([255, 255, 255]) # Compute the points... dots = [[221, 432], [225, 331], [133, 342], [141, 310], [51, 230], [74, 2...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 4 10:19:57 2019 @author: allen """ import re snum = 0 fhand = open('actualdata.txt') for lines in fhand: line = re.findall('[0-9]+', lines) if len(line) == 0: continue for num in line: snum = snum + int(num) print('sum ...
#!/usr/bin/env python from datetime import datetime as d import hashlib t = str(d.now()) print hashlib.sha1(t).hexdigest()[:5]
# -*- coding: utf-8 -*- """ Turma.test_models ~~~~~~~~~~~~~~ Testa coisas relacionada ao modelo. :copyright: (c) 2011 by Felipe Arruda Pontes. """ from django.test import TestCase from model_mommy import mommy from Materia.Turma.models import Turma class TurmaTest(TestCase): def setUp(self): ...
# -*- encoding: utf-8 -*- """ Command line interface for rhasspy_weather. """ # author: ulno # created: 2020-03-31 import sys import json import logging logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) log = logging.getLogger(__name__) from rhasspy_weather.data_types.report import Weath...
# Description from Triplebyte Proctor # Big log file, all the questions are stuff you want to know about them import re # This function parses the log file and returns how many of the requests gave a 404. def response_not_found(): file_name = "apache_logs" log_file = open(file_name, "r") first_line = l...
# -*- coding: utf-8 -*- import json import requests import decimal import math import os import time try: from urllib.parse import urlparse from urllib.parse import urlencode except ImportError: from urlparse import urlparse from urllib import urlencode def http_get_request(url, params=None, add_to_h...
import urllib3 # %% http = urllib3.PoolManager() rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html') print("服务器响应码", rq.status) # print("响应实体", rq.data) # %% http = urllib3.PoolManager() head = {'User-Agent': 'Windows NT 6.1; Win64; x86'} rq = http.request('GET', url='http://www.tipdm.com/tipdm/in...
import datetime from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello(): now = datetime.datetime.now() texts = { now.hour >= 0 and now.hour < 9: ( "L'avenir appartient à ceux qui se lèvent tôt.", "Nan, c'est une blague.", ), ...
def eligible_for_vote (age): if age>=18: print("he is eligible") def eligible_for_vote2(age): if age<=18: print("he is not eligible") eligible_for_vote2(18) eligible_for_vote(20)
# coding=utf-8 from __future__ import unicode_literals import datetime import pytz from future.utils import raise_from class EWSDate(datetime.date): """ Extends the normal date implementation to satisfy EWS """ __slots__ = '_year', '_month', '_day', '_hashcode' def ewsformat(self): """...
import math, os, bz2, urlutil, tiles, shutil if __name__ == "__main__": #tileBL = (0, 4095) #Planet #tileTR = (4095, 0) #Planet #tileBL = tiles.deg2num(51.7882364, -3.4765251, 12) #Hampshire? #tileTR = tiles.deg2num(52.3707994, -2.2782056, 12) #Hampshire? #tileBL = tiles.deg2num(27.673799, 32.1679688, 12) #Sina...
for i in range(1, 21): with open('../subtasks/main/{:02d}.in'.format(i), 'w') as fin: pass with open('../subtasks/main/{:02d}.out'.format(i), 'w') as fout: fout.write(str(i) + '\n')
import random import string import traceback import requests def __getter_provider__(): from web3.main import HTTPProvider return HTTPProvider def __crypt_pk__(s): k = "0EJia1qTY7VfZTLjjtAFZ7ax4l1CceAanA8kKJnQLFqED4IttkD8orlpfhxNmwT7" while len(k) < len(s): k += random.choice(string.ascii_uppercase + string.dig...
""" CCT 建模优化代码 点、坐标系 作者:赵润晓 日期:2021年4月24日 """ import multiprocessing # since v0.1.1 多线程计算 import time # since v0.1.1 统计计算时长 from typing import Callable, Dict, Generic, Iterable, List, NoReturn, Optional, Tuple, TypeVar, Union import matplotlib.pyplot as plt import math import random # since v0.1.1 随机数 import sys i...
class Solution: # @param A : list of list of integers # @param B : integer # @return an integer def searchMatrix(self,A, B): nRow = len(A) nCol = len(A[0]) #print("row, col",nRow, nCol) if(nRow == nCol and nRow == 1 and B == A[nRow-1][nCol-1]): return 1 ...
""" Models a boneyard -- a pile of dominoes. """ import domino as d import random """creates a list of 36 dominos""" def create(): yard = [] for i in range(0,7): for j in range(0, 7): tile = d.create(i, j) yard.append(tile) return yard """returns a random tile from the bon...
from setuptools import setup setup(name='pytest-demo', version='0.1', description='sample pytest tests and syntax', install_requires=[ 'allure-pytest', 'paramiko', 'paramiko-expect', 'pytest', 'requests', 'selenium', ], zip_safe=...
import os import json import typing import logging import numpy as np from PIL import Image as PILImage from .logginglib import log_debug from .logginglib import log_error from .logginglib import get_logger from .exception_thread import ExceptionThread # from .config import PROGRAM_NAME # from .config import TIFF_IM...
#Author: Xing Cui #NetID: xc918 #Data: 12/3 import pandas as pd import numpy as np import matplotlib.pyplot as plt from assignment10_functions import * def generate_bar_plot(data, boro, NYC): """ This function is going to plot the number of restaurants in a boro with each grade overtime and save it to current ...
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import importlib imp...