text
stringlengths
38
1.54M
from django.template import RequestContext from django.shortcuts import render_to_response from wormhole import wormhole import time def index(request, template_name='one/index.html'): return render_to_response(template_name, RequestContext(request, {})) @wormhole.register def sleep(request, seconds): time.sleep...
# The program will scrape the ads page by page # The URLs of ads will be written into the MariaDB database # in the server "jaguar.cs.gsu.edu" # Run "$ sudo apt-get install sshpass" in Ubuntu terminal if you see relevant errors. import datetime import os import mysql import mysql.connector class MySQLcryptomarketsD...
POWER_CLASS=0 IRQ_CLASS=1 WORK_CLASS=2 MISC_TRACES_CLASS=3 KERNEL_CLASS=4 USER_CLASS=5 plugin_list = [] class plugin: additional_colors = "" additional_ftrace_parsers = [] additional_process_types = [] def plugin_register(plugin_class): plugin_list.append(plugin_class) def get_plugins_methods(methods...
import config from collections import defaultdict from requests_futures.sessions import Session from emojiflags.lookup import lookup import logging class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton,...
import os cmd = 'python group_bonding.py' os.system(cmd) cmd = 'python group_bridging.py' os.system(cmd) cmd = 'python individual_bonding.py' os.system(cmd) cmd = 'python individual_bridging.py' os.system(cmd)
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- import os import sys import traceback import argparse import re import commands """ 该脚本用于 打包部署静态代码 参数如下 -d 远程web服务器目录 -i 远程服务器ip地址 -p 安装包路径 --config 使用配置文件,并获取配置文件中的数值 命令范例如下 python deploy.py -i 10.0.5.201 -d /usr/local/SINO/jenkins/apache-to...
n=int(input()) array=[[int(x) for x in input().split()]for y in range (n)] array.sort(key=lambda x:x[0]) array.sort(key=lambda x:x[1]) count=0 start=finish=0 for j in range(0,n): if finish<=array[j][0]: start=array[j][0] finish=array[j][1] count+=1 print (count) #main point는 끝나는 시간도 sor...
from selenium import webdriver import time name = input("Enter Series Name You Want To Search:") chrome_options = webdriver.ChromeOptions() driver = webdriver.Chrome(chrome_options=chrome_options) driver.maximize_window() driver.get(f'https://www.imdb.com/find?q={name}&ref_=nv_sr_sm') def get_series_links(): se...
from pygame import * import pyganim from settings import * import os from platformes import * MOVE_SPEED = 5 WIDTH = 22 HEIGHT = 32 COLOR = "#000000" JUMP_POWER = 9 GRAVITY = 0.35 class Player(sprite.Sprite): def __init__(self, x, y): global Player sprite.Sprite.__init__(self) ...
"""day1""" import itertools import os from .. import util def first_duplicate_frequency(ints): freq = 0 freqs = set() for i in itertools.cycle(ints): freq += i if freq in freqs: return freq freqs.add(freq) dir_path = os.path.dirname(os.path.realpath(__file__)) with op...
import os from glob import glob import pandas as pd def get_list_of_full_child_dirs(d): """ For a directory d (full path), return a list of its subdirectories in a full path form. """ children = (os.path.join(d, child) for child in os.listdir(d)) dirs = filter(os.path.isdir, children) ...
class nesh(object): def __init__(self, something): print("A init called") self.something = something class malli(nesh): def __init__(self, something): print("B init called") self.something = something nesh.__init__(self, something) a = malli("Something")
''' Write a function which takes a positive integer number n and prints [1 2 FIZZ 4 BUZZ FIZZ 7 8 FIZZ BUZZ 11 FIZZ 13 14 FIZZBUZZ … n] where multiples of 3 are replaced by FIZZ, multiples of 5 are replaced by BUZZ and multiples of both are aaareplaced by FIZZBUZZ.''' def fizzbuzz(n): if n < 1: raise ...
import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent import redis import random import threading import time import os import csv ua = UserAgent() db = redis.StrictRedis(host='127.0.0.1', port=6379, decode_responses=True) cookie_pool=[] proxy_pool={} NUM=5000 def spider(number): head...
from rest_framework import routers from django.urls import path from django.conf.urls import include from api.views import DeviceViewSet router = routers.DefaultRouter() router.register('devices', DeviceViewSet) urlpatterns = [ path('', include(router.urls)), ]
# Generated by Django 2.2 on 2021-01-31 22:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pokemon', '0001_initial'), ] operations = [ migrations.RenameField( model_name='pokemon', old_name='width', new_na...
# Problem #85 # Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, # using only mathematical or bit operations. You can assume b can only be 1 or 0. def if_b(x, y, b): if -b >> 1: return x return y assert if_b(1, 2, 1) == 1 assert if_b(1, 2, 0) == 2 assert if_b...
class RatingGenerator(): def __init__(self, rating=0): self.rating = rating def simple_word_by_word_rating(self, list1, list2): score = 0.0 #Swap lists to avoid index error if list1 longer than list2 if len(list1)>len(list2): temp = list1 list1 = list2 ...
from django.conf.urls import include, url from .feeds import BlogFeed from .views import PostList, PostDetail urlpatterns = [ url('', PostList.as_view(), name='blog-post-list'), url('feed/', BlogFeed(), name='blog-post-feed'), url('<slug:slug>/', PostDetail.as_view(), name='blog-post-detail'), ]
import os from store.redis_store import Store from app.carts import API badge = """ :oooooo/ `....-ss` os- :s+ `ssssssssssssssssssssssssssss/ os/---+s+----os/----os/---os: :sooooosooooossooooossooooss` `ss/::/ss/:::os+:::+so:::+s+ +s+///ss+///os+///os...
import argparse import os import os.path as osp import warnings import copy import numpy as np import json import mmcv import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.fileio.io import dump, file_handlers from mmcv.parallel import MMDataParallel, MMDistributedDataParallel fro...
#exception def calc(data): sum=0 try: sum=data[0]+data[1]+data[2] if sum<0: raise Exception("sum error") except IndexError as err: print('indexerror : ',str(err)) except Exception as err: print(str(err)) finally: print('sum : ',sum) ...
import unittest from Spreadsheet.HTML import Table class TestPadding(unittest.TestCase): def test_padding(self): data = [ [ 'header1', 'header2', 'header3' ], [ 'foo1', 'bar1' ], [ 'foo2' ], ] gen = Table() self.assertEqual( '<tabl...
from RecipeManager.models import * def runit (): for recipe in Recipe.objects.all(): for version in recipe.versions.all(): print(version.id) for method in version.methods.all(): print(method.desc) if method.desc is not None: print(method.desc)
""" 돌 게임은 두 명이서 즐기는 재밌는 게임이다. 탁자 위에 돌 N개가 있다. 상근이와 창영이는 턴을 번갈아가면서 돌을 가져가며, 돌은 1개 또는 3개 가져갈 수 있다. 마지막 돌을 가져가는 사람이 게임을 이기게 된다. 두 사람이 완벽하게 게임을 했을 때, 이기는 사람을 구하는 프로그램을 작성하시오. 게임은 상근이가 먼저 시작한다. """ n = int(input()) # 순서를 정해주는 함수 def changer(phase): if not phase: # 처음은 무조건 SK return "SK" elif phase == "SK":...
import random from itertools import combinations # Available colors RED = 'red' GREEN = 'green' PURPLE = 'purple' # Available shapes DIAMOND = 'diamond' SQUIGGLE = 'squiggle' OVAL = 'oval' # Available shadings SOLID = 'solid' EMPTY = 'empty' STRIPED = 'striped' # Available numbers ONE = 'one' TWO = 'two' THREE = 't...
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): set_lst = list(set(ar)) lst = [] for i in set_lst: temp = 0 temp = ar.count(i) if temp == 0 or temp == 1: temp = ...
#!/usr/bin/python # # Copyright 2011 Google Inc. 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 b...
import tkinter import threading import time from Sortingbot import * mode = ["trash", "report", "note","","",""] modeColor = ["orange", "pink", "purple","","",""] # Max mode number = 3 def defineMode(name, color, index=3): if index == 6: print("index out of range!") return if (mode[index] == ""): ...
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 16:56:49 2020 @author: BreezeCat """ import json import Agent import Communication_func as Comm import time A = Agent.Agent('A', -3, 1, 0, 0, 0, 0.2, 3, -1, 0, 1, mode = 'Greedy') B = Agent.Agent('B', -3, -1, 0, 0, 0, 0.2, 3, 1, 0, 1, mode = 'Greedy') C = Agent.Agen...
# -*- coding: utf-8 -*- """ Created on Tue Feb 9 20:55:17 2021 See my comments, this script may require you to download a local NCBI database, it takes a couple minutes. I used ete3 because it had better documentation and a get_lineage function. Entrez was more confusing because it required me to use their...
# Copyright (c) OpenMMLab. All rights reserved. _base_ = [ 'mmdet::_base_/models/faster-rcnn_r50_fpn.py', 'mmdet::_base_/datasets/coco_detection.py', 'mmdet::_base_/schedules/schedule_1x.py', 'mmdet::_base_/default_runtime.py' ]
# This test does *not* currently work. It serves as an example of why # implementing fully dynamic typing is difficult. c = 1 c = "hello" c = 0.2 def screwy(x): if type(x) is str: return 1 if type(x) is int: return 'i' c = screwy(c)
import time import pygame import os import sys import random import binascii import re pygame.init() scrX = pygame.display.Info().current_w scrY = pygame.display.Info().current_h # Insert base64 teletext string here super64 = 'BQt-_Xtw8taDpo080HDDnyoOm9Bzw9sqDzv68kHffy1oECAo4cOHCAl4KKHDhw4cOHDhw4cOHDhw4cOHDhw4cOHDhw...
#!/usr/bin/python import sys def compute(prey): if prey[1] > prey[1]: temp0 = max(prey[0], prey[1]) else: if prey[0] > prey[0]: if prey[0] > prey[0]: temp0 = prey[1] - prey[1] else: if prey[1] != 0: temp0 = prey[0] / prey[1] else: temp0 = prey[1] else: temp0 = max(prey[0], prey[1...
import time from itertools import cycle from flask import Flask, render_template import RPi.GPIO as GPIO app = Flask(__name__) state_cycle = cycle(['on', 'off']) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) locations = { } @app.route("/") @app.route("/<state>") @app.route("/<location>/<state>") def update_la...
from flask.ext.httpauth import HTTPBasicAuth from ..models import User from flask import g #from ..insight import app from flask import current_app auth = HTTPBasicAuth() @auth.verify_password def verify_password(username_or_token,password): user = User.verify_auth_token(current_app.config["SECRET_KEY"]) if not us...
# Import datasets, classifiers and performance metrics from sknn.mlp import Classifier, Layer import numpy as np import logging logging.basicConfig() # The digits dataset opt = [] f = open("feature_open_hand", "r+") ipt_open = f.read() f.close() ipt_open = ipt_open.split("\n") for i in range(0,len(ipt_open)-1): ipt...
import sys from distutils.core import setup from setuptools.command.test import test as TestCommand class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import tox errno ...
import json from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from rest_framework.views import APIView from rest_framework.decorators import api_view, permi...
from django.contrib import admin from . import models # Register your models here. @admin.register(models.Movie) class MovieAdmin(admin.ModelAdmin): list_display = ( "title", "total_rating", "genre", "director", "year", "created", ) list_filter = ( ...
import gtk import threading from automaton.lib import exceptions from automaton.lib.utils import locked from automaton.lib.plugin import UnsuccessfulExecution class StatusIcon(gtk.StatusIcon): """Icon that displays itself in the status bar and gives access to Automaton. """ def __init__(self, server): g...
import model import sys def reg(): login = (input("Придумайте логин\n")).lower() password = input("Придумайте пароль\n") email = (input("Введите емейл\n")).lower() model.read_db() if model.reg_db(login,password,email) == True: print('Регистрация прошла успешно.') return reg_or_auth...
# if user input is "p", print "Hello" # else if user input is "q", print nothing.add() user_input = input("please enter either p or q: ") while user_input != "p": print("") break if user_input == "": print("Hello")
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lic...
from dazer_methods import Dazer from collections import OrderedDict from numpy import empty, random, median, percentile, array, linspace from scipy import stats from uncertainties import ufloat fro...
age = int(input('请输入你的年龄:')) if age < 40: print('Young man') else: print('Old man')
import os import zipfile import h5py import numpy as np import pandas as pd from recommender_datasets import _common def _read_csv(fname, columns=('user_id', 'item_id', 'rating', 'timestamp')): with zipfile.ZipFile(fname, mode='r') as archive: with archive.open('data.csv') as datafile: df ...
import json import numpy as np import argparse from random import randint import cv2 with open('../infos/directory.json') as fp: all_data_dir = json.load(fp) ANN_FILE_train = all_data_dir + 'Annotations_vcoco/train_annotations.json' ANN_FILE_val = all_data_dir + 'Annotations_vcoco/val_annotations.json' ANN_FILE_test ...
import hashlib import json import logging import time block = ''' hash : %s +%s+ version : %s prehash : %s timestamp : %s nonce : %s target: %s mercle: %s +%s+ trans : %s +%s+ | | V ''' def sha256(str): ...
import falcon import json from megapy import ArduinoConnection, MegaException from app import MegaRestApp, Exception400 import traceback class DeviceResource(object): def __init__(self, conn): self.connection = conn def on_get(self, req, resp): try: print "Received {} {} request ...
import xlsxwriter from datetime import timedelta, date import pandas as pd def daterange(date1, date2): for n in range(int ((date2 - date1).days)+1): yield date1 + timedelta(n) # mảng, hàng_event, cột_event, chiều_dài_event def is_avaiable_event(arr, event_row_postion, event_col_postion, e...
import config.package import os, sys class Configure(config.package.Package): def __init__(self, framework): config.package.Package.__init__(self, framework) self.download = ['http://launchpad.net/fiat/0.x/0.9.9/+download/fiat-0.9.9.tar.gz'] # 'http://ftp.mcs.anl.gov/pub/petsc/externalpackages/fiat-dev.tar.g...
x=input() count1=1 for t in range(0,x): num=input() if(num==0): print "Case #"+str(count1)+": " + str("INSOMNIA") count1=count1+1 else: list=[] count=1 while(1): d=num*count while(1): b=d/10 c=d%10 if(b==0 and c==0): break else: ...
import numpy as np import matplotlib.pyplot as plt import random from scipy.linalg import expm from scipy.stats import chisquare class Patient: def __init__(self, q, id_, x0=0): self.q = q self.id_ = id_ self.x0 = x0 # initial state self.x = x0 self.time = 0.0 self.alive = self.is_alive() self.history ...
import argparse import asyncio from typing import List, Any import pandas as pd import parser import config def load_person_data(file_name): df = pd.read_csv(file_name) # post_df = pd.DataFrame() df['bday'] = pd.to_datetime(df['birthdate']).dt.strftime('%d-%m-%Y') df.dropna(axis=0, how='any', inplac...
# Generated by Django 2.2.3 on 2019-08-24 18:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flights', '0008_auto_20190824_1849'), ] operations = [ migrations.AlterField( model_name='airport', name='keywords',...
import Function class BusinessElemet: def __init__(self, _RestaurantId, _Rating, _CategoriesCnt, _CategoriesText, _ReviewCount): self.RestaurantId = _RestaurantId self.Rating = _Rating self.CategoriesCnt = _CategoriesCnt self.CategoriesText = _CategoriesText self.ReviewCoun...
import sqlite3 import json def pageview_settings(): try: conn = sqlite3.connect("webdata.db") c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS TABLEVIEW (Id INTEGER PRIMARY KEY, name TEXT, type TEXT)") c.execute("SELECT * FROM TABLEVIEW") rows = c.fetchall() ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import math from functools import partial # for trials from collections import OrderedDict # for dynamic configuration definition import os # for paths from pathlib import Path # for OS agnostic path definition import numpy as np # for accuracy math # allow configura...
import numpy as np a = np.array([1, 3, 3, 4, 4]) b = np.array([3, 3, 4, 5, 6]) less = a < b lessThanEquals = a <= b greater = a > b greatThanEqual = a >= b print(less) print(lessThanEquals) print(greater) print(greatThanEqual)
import random import numpy as np from collections import deque class ReplayBufferEpisode(object): def __init__(self, buffer_size, batch_size, random_seed=1234): """ The right side of the deque contains the most recent experiences """ self.buffer_size = buffer_size self.bat...
# Generated by Django 2.2.13 on 2020-11-30 14:16 from django.db import models, migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('per', '0036_auto_20201123_1055'), ] operations = [ migrations.AddField( model_name='formquestion', ...
from aiogram.dispatcher.filters.state import State, StatesGroup class GetIDs(StatesGroup): channel = State() user_info = State()
from rest_framework import serializers from extras.models import CF_TYPE_SELECT, CustomFieldChoice, Graph class CustomFieldSerializer(serializers.Serializer): """ Extends a ModelSerializer to render any CustomFields and their values associated with an object. """ custom_fields = serializers.Serialize...
# users/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): name = models.CharField(max_length=255) def __str__(self): return self.email class Client(models.Model): user = models.OneToOneField(CustomUser , on_delete = models.C...
''' Package ''' import argparse import configparser from contextlib import contextmanager import datetime import getpass import io import json import logging import operator import os import re from urllib3.util.retry import Retry import uuid from geopy.distance import geodesic import piexif import requests CLIENT_...
def poly_func(x): return -5 * x**5 + 69 * x*x - 47 print poly_func(0) print poly_func(1) print poly_func(2) print poly_func(3)
# -*- coding: utf-8 -*- from datetime import datetime from django.shortcuts import render from django.http.response import HttpResponseRedirect, HttpResponse,\ StreamingHttpResponse from django.contrib.auth.decorators import login_required #使用注意在settings.py中设置 LOGIN_URL = '/login/' from django.utils.safestring impo...
__author__ = 'Stephen "TheCodeAssassin" Hoogendijk' import os import sys import gnupg from BTB import Validator as Validator class Runner: quiet = False simulate = False config = None arguments = [] validator = None operating_system = None git_url = None version = None gnupghome =...
# CONSECUTIVE 1s # Given a binary array, find the maximum number of consecutive 1s in this array. # [1,1,0,1,1,1] def solution(): recordCount = 0 currentCount = 0 l1 = [] for i in range(len(l1)): if l1[i] == 1: currentCount += 1 if i == len(l1) - 1: if cur...
"""Simple report showing various features of Pyreball.""" import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pyreball as pb pb.set_title("Sample Report") pb.print_h1("Displaying Texts") pb.print_html("<div>We can always start inserting custom raw HTML code.</div>") p...
from rpc_forge import * class Struct_40_t(NdrStructure): MEMBERS = [NdrLong, NdrLong, ] class Struct_48_t(NdrStructure): MEMBERS = [NdrLong, Struct_40_t, Struct_40_t, Struct_40_t, ] class Struct_170_t(NdrStructure): MEMBERS = [NdrLong, NdrLong, Struct_48_t, ] class Union_24_t(NdrUnion): SWITCHTYPE = ...
# -*- encoding: utf-8 -*- import json import pytest from django import forms from bpp.views.api.uzupelnij_rok import ApiUzupelnijRokWydawnictwoZwarteView, \ ApiUzupelnijRokWydawnictwoCiagleView @pytest.mark.django_db def test_ApiUzupelnijRokWydawnictwoZwarteView_get_data(wydawnictwo_zwarte): x = ApiUzupelni...
from PIL import Image # Opens a image in RGB mode im = Image.open(r"C:\Users\suddharshan\Downloads\Cali.png") # Size of the image in pixels (size of orginal image) # (This is not mandatory) width, height = im.size left=35 right=200 a=7 b=0 top=130 # Setting the points for cropped image for top ...
from apps.app.setting import QINIU_HOST from models.zhuzhu.model import * tb_zone = Zone() tb_level_one = LevelOne() tb_level_two = LevelTwo() def zone_list_and_size(spec): if not spec: spec = {} results = tb_zone.find(spec) count = tb_zone.count(spec) data = [] for result in results: ...
import datetime import apache_beam as beam import argparse from sys import argv parser = argparse.ArgumentParser() parser.add_argument('--gs_input') parser.add_argument('--gs_output_bucket') known_args, pipeline_args = parser.parse_known_args(argv) def _get_date_components(ts): """Generates date components fr...
# Generated by Django 3.1 on 2020-08-21 18:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20200820_1434'), ] operations = [ migrations.AlterModelManagers( name='article', managers=[ ], ...
def func(x): if x == 1: def rv(): print("x is equal to 1") else: def rv(): print("x is not 1") return rv new_func = func(2) new_func()
import unittest from parameterized import parameterized from woniubossAPIDDT.lib.training import Training from woniubossAPIDDT.tools.service import Service from woniubossAPIDDT.tools.uiti import uiti test_info = uiti.get_json('..\\conf\\testdata.conf') train_infos=uiti.trans_dict_tup(test_info[1]) follow_infos = uit...
import imageio import numpy as np class GameOfLife(object): def __init__(self, width_height, square_size): self.square_size = square_size self.width_height = width_height self.field_width = int(width_height/square_size) self.state = [[0 for _ in range(self.field_width)] fo...
from fortpy.elements import Function, Subroutine, CustomType, ValueElement from fortpy.elements import Module, Executable, Interface from fortpy.docelements import DocElement from . import cache from .classes import Completion class Evaluator(object): """Uses the user context and code parsers to perform code c...
import torch import numpy import onnx import onnxruntime import time target_name = "/home/alex/Models/Yawn/_.onnx" model = torch.load("./build/yawning_resnet4s_test_f1.pth").to(torch.device('cpu')) model.eval() dummy_input = torch.randn(1, 3, 64, 64) torch.onnx.export(model, dummy_input, ...
import os import glob import cv2 as cv from Car_Number_Plate_Detection import * path = glob.glob("./data/images/*.png") i=1 for img in path: path1 = 'python detect.py --weights ./checkpoints/custom-416 --size 416 --model yolov4 --images ./data/images/car'+str(i)+'.png --crop' os.system(path1) path2 = './d...
from sqlalchemy import create_engine import pandas as pd import time import config as cfg import logging # GRANT ALL PRIVILEGES ON testdb.* To 'testuser'@'24.6.58.95' IDENTIFIED BY '**'; class mysql_engine: def __init__(self, username, password, host, db_name): db_log_file_name = 'db.log' db_hand...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC from scipy import stats from sklearn.metrics import accuracy_score df = pd.read_csv("week2.csv") X1 = df.iloc[:, 0] X2 = df.iloc[:, 1] y = df.iloc[:, 2] # (c)...
from cgi import FieldStorage import tarfile import os import tempfile import time import shutil from json import loads as json_loads try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from collections import OrderedDict, defaultdict from zipfile import BadZipfile from sqlalch...
import wtforms as forms from wtforms import validators, widgets from wtforms.widgets.core import HTMLString, html_params from extra.lib.regions import REGION_CHOICES, COUNTRY_CHOICES from extra.formfields import ExpDateField class OptGroupSelect(widgets.Select): def iter_group(self, field, group): for val...
#coding:utf-8 from settings_local import * from os.path import join, abspath, dirname rel = lambda x: join(abspath(dirname(__file__)), x) TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru-RU' SITE_ID = 1 USE_I18N = True USE_L10N = True MEDIA_ROOT = rel('../upload/') MEDIA_URL = '/upload/' STATIC_ROOT = rel('stat...
import logging import os def load_stopwords(stopwords_path): stopwords = set() with open(stopwords_path, 'r') as f: n = 1 while True: stopword = f.readline() if stopword == '': break stopwords.add(stopword.strip('\n')) n += 1 ...
import sqlite3 database = sqlite3.connect("my_database.db") cursor = database.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS Users ( id INTEGER PRIMARY KEY, first_name varchar(255), last_name varchar(255), phone_number INTEGER ); """) # cursor.execute(""" # insert into User...
from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): is_verified = models.BooleanField(default=True) public_name = models.CharField(max_length=130, null=True, blank=True) phone_number = models.CharField(max_length=12, blank=True) city = models.C...
from PyQt5.uic import loadUiType from PyQt5 import QtCore, QtGui, QtWidgets from matplotlib.backends.backend_qt5agg import ( FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar) from main import Main import os dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardi...
class Vertex: def __init__(self, adj_vertex = None): if adj_vertex: self.adj_list = [adj_vertex] # [(index, weight)] else: self.adj_list = [] class Graph: def __init__(self, n): # 인접행렬 보다 리스트가 유리(트리기 때문에) self.vertices = [0] * (n + 1) def insert(self...
""" Write a program that takes as input a singly linked list and a nonnegative integer k, and returns the list cyclically shifted to the right by k. """ class Node: def __init__(self, data=0, next=None): self.data = data self.next = next # g = Node(5) # f = Node(5, g) # e = Node(4, f) # d = Node...
class Mark_Zoid: def __init__ (self): self.state = "SEARCH_TASK"; return; def update_board(self, board, bot_pos): self.table = board; self.bot = bot_pos; return; def distance_between_blocks(self, source, dest): return pow(source[0]-dest[0], 2) + pow(source[1...
# 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 # d...
from selenium import webdriver # 创建实例 browser = webdriver.Chrome() # 请求百度首页 browser.get("http://www.baidu.com") # 获取网页源码 print(browser.page_source) browser.close()
record = { 1 : {"Name" : "John" , "Class" : 9, "Marks" : 92}, 2 : {"Name" : "Joe" , "Class" : 4, "Marks" : 62} , 3 : {"Name" : "Jill" , "Class" : 6, "Marks" : 72}, 4 : {"Name" : "Jack" , "Class" : 7, "Marks" : 96}, 5 : {"Name" : "Johny" , "Class" : 10, "Marks" : 84}} studen...
from torch import nn import numpy as np import torch.nn.functional as F import torch from typing import Dict def conv_block(in_channels: int, out_channels: int) -> nn.Module: return nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(), ...