text
stringlengths
38
1.54M
from django.conf import settings as django_settings from django.core import mail from django_mailer import models, constants, queue_email_message from django_mailer.tests.base import MailerTestCase class TestBackend(MailerTestCase): """ Backend tests for the django_mailer app. For Django versions less th...
#!/usr/bin/env python import json, urllib2, os, sys def api_call(url, token=None, data=None): if data: data = json.dumps(data) req = urllib2.Request(url, data) if data: req.add_header('Content-Type', 'application/json; charset=UTF-8') if token: req.add_header('Authorization', 't...
# reset the console %reset -f #Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # Import dataset dataset_train = pd.read_csv('SalaryData_Train.csv') dataset_train.head() dataset_train.columns dataset_train.shape #(30161, 14) dataset_train.info() dataset_train.dtype...
# -*- coding:utf-8 -*- # # File Name: xxxx.py # Function: To xxxxx. # Created by: W. Wang (Kevin), ww288@cantab.net # Created on: 20xx/xx/xx # Revised hist: revised by _____ on ____/__/__ # import os import threading from pcmd.env import Env # conf/zhi_miner.ini class ParaCmdEnv(Env): instance = No...
from django.db import models from django import forms from django.template import Context from django.template.loader import get_template from django.http import Http404 from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db.models import get_model from...
import random import os from subjects import SUBJECTS_BY_NAME import cards_loader subjects_db = {} def load_cards(): global subjects_db for subject_data in SUBJECTS_BY_NAME.values(): if not subject_data.cards_db: continue module_dir = os.path.abspath(os.path.dirname(__file__)) ...
import cv2 face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') smile_detector = cv2.CascadeClassifier('haarcascade_smile.xml') webcam =cv2.VideoCapture(0) while True : successful_frame_read, frame = webcam.read() if not successful_frame_read: break ...
from numpy import random import matplotlib.pyplot as plt import seaborn as sns def normalize(distribution): s = 0 if isinstance(distribution, dict): for elem in distribution.values(): s += elem if s != 0: for k in distribution.keys(): distribution[k] /= s...
import requests import requests_cache from requests_html import HTML import microdata from urllib.parse import urljoin import datetime import logging import pprint requests_cache.install_cache("rtpplay-cc_cache") logging.basicConfig() logging.getLogger().setLevel(logging.INFO) def get_all_program_urls(): all_...
#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') from gi.repository import Gtk, GObject, Gst, Gdk import cairo, math, time import colorsys import os.path import configparser #Default Button size WIDTH = 200 HEIGHT = 200 TESTFILE = os.path.join("test1.mp3") class Jin...
''' Holds the base configuration options for charts. The options are in YAML format and then converted to a Python dictionary. Set Tab to 2 spaces. ''' import yaml # ------------------------------------ For Plotly Chart ----------------------------- plotly_opt = yaml.load( ''' renderTo: chart_container # the name ...
import numpy as np from progressivis.core.utils import (slice_to_arange, indices_len, fix_loc) from . import Table from . import TableSelectedView from ..core.slot import SlotDescriptor from .module import TableModule from ..core.bitmap import bitmap from .mod_impl import ModuleImpl from .binop import ops from collec...
import warnings from torch.optim import ASGD, SGD, Adadelta, Adagrad, Adam, Adamax, AdamW, RMSprop from torch.optim.lr_scheduler import ( CosineAnnealingLR, CosineAnnealingWarmRestarts, CyclicLR, ExponentialLR, LambdaLR, ReduceLROnPlateau, ) from .utils import adjust_optim_params EXTRA_OPTIM_...
#!/usr/bin/python3 # Webbrowser v1.0 # Written by Sina Meysami # from tkinter import * # pip install tk-tools import tkinterweb # pip install tkinterweb import sys class Browser(Tk): def __init__(self): super(Browser,self).__init__() self.title("Tk Browser") try: browser = tkin...
from max.regex import RE_VALID_HASHTAG from max.regex import RE_VALID_TWITTER_USERNAME import re def stripHash(text): """ Returns the valid part of a hashtag input, lowercased """ return re.sub(RE_VALID_HASHTAG, r'\1', text).lower() def stripTwitterUsername(text): """ Returns the val...
import matplotlib.pyplot as plt import matplotlib import math from dataclasses import dataclass import itertools # stolen from matplotlib.ticker.LogFormatterExponent class LogFormatter(matplotlib.ticker.LogFormatter): def _num_to_string(self, x, vmin, vmax): fx = math.log(x) / math.log(self._base) ...
import subprocess import time a = subprocess.check_output(["/opt/vc/bin/tvservice", "-s"], shell=False) print ("Erster Status ist: " + str(a)) time.sleep(5) subprocess.call(["/opt/vc/bin/tvservice", "-p"], shell=False) subprocess.call(["sudo", "/bin/chvt", "6"], shell=False) subprocess.call(["sudo", "/bin/chvt", "7"],...
import asyncio import discord client = discord.Client() # 복사해 둔 토큰을 your_token에 넣어줍니당 token = "ODc2MzkwNTAzNjUyOTQ1OTMw.YRjYQg.S0dXPfBMDrAzXO8hSqXBeO0EEmo" # 봇이 구동되었을 때 동작되는 코드 @client.event async def on_ready(): print("봇연습#6890") #화면에 봇의 아이디, 닉네임이 출력되는 코드 print(client.user.name) print(clien...
def choose_median(start, middle, end): # finish the method for finding the median pivot = [start, middle, end] pivot.sort() return pivot[1] def partition(lst, pivot, start, end): # add necessary modifications # don't forget to print the result of the partition! pivot = lst.index(pivot) ...
''' 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 思路: 定义两个标志位,分别表示E或者e是否出现过,以及小数点.是否出现过。 1. 以e(或E)为分隔,获得两个子字符串;e之前的字符串小数点只能出现一次;e之后的字符串不允许出现小数点; 2. 符号位+或-只可能出现在两个子字符串的首位; 3. e(或E)、小数点.不能出现在末尾 ''' # -*- coding:utf-8 -*- class Solution: ...
import pytest import exercise_part1 import exercise_part2 def test_solve_part1() -> None: expected = 4 with open('test_input.txt') as f: assert exercise_part1.solve(f.read()) == expected @pytest.mark.parametrize( ('input_path', 'expected'), [ ('test_input.txt', 32), ('test_i...
# derived off of example in Corey Schafer youtube channel # create decorator function def decorator_function(inner_function): def wrapper_function(): print("Running decorator1 before '{}'".format(inner_function.__name__)) return inner_function() return wrapper_function def display_function():...
import media import fresh_tomatoes #define instances of Class Movie toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/wa...
from __future__ import print_function def cross_off(flags, prime): """ Cross of (set to False) those indexes that are divisible by `prime` """ i = prime * prime while i < len(flags): flags[i] = False i += prime def get_next_prime(flags, prime): """Find the index of the fi...
#!/usr/bin/env python import platform from os.path import abspath, dirname, join import sys from robot import run, rebot from robot.version import VERSION as rf_version from robotstatuschecker import process_output library_variants = ['Hybrid', 'Dynamic', 'ExtendExisting'] curdir = dirname(abspath(__file__)) outdi...
from django.views import generic from django.contrib.auth import mixins from django.db.models import Min, Max class ProfileTemplateView(mixins.LoginRequiredMixin, generic.TemplateView): template_name = 'accounts/profile.html' class IndexView(generic.TemplateView): template_name = 'index.html' def get_c...
#!/usr/bin/python3 import json import sys import dataclean as clean def main(): reader = open(sys.argv[1]) writer = open(sys.argv[2],"w") data = reader.readlines() for d in data : article = json.loads(d) text= article["text"] lines=text.replace('\n',"#") text=''.join(lines) text=clean.dataclean(text) wr...
################################################################################ # Authors: # # · Alejandro Santorum Varela - alejandro.santorum@estudiante.uam.es # # Date: April 15, 2019 ...
import pygame import numpy as np from doom_py.CONFIGS import TILE_X, TILE_Y, MAX_DEPTH def gradientRect( window, leftbottom_colour, righttop_colour, target_rect, is_vertical=True ): """ Draw a horizontal-gradient filled rectangle covering <target_rect> """ colour_rect = pygame.Surface( ( 2, 2 ) ) ...
from flask import Blueprint, json, jsonify, request, current_app from ..model import Overtime, User, Department from .util import failed, login_required, success, Role, url, current_role, current_user bp = Blueprint('overtimes', __name__, url_prefix='/overtimes') @bp.route('/', methods=['GET']) @url def get_overtim...
""" Jude Ferrier - s1808200 - 31/10/20 Ex 1. Program to find the image of a position r within a cube of length l repeated over space and the closest image to the origin. """ import numpy as np def main(): # Inputs are asked for the coordinates of the vector and the length of the cubes that space is divided into ...
#List Slicing and searching #Mr Pinizzotto #May 6 #create a list of food items foodList = ["pizza", "tater tots", "wings", "sandwich", "falafel", "taco", "fries", "wings"] #regular printing print(foodList) #print first 3 (top 3) items print(foodList[:3]) #print middle items give start, and end (not including) print...
# Generated by Django 2.0.9 on 2018-11-10 17:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shitty', '0002_auto_20181110_1744'), ] operations = [ migrations.AddField( model_name='profile', name=...
from django import forms from django.core import validators class FormName(forms.Form): """docstring for F.""" name = forms.CharField() email = forms.EmailField() verify = forms.EmailField() text = forms.CharField(widget = forms.Textarea) def clean(self): all_clean_data = super().cle...
from .strategy import StrategyInterface from ..orders import MarketOrder class TriangularArbitrage(StrategyInterface): def __init__(self, pairs, exchanges, strategy_parameters): """ pairs = currency pairs on which the strategy is ran exchanges = exchanges on which the strategy is...
#!/usr/bin/python # -*- coding: utf-8 -*- # python 2.7 # @Author: Moming def last_word(cmd): result = cmd[0] for i in range(len(cmd))[1 : ]: if cmd[i] >= result[0]: result = cmd[i] + result else: result = result + cmd[i] return result # main i...
import allure class Test_002: def test002(self): with open(r"C:\Users\James\Desktop\app8\scripts\chy.png", "rb") as f: allure.attach("图片", f.read(), allure.attach_type.PNG)
import agros2d as a2d # PROBLEM problem = a2d.problem(clear=True) problem.coordinate_type = "axisymmetric" problem.mesh_type = "triangle" magnetic = a2d.field("magnetic") magnetic.analysis_type = "steadystate" magnetic.number_of_refinements = 2 magnetic.polynomial_order = 2 magnetic.solver = "linear" geometry = a2d....
from abc import abstractmethod from starfish.core.intensity_table.decoded_intensity_table import DecodedIntensityTable from starfish.core.morphology.binary_mask import BinaryMaskCollection from starfish.core.pipeline.algorithmbase import AlgorithmBase class AssignTargetsAlgorithm(metaclass=AlgorithmBase): """ ...
class Solution: def numTrees(self, n: int) -> int: res = [1, 1] if n <= 1: return res[n] for i in range(2, n + 1): s = i - 1 ct = 0 for j in range(i): ct += res[s - j] * res[j] res.append(ct) return res[n]
from django.core.paginator import Paginator from django.shortcuts import render # Create your views here. from payment.models import PaymentStatus def home(request): page_length = 20 team_list = PaymentStatus.objects.order_by('university', 'team_name') # user_list = Profile.objects.order_by('-level_com...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.CplifeRoomInfoResp import CplifeRoomInfoResp class AlipayEcoCplifeRoominfoUploadResponse(AlipayResponse): def __init__(self): super(AlipayEcoCplifeRoomin...
# -*- coding: UTF-8 import requests import sys # Información api_key = '23e1395c903b1ffa6292125af3c216a1' # Petición def petition(api_key,number): data = requests.get("http://apilayer.net/api/validate?access_key=%s&number=%s&country_code&format=1" % (api_key, number)) for key, value in data.json().items(...
from .breakpoint import Breakpoint from .pesr_test import PESRTest from .sr_test import SRTest, SRTestRunner from .pe_test import PETest, PETestRunner from .pesr_test import PESRTest, PESRTestRunner
from __future__ import print_function import tensorflow as tf import time import numpy as np import math import libmr import urllib.request import os from abc import * import sys mean = {} def printProgress(current, total, prefix='', suffix='', barLength=100): percent = current*100 / float(total) assert percen...
# iSDAsoil Clay Content # https://developers.google.com/earth-engine/datasets/catalog/ISDASOIL_Africa_v1_clay_content # Clay content at soil depths of 0-20 cm and 20-50 cm,\npredicted mean and standard deviation. In areas of dense jungle (generally over central Africa), model accuracy is low and therefore artifacts su...
from copy import copy from functools import partial from jinja2 import Environment, StrictUndefined from syn.base import Base, Attr, init_hook from syn.type import Dict, List, Callable from syn.five import STR from .base import resolve, ordered_macros, get_output, DEFAULT_JINJA_FILTERS, \ DEFAULT_JINJA_FUNCTIONS, ...
from django import forms from django.core import validators class FormularioPacientes(forms.Form): rut = forms.CharField() nombre = forms.CharField() apellido = forms.CharField() email = forms.CharField() tutor = forms.CharField() direccion = forms.CharField() enfermedades = forms.CharFiel...
#!/usr/bin/env python3 # Copyright The OpenTelemetry Authors # # 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 applica...
from tartiflette.types.exceptions.tartiflette import TartifletteError __all__ = ("TartifletteError",)
from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from optparse import make_option from os.path import basename from police.models import Crimepoint, Neighbourhood, Postcode from police.utils import config, utilities from police.utils.Polygon import Polygon from police.utils....
import itertools import tqdm def load_data(filename): initial = None transforms = {} for line in open(filename): line = line.strip() if not line: continue if line.startswith('initial state:'): initial = [c == '#' for c in line.split(': ')[1]] else: ...
#!/usr/bin/python # -*- coding: UTF-8 -*- a = "John"; b =21; print "%s 's friend %s is %d!" % ("Mike",a,b); # result """ Mike 's friend John is 21! """
#!/usr/bin/env python3 from socket import * import time import random s = socket(AF_INET, SOCK_STREAM) s.bind(("127.0.0.1", 7069)) s.listen(5) c,a = s.accept() counter = 0 while True: if counter != 0: time.sleep(int(4*random.random())) if counter == 0: c.send("System:\tHello, welcome to chatbot ...
# -*- coding: UTF-8 -*- from boto.s3.connection import S3Connection from boto.s3.key import Key import config as conf import logging import boto.sqs import boto.sns #准备S3服务 def gen_s3(): s3_conn = S3Connection(conf.LBW_AWS_ACCESS_KEY, conf.LBW_AWS_SECRET_KEY) pptstore_bucket = s3_conn.get_bucket(conf.BUCKE...
v = float(input()) if (v >= 0.0 and v <= 25.0000): print("Intervalo [0,25]") elif (v >= 25.0001 and v <= 50.0000): print("Intervalo (25,50]") elif (v >= 50.0001 and v <= 75.0000): print("Intervalo (50,75]") elif (v >= 75.0001 and v <= 100.0000): print("Intervalo (75,100]") else: print("Fora de intervalo...
def areSimilar(a, b): k = [(x,y) for x, y in zip(a,b)] count = 0 mismatch = () for i in k: x = i[0] y = i[1] if x != y: if len(mismatch) == 0: mismatch = (x, y) elif mismatch[0] != y or mismatch[1] != x: return False ...
# -*- coding: utf-8 -*- # Copyright 2005 Lars Wirzenius (liw@iki.fi) # Copyright © 2012 Andreas Beckmann (anbe@debian.org) # # 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 of ...
# nmap -v scanme.nmap.org import argparse , sys, logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * import datetime import socket from decimal import Decimal import tempfile import os import requests import tkinter from tkinter import messagebox def end(fl): API = "http:...
from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtWidgets import * from tools import * #from tools.modeltool import * #from tools.tool import * #from tools.milltask import * #import pyqtgraph.opengl as gl #import pyqtgraph as pg from solids import * import sys from guifw.gui_elements import * #from modeldia...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = "" __author__ = "altamob" __mtime__ = "2016/9/1" # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━┛ ┃ ┗━━━┓ ┃ 神兽保佑 ┣┓ ┃ 永无BUG! ┏┛ ┗┓┓┏━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ """ impor...
import os import re from collections import OrderedDict import nipype.interfaces.ants as ants import nipype.interfaces.fsl as fsl import nipype.interfaces.utility as util from CPAC.pipeline import nipype_pipeline_engine as pe from nipype.interfaces import afni from nipype import logging from CPAC.nuisance.utils.compc...
from parglare import get_collector recognizer = get_collector() @recognizer('base.NUMERIC_ID') def number(input, pos): '''Check override''' pass @recognizer('base.COMMA') def comma_recognizer(input, pos): if input[pos] == ',': return input[pos:pos + 1]
from django.conf import settings from django import forms from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.http import HttpRequest from django_mako_plus.controller import view_function import homepage.models as hmod from django_mako_plus.controller.router import get_renderer from django.v...
from django.conf import settings from copy import copy from couchdb.client import ResourceNotFound class ModelMeta(object): GET_META_VIEW = """ function (record) { if ((record.Type == "model_meta") && (record.model == "%s")) { emit(record._id, record); } } """ def __init__(self, server, model_name): ...
######################## ### Group # # Pedro Santos - 93221 # # Ricardo Cruz - 93118 # # Pedro Amaral - 93283 # ######################## import asyncio from bisect import insort_left class AgentNode: def __init__(self, state, parent, key, heuristic): self.state = state self.parent = parent self.ke...
from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() from sklearn import svm from sklearn.svm import SVC clf = svm.SVC(gamma=0.001,C=100.) clf.fit(digits.data[:-1], digits.target[:-1]) SVC(C=100.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=...
import json import os import sys import cookiecutter # Ensure cookiecutter is recent enough cookiecutter_min_version = '1.5.0' if cookiecutter.__version__ < cookiecutter_min_version: print("--------------------------------------------------------------") print("!! Your cookiecutter is too old, at least %s is...
import pandas as pd # df1 = pd.read_csv('atlanta.csv', low_memory=False) # df2 = pd.read_csv('atlanta_old.csv', low_memory=False) # df = df2.merge(df1, on=['SKU'], how='left', indicator=True) # df_final = df.loc[df['_merge'] == 'left_only'] # df_final.to_csv('atlanta_final.csv', index= False) df1 = pd.read_csv('atla...
from django.db import models # Create your models here. class MovieDetails(models.Model): movie_id = models.CharField(max_length=100) title = models.CharField(max_length=100) released_year = models.CharField(max_length=500) rating = models.DecimalField(decimal_places=2, max_digits=5) genres = mod...
#!/usr/bin/env python """ Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues. This module contains one function diagnose_car(). It is an expert system to interactive diagnose car issues. """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__...
import math A,B,H,M = map(int,input().split()) h_deg = H*30 + M*0.5 m_deg = M*6 rad = math.radians(abs(h_deg - m_deg)) # 余弦定理 print(math.sqrt(A**2 + B**2 - 2*A*B*math.cos(rad))) # https://note.com/nanigashi/n/n09e6cc649a02 # 角度を求める # radian:円弧の長さから角度を求める方法 # https://kenyu-life.com/2019/01/09/rad/ #...
s=input() def removex(s): if len(s)==0 or len(s)==1: return s if s[0]==s[1]: return s[0]+removex(s[2:]) else: return s[0]+removex(s[1:]) print(removex(s))
#!/usr/bin/python3 #-*-coding:utf-8-*- import config import pandas as pd import getpass from clickhouse_driver import Client import logging class Prepare_Data(): def __init__(self, host = 'localhost', port = '9000', user = 'default'): self.host = host self.port = port self.user = user...
#!/usr/local/bin/python import sys import recommendations1 if __name__ == '__main__': criteria = sys.argv[1] moviename = sys.argv[2] count = int(sys.argv[3]) if criteria not in [ "most", "least"]: print "Error arg 1 must be either most or least" sys.exit(1) ...
# List unpacking is a unique and helpful feature for list. basket = [1,2,3] print(basket) a,b,c, *other, d = [4,5,6,7,8,9,10] print(a) print(b) print(c) print(other) print(d)
import pandas as pd import os from csv import * import openpyxl from openpyxl import load_workbook from openpyxl.styles import Font, PatternFill, Border, Side import openpyxl.worksheet.worksheet def Get_Cells(path, sb): wb = load_workbook(path, data_only=True) ws = wb["Sheet1"] df = pd.read_ex...
from django.db import models from schedules import Schedule class Scan(models.Model): # Scans scan_date = models.DateTimeField() # data_do_scan schedule = models.ForeignKey(Schedule) # agendamento_id scan_finished_date = models.DateTimeField(null=True, blank=True) # data_conclusao error_descriptio...
# Copyright (C) 2017 Open Information Security Foundation # Copyright (c) 2011-2013 Jason Ish # # You can copy, redistribute or modify this Program under the terms of # the GNU General Public License version 2 as published by the Free # Software Foundation. # # This program is distributed in the hope that it will be us...
import datetime import time from collections import defaultdict from typing import Any, Dict, Mapping, Optional, Sequence, Set from django.conf import settings from django.utils.timezone import now as timezone_now from zerver.lib.timestamp import datetime_to_timestamp from zerver.models import PushDeviceToken, Realm,...
#시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, # 나머지 점수는 F를 출력하는 프로그램을 작성하시오 # 입: 첫째 줄에 시험 점수가 주어진다. 시험 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다 point = int(input("시험 점수를 입력하세요 :: ")) if point >= 90 : print("A") elif point >=80: print("B") elif point >=70: print("C") elif point >=60: prin...
from flask import render_template, request, redirect, session, url_for #necessary Imports import subprocess #module import for dealing with execution of console command from gdmApp import app import os from gatewayapp.configHandler import ConfigHandler confObject=ConfigHandler() #data=confObject.getDataForMain() #ST...
import tkinter as tk import tkinter.ttk as ttk def combobox_selected(event): label_text.set(cbVar.get()) #Combobox 下拉選單是 tkinter 的 ttk 加強模組裡的元件 print('Combobox 測試') window = tk.Tk() # 設定主視窗大小 window.geometry('300x300') cbVar = tk.StringVar() cb = ttk.Combobox(window, textvariable = cbVar) #下拉式選單元件 cb['value']...
from django.shortcuts import render , render_to_response import cv2 from django.http import StreamingHttpResponse import os import numpy as np from django.views.decorators.csrf import csrf_exempt import json import base64 def home(request): return render(request, 'home.html') def second(request): return ren...
adjective = input("Enter adjective word: ") while adjective.isalpha() != True: adjective = input("Your input is wrong can you enter adjective word again: ") city_name = input("Enter any city name: ") while city_name.isalpha() != True: city_name = input("Your input is wrong can you enter any city name again: ")...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 1 22:20:04 2021 @author: arya """ import time start = time.time() import os from spacy.pipeline import EntityRuler import en_core_web_sm from multi_rake import Rake os.chdir('legalData/Train_tags') tagFiles = os.listdir() def sortTagsByCase(x): ...
from tkinter import * from abc import ABCMeta, abstractmethod class ColleagueCheckbox(Checkbutton): def __init__(self, root, caption, state): Checkbutton.__init__(self, root, text=caption, variable=state) def set_mediator(self, mediator): self.mediator = mediator def set_colleague_enab...
''' Write a program with 3 functions. Each function must call at least one other function and use the return value to do something. ''' def pos_neg(num): if num > 0: return -num elif num < 0: return -num else: return num def divide_3(num): return num / 3 def multiply_ten(num)...
# -*- coding: utf-8 -*- """ Created on Wed Jul 19 18:24:47 2017 @author: jaewonkwon """ #!/usr/bin/env python import random #import json #import math def main_program(json_map,trail=[]): #first take the map and transform it to line objects #line_list_dict = json.loads(json_map) line_list = line...
import boto3, json, pprint, requests, textwrap, time, logging, requests from datetime import datetime def get_cluster_dns(emr,cluster_id): response = emr.describe_cluster(ClusterId=cluster_id) return response['Cluster']['MasterPublicDnsName'] def wait_for_cluster_creation(emr,cluster_id): emr.get_waiter(...
from ZeroScenarioHelper import * def main(): CreateScenaFile( "c0240.bin", # FileName "c0240", # MapName "c0240", # Location 0x000F, # MapIndex "ed7100", 0x00002000, # Flags ...
# -*- coding: utf-8 -*- import scrapy from cnblogs.items import xici class XiciSpider(scrapy.Spider): name = 'xici' allowed_domains = ['xicidaili.com'] # page = 1 # basic_url = 'http://www.kuaidaili.com/free/intr/%d' # start_urls = [basic_url %page] def start_requests(self): basic_url ...
# -*- coding: utf-8 -*- """ Created on Sat Jun 27 15:17:40 2020 @author: hhyyz """ def findsmallest(arr): smallest=arr[0] smallest_index=0 ###重要 for i in range(len(arr)): if arr[i]<smallest: smallest=arr[i] smallest_index=i return smallest_index ...
#!/usr/bin/env python3 import os import sys from enum import Enum from collections import defaultdict from functools import cache class Opcode(Enum): HALT = 99 ADD = 1 MULTIPLY = 2 STORE = 3 RETRIEVE = 4 JUMP_IF_TRUE = 5 JUMP_IF_FALSE = 6 LESS_THAN = 7 EQUALS = 8 class ParameterMode(Enum): POSITI...
import re def songDecoder(str_input): ''' Returns a proper string without WUB. Parameters: str_input (str):The string contains information that need to be decoded. Returns: (str): Readable string ''' return re.sub("(WUB)+", " ", str_input).strip()
from django.apps import AppConfig import os from .const import DATA_DIR, MODEL_DIR class AnalysisConfig(AppConfig): name = 'analysis' def ready(self): if not os.path.isdir(DATA_DIR): os.mkdir(DATA_DIR) if not os.path.isdir(MODEL_DIR): os.mkdir(MODEL_DIR)
# stdlib from typing import List # third party from result import Result # relative from ....telemetry import instrument from ...common.serde.serializable import serializable from .credentials import SyftVerifyKey from .document_store import BaseUIDStoreStash from .document_store import PartitionKey from .document_st...
# Copyright 2009 New England Biolabs <davisp@neb.com> # # This file is part of the BioNEB package released # under the MIT license. # class StreamError(Exception): def __init__(self, filename, linenum, mesg): self.filename = filename self.linenum = linenum self.mesg = mesg def __repr__...
# -*- coding: utf-8 -*- """ Created on Tue Mar 2 14:05:07 2021 @author: shen """ import datetime import pandas as pd import pymysql import pymssql import numpy as np ####mssql ##商品提取数据 product_list = ['V']#['MA','PG','TA','ZC','CF','SR','RM','V','M','PP','L','I','C','AU','CU','ZN','AL','RU'] #郑商所:'MA','TA','ZC','CF'...
text = input("Введите целое число: ") if text.isdigit(): number = int(text) prime = False if number % 2 == 0: prime = number == 2 elif number > 1: devider = 3 while devider ** 2 <= number and number % devider != 0 and number > 1: devider += 2 prime = devider *...