text
stringlengths
8
6.05M
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.codegen.thrift.apache.python import additional_fields from pants.backend.codegen.thrift.ap...
import requests from bs4 import BeautifulSoup import pandas as pd link = "http://www.ipeen.com.tw/search/taipei/000/1-0-0-0/?baragain=1&so=sat" NextPage = "http://www.ipeen.com.tw" count = 1 alldata = [] tmplink = [] def SplitStr(InputStr): #宣告副程式 city = "" #用來存取區域的變數名稱宣告成strin...
"""``pytest`` fixtures.""" import pytest from tinyflow import __license__ from tinyflow import _testing @pytest.fixture(scope='module') def wordcount_input(): return __license__.splitlines() @pytest.fixture(scope='module') def wordcount_top5(): return {'the': 13, 'of': 12, 'or': 11, 'and': 8, 'in': 6} ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-31 23:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AddField( mo...
import pytest import allure @allure.title("Запрос всех доступных ресурсов") @pytest.mark.xfail(reason="Как пример падающего теста", strict=True) def test_get_all_resources(session, base_url): response = session.get(url=f'{base_url}') assert response.status_code == 200, f"Неверный код ответа, получен {response...
from __future__ import print_function import shutil import os import glob import cv2 import numpy as np #path = '../data/img/training/' #output_path = '../data/img/training/' path = '../data/mask/95_masks_ori/' output_path = '../data/mask/95_masks/' for img_name in glob.glob(path + '/*.png'): pure_name = img_name...
from mysql.connector.errors import Error from flask import Blueprint, flash, g from flask_restful import Api, Resource, reqparse, fields, marshal_with from homework.db import get_db # 下面为department的api的实现 parser_departmentItem = reqparse.RequestParser() parser_departmentItem.add_argument('departName', required=True, ...
#!/usr/bin/env python3.6 # -*- coding: iso-8859-15 -*- import pygame from pygame.locals import * from OpenGL.GL import * #from OpenGL.GLUT import * from OpenGL.GLU import * import numpy as np BLACK = (0.0, 0.0, 0.0) WHITE = (1.0, 1.0, 1.0) MAJOR_BLUE = (0.290198, 0.627456, 0.729418) MINOR_BLUE = (0.078432, 0.20392...
from __future__ import unicode_literals, print_function from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.generic import GenericRelation from django.conf import settings from cjklib.characterlookup import CharacterLookup from hitcount.models import HitCount from...
from test.tts.mytts import gTTS def test(): tts = gTTS("罗大姐说,她弟弟在买奔驰之前,就跟她提起过一个女朋友,按弟弟的描述,那就是一个典型的白富美,但弟弟从来没带对方来见过面",lang='zh') tts.save("E://temp/tts/gtts.mp3") # tts.save("/home/recsys/hzwangjian1/data/test_gtts91.mp3")
#!/usr/bin/env python def laceStrings(s1,s2): if len(s1) > len(s2): maxlen = len(s1) else: maxlen = len(s2) res = '' for i in range(maxlen): if i < len(s1): res += s1[i] if i < len(s2): res += s2[i] return res print laceStrings('','') print laceStrings('12','ab') print laceStrings('1','ab') print l...
#!/usr/bin/env python3 # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Updates the list of Observatory source files. import os import sys from dateti...
# Copyright 2014 Google. # # 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, softw...
with open("artifacts01.txt","w+") as f: f.write("text in stage01.py")
""" Transform AWS Transcribe json files to docx, csv, sqlite and vtt. """ from docx import Document from docx.shared import Cm, Mm, Inches, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH import json, datetime import matplotlib.pyplot as plt import statistics from pathlib import Path from time import perf_count...
#!/usr/bin/python """ A simple script that: 1 - Connects to the ICOM-M802 via serial port on COM9 (Windows) or ttyUSB4 (Linux). Adjust the COM/TTY ports to match your system setup. Comment out lines 14/15 depending on if you are Linux/Windows based. This is the call that will turn on the ICOM-M802 head-unit if it i...
import datetime import streamlit as st #from playsound import playsound def alarm(alarmH,alarmM,ap): if ap == 'pm': alarmH=alarmM+12 while(True): if(alarmH==datetime.datetime.now().hour and alarm==datetime.datetime.now().minute): st.write("Time to wake up") audio_file=ope...
# Code to perform bit reversal def bitreversal(N,lo,hi): binary_num=bin(N) print ("Binary of ",N,"is equal to = ",binary_num) binary_rep=binary_num[2:len(binary_num)] str1=binary_rep[0:lo] str2=binary_rep[lo:hi+1] str3=binary_rep[hi+1:] str2_new='' for i in range(0,len(s...
from .crosslingual_vectors import Crosslingual from torchtext import data from .NERDataset import NERDataset from torchtext.datasets import SequenceTaggingDataset import logging import numpy as np import torch import math DATA_RELATIVE_PATH = 'data' logger = logging.getLogger("data") # predefine a label_set: PER - 1,...
from pyspark.sql import * from pyspark.sql.types import * import os import shutil import subprocess spark = SparkSession.builder \ .master("local") \ .appName("Data Integration") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() def get_or_create_dataframe(schema, path=None, format=...
import torch.nn as nn from .utils import repeat_module, LayerNorm, SublayerConnection class Encoder(nn.Module): """ stack of N encoder layers """ def __init__(self, layer, N): super().__init__() self.layers = repeat_module(layer, N) self.norm = LayerNorm(layer.model_dim) def forwar...
from models.users import UserModel from flask_restful import reqparse,Resource class UserRegister(Resource): parser = reqparse.RequestParser() parser.add_argument('username',type=str,required=True,help='This field is required') parser.add_argument('password',type=str,required=True,help='This field is requi...
import json from flask import Blueprint, render_template, request, redirect, url_for from src.models.bsb.orders.order import BSBOrder from src.models.bsb.orders.utils import handleRequestForm __author__ = 'nabee1' bsborder_blueprint = Blueprint('bsborders', __name__) @bsborder_blueprint.route('/') def index(): ...
from mezzanine.conf import register_setting from django.utils.translation import ugettext_lazy as _ # import as '_', used for trans # These register setting to editable in the admin easily. # http://mezzanine.jupo.org/docs/configuration.html#registering-settings # Register our new settings, so we can change their va...
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref Base = declarative_base() ...
from pycocotools.coco import COCO import numpy as np import skimage.io as io # pip3 install scikit-image import matplotlib.pyplot as plt import pylab import os def parameters(): param = {} #pylab.rcParams['figure.figsize'] = (8.0, 10.0) dataDir='../bipolar_data' param['dataDir'] = dataDir dataT...
from modules.facility import facility detroit = facility('DETROITMI') rmi = detroit.rmi cfr = detroit.cfr pfi = detroit.pfi pfo = detroit.pfo pis = detroit.pis pck = detroit.pck time = 0 transfer = pd.DataFrame( { 'jb_color':['Coloring Agent1', 'Coloring Agent18'], 'amount':[45000, 250000] } ...
# Generated by Django 2.0.3 on 2018-03-14 06:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('orders', '0005_auto_20180314_0610'), ] operations = [ migrations.CreateModel( name='ConatacForm', fields=[ ...
from django.db import models # Create your models here. class Product(models.Model): img = models.ImageField(upload_to='img/course_list', default='assets/images/product_03.jpg') price = models.DecimalField(max_digits=10, decimal_places=2) name = models.CharField(max_length=100, default="") desc = mode...
filepath = 'input.txt' f = open(filepath, 'r') contents = f.readlines() numlines = len(contents) for index, line in enumerate(contents): for index2 in range(index+1, numlines): charcount = 0 for cindex in range(len(line)): if contents[index][cindex] != contents[index2][cindex]: ...
from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models import * from django.core.paginator import Paginator from django.db.models import Q from django.core.exceptions import ValidationError class BlogObjectsMixin: model = None url = None paginator = False...
list_of_words = [ "python", "adventure", "words", "banana", "measure", "cooing", "milk", "wheel", "illegal", "wretched", "spy", "letter", "curl", "haunt", "trip", "own", "bleach", "flimsy", "useful", "unlock", "sedate", "double", ...
#Write a Python program to convert a list of characters into a string def charToString(character): print(' '.join(character)) character = ['a','s','d','r','g','f'] charToString(character)
"""Написать свою реализацию функции filter.""" from typing import Union, Callable test_list = [] test_tuple = ()
from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') author = models.TextField(null=True) body = models.TextField() def summary(self): if len(self.body) > 100: return se...
""" This type stub file was generated by pyright. """ import sys PY2 = sys.version_info[0] == 2 if PY2: def iteritems(d): ... def itervalues(d): ... xrange = xrange string_types = (unicode, bytes) def to_str(x, charset=..., errors=...): ... else: def iter...
from CallBackOperator import CallBackOperator from SignalGenerationPackage.Sinus.SinusSignalController import SinusSignalController from SignalGenerationPackage.UserSignal.UserSignalController import UserSignalController from SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensitySignalController import...
from .responses import bucket_response, key_response url_bases = [ "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3.amazonaws.com" ] url_paths = { '{0}/$': bucket_response, '{0}/(?P<key_name>[a-zA-Z0-9\-_.]+)': key_response, }
# Copyright (C) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
#-*—coding:utf8-*- import numpy as np import gc import re import csv import codecs from decimal import * import os try: fil_winsize = codecs.open("list.txt", "r", 'utf_8_sig') # fil6 = codecs.open("channel_ssid_time.csv", "w", 'utf_8_sig') winsize = csv.reader(fil_winsize) # write_ssid = csv.writer(fil6...
from django.db import models from django.utils import timezone class Msg(models.Model): name = models.CharField(max_length=200) title = models.CharField(max_length=200) text = models.TextField() date = models.DateTimeField( default=timezone.now) def __str__(self): ...
import binascii import unittest from encoding.base58_check import Base58CheckAddress from encoding.byte_conversion import to_n_bits from encoding.cashaddr import AddressType, Cashaddr class CashaddrTest(unittest.TestCase): def test_polymod(self): """ Polymod should return 0 """ ca...
from datetime import datetime import json from pathlib import Path import sys import click import humanize from tabulate import tabulate from tqdm import tqdm from ai.backend.cli.interaction import ask_yn from ai.backend.client.config import DEFAULT_CHUNK_SIZE, APIConfig from ai.backend.client.session import Session ...
import pytest class Test_a(): def setup(self): print("--setup---") def setup_class(self): print("--1setup_class--") def teardown(self): print("---teardown---") def teardown_class(self): print("--1teardown_class--") def test_001(self): assert True def tes...
# -*- coding: utf-8 -*- """ Created on Tue Oct 29 17:56:44 2019 @author: KelvinOX25 """ import time import numpy as np import matplotlib.pyplot as plt from qcodes.instrument_drivers.tektronix.AWG3252_Isrc import AWG3252_Isrc from qcodes.instrument_drivers.HP.HP34401 import HP34401 from qcodes.instrument.base import ...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 import os import pytest import uvloop from kafka.client import KafkaClient as PyKafkaClient from kafka.cluster import ClusterMetadata # StoreRecord import from tonga.models.store.store_record import StoreRecord from tonga.models.store.store_record_han...
import sys sys.path.insert(0, '/home/jesperes/dev/libstdc++-v3/python') import libstdcxx.v6.printers libstdcxx.v6.printers.register_libstdcxx_printers(None)
print(0.1 + 0.2) #0.30000000000000004 -> 오차가 붙기 때문 print(0.1 + 0.2 == 0.3) #False import decimal a = decimal.Decimal("0.1") b = decimal.Decimal("0.2") print(a) #0.1 print(b) #0.2 print(a + b) #0.3 -> 정확하게 연산을 하니 0.3이 나옴 #분수 표현 클래스 import fractions a = fractions.Fraction(3, 10) #분자 분모 b = fractions.Fraction(-2, 20) pr...
""" some utilities to work with xarray objects """ import numpy as np import xarray as xr def strip_coords(X, coords=None, inplace=False, as_str=True): """ strip blanks from string coordinates Parameters ---------- X : DataArray or Dataset coords : iterable (Default None) Iterable o...
""" 需求:小猫爱吃鱼,小猫爱喝水 """ class Cat: def eat(self): print("小猫吃鱼") def drink(self): print("小猫喝水") # 创建对象 tom = Cat() # 使用 .属性名 利用赋值语句就可以 tom.name = 'tom' tom.eat() tom.drink() # print(tom) # print("%x" % id(tom)) # %x 16进制 print('-'*30) # 创建另一个对象 lazy_cat = Cat() lazy_cat.age = 12 lazy_cat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Unit test module. Unit Tests in this module will often compare size and offset between the libclang version and the ctypeslib-processed python version the types. Because the objective of this framework is not to verify if libclang or the python bindings work, there wi...
# -*- coding: utf-8 -*- """ Created on Thu May 23 03:29:24 2019 @author: Parth Bhandari """ import cv2 import numpy as np from sklearn.externals import joblib from keras.preprocessing import image dic = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f', 7 : 'g', 8 : 'h', 9 : 'i', 10 :...
import re from collections import OrderedDict from functools import partial from typing import Any, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from torch import Tensor from ..transforms._presets import ImageClassification from ..utils i...
# Generated by Django 3.1.2 on 2020-11-11 18:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shopping', '0004_product_comment'), ] operations = [ migrations.RemoveField( model_name='product', name='comment', ...
import sys, os sys.path.append(os.pardir) from dataset.mnist import load_mnist from DeepConvNetwork import DeepConvNet from common.trainer import Trainer (a_train, b_train), (a_test, b_test) = load_mnist(flatten=False) network = DeepConvNet() trainer = Trainer(network, a_train, b_train, a_test, b_test, ...
# 列表推导式列表 字典推导式 集合推导式 # 旧的列表---新的列表 # 1、列表推导式 # 格式:[表达式 for 变量 in 旧的列表] 或者[表达式 for 变量 in 旧的列表 if 条件] # 过滤掉长度小于或者等于3的人名 names = ['xiaomei', 'xiax', 'bob'] result = [name for name in names if len(name) > 3] # 第一个name 是符合条件的name 存放值,第二个name是从names中遍历的值, print(result) # 将获取的名字首字母大写 names = ['xiaomei', 'xiax',...
from .driverchrome import DriverChrome from .driverfirefox import DriverFirefox from .driverIE import DriverIE from .driver import IDriver from .driverFactory import DriverFactory
from decimal import Decimal def convert_to_frames(cut_list, frame_rate): START_THRESHOLD = 0.5 out = [] for i, cut in enumerate(cut_list): # Clean first pyannote audio start time if cut['start'] < START_THRESHOLD and cut['end'] > START_THRESHOLD and i == 0: out.append({'start': 0, 'end': int(frame...
from django.shortcuts import render # Create your views here. from rest_framework import viewsets, mixins from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import SessionAuthentication from user_operation.s...
from requests import * from json import * from re import * url="media/videos" array_world_to_find=[ "" ] array_url=[ """List of your videos""" ] min_like=100 s=Session() array_username=[] array_like=[] array_appear=[] array_comment=[] for full_url in array_url: obj=s.get(ful...
# dict2 遍历字典 dict1 = {"name": "xianqian", "age": 25,"sex": "girl"} print(type(dict1)) for i in dict1: print(i, dict1[i]) dict1[None] = "laotian" # None可以作为键 dict1[None] = "laowen" # None键也不能重复,重复时后面的还会覆盖前面的 dict1["grade"] = None # 值可以为None dict1["class"] = None # 值可以重复 print(dict1)
class BinarySearchTree: def __init__(self, array): self.root_node = Node(None) self.counter = 0 for key in array: self.insert(self.root_node, key) def insert(self, current_node, key): """Recursive insertion with in-place count updating Params: current_node ...
#To use % in string formatting a=raw_input('What is your name? ') b=raw_input('What is your favorite sport? ') print "Sooooo your name is %s, and you really enjoy playing %s..."%(a, b) print "" print "I AM A GENIUS!"
from datetime import datetime import unittest from zoomus import components, util import responses def suite(): """Define all the tests of the module.""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(AddPanelistsV2TestCase)) return suite class AddPanelistsV2TestCase(unittest.TestCas...
from time import sleep from nameko.events import EventDispatcher, event_handler from nameko.rpc import rpc class ServiceA: """ Event dispatching service. """ name = "service_a" dispatch = EventDispatcher() @rpc def dispatching_method(self, payload): self.dispatch("event_type", paylo...
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from GradientHelpers import abs_sobel_thresh, mag_thresh, dir_threshold # Read in an image image = mpimg.imread('../images/signs_vehicles_xygrad.png') # Choose a Sobel kernel size ksize = 3 # Choose a larger odd number to ...
''' @Description: 二分查找算法 @Date: 2019-07-29 16:07:55 @Author: Wong Symbol @LastEditors: Wong Symbol @LastEditTime: 2020-06-13 16:39:09 ''' # -*- coding:utf-8 -*- # ''' 二分查找算法: 基于有序数据集合的查找算法 底层必须依赖数据结构 对于较小规模的数据查找,推荐使用直接遍历的方式 比较适合处理静态数据(无频繁的数据插入、删除操作) 易错点: 1. 最外层 while 的循环退出条件;同时注意和各排序算法的临界条件的异同(如快...
from rest_framework import serializers, viewsets from .models import Event class EventSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Event fields = [ 'id', 'title', 'description', 'created', 'modified', ...
# Python Coroutines and Tasks. # Coroutines declared with async/await syntax is the preferred way of writing asyncio applications. # # To actually run a coroutine, asyncio provides three main mechanisms: # # > The asyncio.run() function to run the top-level entry point “main()” function. # > Awaiting on a corout...
""" Evaluation Script of Auto Encoder Model (ae.py) """ import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.optim as optim import torch.nn as nn from torch.utils.data import Dataset, DataLoader import matplotlib.pyplot as plt from model import AutoEncoder, CAE fr...
from django.apps import AppConfig as BaseAppConfig from django.utils.translation import ugettext_lazy as _ class AppConfig(BaseAppConfig): name = "pinax.badges" label = "pinax_badges" verbose_name = _("Pinax Badges")
import os from dotenv import load_dotenv load_dotenv() TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN") HGBRASIL = os.getenv("HGBRASIL") HOST = os.getenv("HOST") DATABASE = os.getenv("DATABASE") USER = os.getenv("USER") PASSWORD = os.getenv("PASSWORD")
activity_pattern = r'^activity/$'
import os def handle(form): import DPjudge try: DPjudge.Page(form) except SystemExit: pass except: import traceback print """ <H3>DPjudge Error</H3><p class=bodycopy> Please <a href=mailto:%s>e-mail the judgekeeper</a> and report how you got this error. Thank you. <!-- """ % DPjudge.host.judgek...
first_row = input().split(' ') second_row = input().split(' ') third_row = input().split(' ') if first_row[0] == second_row[0] and second_row[0] == third_row[0]: if first_row[0] == '1': print("First player won") elif first_row[0] == '2': print("Second player won") else: print('Draw!...
#!/usr/bin/env python import unittest from testphonenumber import PhoneNumberTest from testphonenumberutil import PhoneNumberUtilTest from testasyoutype import AsYouTypeFormatterTest from testexamplenumbers import ExampleNumbersTest from testphonenumbermatcher import PhoneNumberMatchTest, PhoneNumberMatcherTest if __...
#From Jupyter notebook #C1_Titanic T5.txt #1 import matplotlib.pyplot as plt import numpy as np import pandas as pd import warnings warnings.filterwarnings('ignore') f=open("E:/Tinky/大学课件及作业/6 自学课/6-3.Kaggle竞赛/C1_泰坦尼克号生还预测/泰坦尼克号数据/train.csv") data=pd.read_csv(f) #2 数据可视化 fig=plt.figure(figsize=(18,6)) alpha=alpha_sca...
#!/usr/bin/python import socket, subprocess,sys from datetime import datetime subprocess.call('clear',shell=True) rmip = raw_input("\t Enter the remote host IP to scan:") r1 = int(raw_input("\t Enter the start port number\t")) r2 = int (raw_input("\t Enter the last port number\t")) print "*"*40 print "\n Mohit's Scanne...
../../subrepos/colin-nolan/key_value_string_parser.py/key_value_string_parser.py
from simulator.core.pq import PriorityQueue from simulator.schedulers.scheduler import Scheduler class SRTF(Scheduler): """ Shortest Remaining Time First (SRTF) scheduler. Think of this as a Shortest Job First (SJF) but pre-emptive. """ def __init__(self): super(SRTF, self).__init__() ...
# -*- coding: utf-8 -*- # ------------- import sublime from RSBIDE.common.async import run_after_loading # from RSBIDE.common.notice import * ST3 = int(sublime.version()) > 3000 if ST3: basestring = (str, bytes) # if the helper panel is displayed, this is true # ! (TODO): use an event instead b_helper_panel_on =...
#!/usr/bin/env python3 with open('/proc/sys/vm/swappiness') as file: swappiness = file.readlines()[0][:-1] with open('/proc/sys/vm/min_free_kbytes') as file: min_free_kbytes = file.readlines()[0][:-1] with open('/proc/sys/vm/admin_reserve_kbytes') as file: admin_reserve_kbytes = file.readlines()[0][:-...
user_agents = ['Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0', 'Mozilla/5.0 (Windows NT 10.0; rv:60.0) Gecko/20100101 Firefox/60.0.2', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0', 'Mozilla/5.0 (Windows NT 10.0; WOW64...
#!/usr/bin/python from xlrd import open_workbook import constants import sys #Open excel book print 'opening Machine Learning Training Workbook...(this can take a while)' try: book = open_workbook(constants.training_workbook_name) except: print 'unable to find or open training workbook...' print 'progra...
""" author songjie """ import json from flask import Response class Reply(object): _result = None _code = None _msg = None _data_type = 1 def __init__(self, **kwargs): pass @property def result(self): return Reply._result @result.setter def result(self, value): ...
import os from itertools import chain from django.conf import settings from datetime import datetime from operator import attrgetter from urllib.parse import urlparse, urlunparse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.http import HttpResponseRedirect, QueryDict, JsonRe...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 06/02/2018 9:32 PM # @Author : Lee # @File : index_max_heap.py # @Software: PyCharm import random class IndexMaxHeap(object): """ 索引最大堆 """ def __init__(self, capacity): self.data = [-1] self.index = [-1] self.rev...
from flask import Blueprint, render_template, abort, session, request, jsonify, url_for, redirect from jinja2 import TemplateNotFound import requests import pprint import simplejson as json from collections import OrderedDict from datetime import datetime, date, timedelta import application.codechefAPI as helper from f...
from django import forms from .models import Profile,Photo,Comments from django.forms import ModelForm,Textarea,IntegerField class NewPhotoForm(forms.ModelForm): class Meta: model = Photo exclude = ['user','photos','likes'] class NewProfileForm(forms.ModelForm): class Meta: model = P...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-08 22:00:09 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ #闭包应用 #1.保存返回闭包时的状态 #2. def func(a,b): c = 10 def inner_func(): s = a+b+c print("加和为:",s ) return inner_func #调用 ...
import numpy as np import pandas as pd import random import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split import sys sys.path.insert(1, 'Trabalho 3/modules/') import models #Funções do Trabalho 2 def plot_confusion_matrix(y_true, y_pred, t...
# Author: Koorosh Gobal # Python code for 3.3 # ----------------------------------- import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from scipy.integrate import odeint # ----------------------------------- epsilon = 1.0 mu = 1.0 alpha = 1.0 k = 1.0 omega = 2.0 N = 99...
# -*- coding: utf-8 -*- """ Created on Wed Dec 2 17:45:52 2020 @author: Mitchell """ import requests as rq import datetime import json from datetime import timedelta, date import xlsxwriter import time #default data start_date = datetime.date.today() end_date = datetime.date.today() row = 0 col = 0 #commented coun...
# coding=utf-8 # Copyright 2018 The Dopamine Authors. # Modifications copyright 2019 Unity Technologies. # # 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...
#coding:utf-8 from django.shortcuts import render_to_response, get_object_or_404 from activity.dao import activityDao from django.template.context import RequestContext from collection.dao import collectionDao, select_collection_byReq,\ update_rightTime_byReq, update_wrongTime_byReq from django.http.response impor...
def bubblesort (list1): temp = 0 #this code is implemented for ascending sort for i in range(len(list1)-1,0,-1): for j in range (i): if list1[j] > list1[j+1]: temp = list1[j] list1[j] = list1[j+1] list1[j+1] = temp ...
# Learn Python The Hard Way # http://learnpythonthehardway.org/book/ # iTerm for terminal # iPython # Atom as IDE (integrated developent environment) / Text Editor # GitHub, keep remote cooy of your git repository # Exercise 1 print "Begin Exercise 1" + "\n" print "Hello World!" print "Hello Again" print "I like typ...
print ("Please enter your name!") user_name = input() print("Hello,", user_name)
from option import gather_options, print_options from network import Resnet, get_scheduler, init_net from dataload import loadData from Util import save_networks, load_networks, evaluate import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter import torchvision if __name__ == '__main__': ...
from encoding.base58_check import Base58CheckAddress """ You don't wanna know. """ class Ptr(Base58CheckAddress): VERSION_BYTE = bytes([117])