text
stringlengths
38
1.54M
from django.db import models from django.contrib.auth.models import User from datetime import datetime from localflavor.us.us_states import STATE_CHOICES from localflavor.us.models import USStateField class MoveType(models.Model): temporary= 'Temporary' permanent='Permanent' individual='Individual' family='Fam...
# Chocolatey package version checking and packing of package # Written by Hadrien Dussuel import os import subprocess import json import urllib.request import hashlib import zipfile import pathlib import shutil import functions as func # Routine de vérification et de paquetage automatique en fonction de la version co...
# 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 # distributed under t...
''' Created by auto_sdk on 2013-11-07 12:53:22 ''' from top.api.base import RestApi class TripJipiaoAgentItinerarySendRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.company_code = None self.express_code = None self.itinerary_id = None self.it...
from neteaseSpider.proxy.parsing_html import * from neteaseSpider.proxy.checking_ip import * def main(): ipPoolsPath = "ipProxy/ip_pools.txt" # 原始ip保存路径 ipFormatPoolsPath = "ipProxy/ipFormatPools.txt" # 格式化后ip保存路径 ipUsePath = "ipProxy/ipUse.txt" # 可用ip保存路径 open...
import FWCore.ParameterSet.Config as cms l1tRawToDigi = cms.EDProducer( "L1TRawToDigi", Setup = cms.string("stage2::CaloSetup"), InputLabel = cms.InputTag("l1tDigiToRaw"), FedIds = cms.vint32(1352), FWId = cms.uint32(1), FWOverride = cms.bool(False), TMTCheck = cms.bool(True), ...
import tkinter as tk import sqlite3 LARGE_FONT=("Verdana",12, "bold") conn = sqlite3.connect('users.db') conn.execute("CREATE TABLE IF NOT EXISTS pins(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, pin TEXT NOT NULL, balance INT NOT NULL)") #conn.row_factory = lambda cursor, row: row[0] #try: # conn.execute("CREATE ...
## note: cv2 works with python2. so type in terminal: alias python=python2 after launch from __future__ import division import cv2 import numpy as np from sklearn.metrics import accuracy_score from namespace import * def equiv(a, b): return ((a[0] == b[0]) and (a[1] == b[1]) and (a[2] == b[2])) def getTP(obj, com...
import sys import uinspect # init the ability to detect static method for main module uinspect.enable_static_method_detect(uinspect.main_module) class TestCase(object): def assert_equal(self, a, b): if a != b: raise TestError(str(a) + ' is not equal to ' + str(b)) class TestErr...
# -*- coding: utf-8 -*- # @Date : 2019-05-14 16:15:56 # @Author : QilongPan # @Email : 3102377627@qq.com import seaborn as sns import matplotlib.pyplot as plt sns.set() tips = sns.load_dataset("iris") print(tips.head())
from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import MeanSquaredError from algorithms.dane.models import AutoEncoder class PreTrainer(object): def __init__(self, config): self.config = config self.net_input_dim = config['net_input_dim'] self.att_input_dim = con...
from django.conf.urls import url from . import views # Url patterns for this app urlpatterns = []
import os.path import unittest import collections import json from .. import invitation from ..base32 import b2a from ..client import Client from .. import database from ..scripts.create_node import create_node from ..netstring import split_netstrings class Outbound(unittest.TestCase): def test_create(self): ...
import argparse import json import os from glob import glob from typing import Dict def load_correlations(input_dir: str, summarizer_type: str, level: str) -> Dict[str, Dict[str, float]]: correlations_dict = {} for input_file in glob(f'{input_dir}/*-{summarizer_type}.json'): name = os.path.basename(in...
import json import boto3 from boto3.dynamodb.conditions import Key, Attr """ JSON Format: "token" = "auth token ", "displayName" = "Steve Nash" """ def lambda_handler(event, context): output = {} dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('PickPocket') token = event['tok...
import torch import numpy as np from models.basecritic import AbstractCritic class DenseCritic(torch.nn.Module, AbstractCritic): def __init__(self, m, n, t, lr=0.001): """ max_input is the size of the maximum state size Let t be the max number of timesteps, maximum state/action si...
import socket from django.core.exceptions import ImproperlyConfigured hostname = socket.gethostname() if hostname == "arun-desktop": from settings_arun import * elif hostname == "Leoankit": from settings_ankit import * elif hostname == "anup-desktop": from settings_anup import * elif hostname == "Leonile...
__author__ = 'martin.majer' import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import h5py import cv2 root = '/storage/plzen1/home/mmajer/pr4/data/sun_full/SUN397' storage = '/storage/plzen1/home/mmajer/pr4/data/' filename = storage + 'sun_img_names.hdf5' def list_filepaths(root): ...
"""Необходимо вывести все числа кратные 4 между числами 40 и 60 включительно. Реализовать 2 варианта: использовать конструкцию if для определения кратности (цикл с шагом 1, i = i + 1); без использования конструкции if (шаг цикла на ваше усмотрение). """ for i in range(40, 61) : if i%4==0: print(i) for i in...
from contacts.Group import DGroup from common import pref from logging import getLogger; log = getLogger('blistsort'); info = log.info def grouping(): s = pref('buddylist.sortby', 'none none').startswith return s('*status') or s('*service') class SpecialGroup(DGroup): _renderer = 'DGroup' def groupk...
# coding:utf-8 # 经历了诸多实验,终于开始尝试写作基于用户工作满意度的主观分类器 # 其核心思想是基于提取的17维度的用户JS特征, # 1. 首先,假设全体用户中存在者许多满意度相近的用户,反映在特征空间中,即是相近的样本聚为一个类; # 2. 全部用户中,所有用户的工作满意度大致存在三种情况,根据正态分布,绝大多数用户的满意度在一个正常范围,少部分高于或者低于这个范围, # 而我们所关注的即低于这个范围的用户; # 为了找到这些用户,我们基于高于或等于正常范围的正常用户进行OCSVM训练,而这些用户通过聚类中心的JS分数高于中位数的群簇提供; # 3. 通过训练OCSVM的样本整体上位于所有用户中上部分,因而其判...
import scrapy from scrapy import Request import re from ..items import RaidforumsItem class Quotespider(scrapy.Spider): name = 'database_posts' # allowed_domains = ["https://raidforums.com"] start_urls = [ 'https://raidforums.com/Forum-Databases' ] base_url = 'https://raidforums.com/' ...
import numpy as np A = np.arange(12).reshape(3,4) print(A) #根据行进行分割 print(np.split(A,2,axis=1)) #根据行分成两组两个列 ''' [array([[0, 1], [4, 5], [8, 9]]), array([[ 2, 3], [ 6, 7], [10, 11]])] ''' #等效分割 print(np.split(A, 1, axis=0)) # 根据列分成两组两个列 ''' [array([[ 0, 1, 2, 3], ...
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: aCitiesDiff = [] bCitiesDiff = [] s = 0 aCount = 0 bCount = 0 for list in costs: if(list[0]<list[1]): s += list[0] aCount+=1 bCitiesD...
import FWCore.ParameterSet.Config as cms from Calibration.TkAlCaRecoProducers.AlcaSiStripLorentzAngleHarvester_cfi import * from DQMServices.Components.EDMtoMEConverter_cfi import * EDMtoMEConvertSiStripLorentzAngle = EDMtoMEConverter.clone( lumiInputTag = ("MEtoEDMConvertSiStripLorentzAngle","MEtoEDMConverterLum...
class ImportanceErrors(Exception): def __init__(self, data): self.message = { "error":{"valid_options":{ "importance":[1,2], "urgency":[1,2]}, }, "recieved_options":{ ...
""" This module serves as a web frontend to allow getting requested username from MySQL via db_connector from a browser (or by json request, too). made to make testing with selenium easier. """ from flask import Flask import db_connector as db app = Flask(__name__) @app.route('/users/get_user_data/<user_id>', meth...
from setuptools import setup setup( name='lenin', version='0.1', author=['brainopia', 'gazay'], packages=['lenin', 'lenin.augmentors', 'lenin.datasets', 'lenin.preloader'], install_requires=['torchbearer', 'scikit-learn'], )
import curses screen = curses.initscr() curses.noecho() curses.curs_set(0) screen.keypad(1) curses.mousemask(1) screen.addstr("This is a Sample Curses Script\n\n") while True: event = screen.getch() if event == ord("q"): break if event == curses.KEY_MOUSE: _, mx, my, _, _ = curses.getmouse() ...
# http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html import random #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] a = random.sample(range(120), k = 10) b = random.sample(range(101), k = 8) #common = set(a).intersection(set(b)) #clean version of the belo...
from collections import Counter from numpy import * with open('hw12Data/digitsDataset/trainFeatures.csv') as f: inp = f.readlines() trainFeatures = [] for line in inp: trainFeatures.append(array([float(x) for x in line.split(',')])) with open('hw12Data/digitsDataset/trainLabels.csv') as f: inp = f.readlines() trai...
import pytest def solution_on2(n, arr): counters = [] for i in range(n): counters.append(0) max_ele = float('-inf') for ele in arr: if ele > n: for i in range(n): counters[i] = max_ele else: counters[ele - 1] += 1 if counters...
class Anima: def __init__(self, animaTitle): self.animaTitle = animaTitle self.season = 1 self.episode = 12 self.currentlyOnEpisode = 1 # getter method for anima title def get_anima_title(self): return self.animaTitle # setter method for anima title def set_...
from testPipe import * from pyspark.ml import Pipeline from pyspark.ml.classification import * from pyspark.ml.feature import * def getSpark(): return SparkSession.builder.getOrCreate() spark = getSpark() index = 8 lr = LogisticRegression(regParam=0.1, maxIter=20) pipeline = Pipeline(stages=[lr]) description = ...
import time def warn_slow(func): def inner(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() duration = end - start if duration > 2: print(f"execution of {func.__name__} with {(*args, *kwargs.values())} arguments took more th...
#!/usr/bin/env python3 import argparse import collections import itertools import math import sys def take(c, iterable): out = [] for x in iterable: out.append(x) if len(out) == c: return out return out def skip(c, iterable): iterable = iter(iterable) for x in iterable: if c > 0: c ...
#!/usr/bin/env python from socket import * import pickle class remoteXclient: def __init__(self): self.cmdstring_list = [] #self.socketup() #if not self.serverup: # print "RemoteX Client: server not found. Please start the server on your local machine." #self.socketdown...
import sys sys.stdin = open("D3_5108_input.txt", "r") T = int(input()) for test_case in range(T): N, M, L = map(int, input().split()) data = list(map(int, input().split())) for _ in range(M): idx, val = map(int, input().split()) data.insert(idx, val) print("#{} {}".format(test_case + 1,...
''' Created on Oct 24, 2016 @author: Noor Jahan Mukammel Program: set_method: issuperset() * x.issuperset(y) returns True, if * x is a superset of y. * ">=" is an abbreviation for "issuperset of" * ">" is used to check if a set is a proper superset of a set. ''' x = {"a","b","c","d","e"} y = {"c","...
import sys """The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?""" def isprime(x): for i in range(x - 1, 2, -1): if x % i == 0: return False return True def isfactor(num, factor): return num % factor == 0 def main(): x...
import math p=1009 q=3643 n = p * q φ = (p-1)*(q-1) tmp_list = [] tmp = 0 dic = {} for e in range(2, φ): if (math.gcd(e, φ) == 1): tmp_list.append(e) dic[e] = (math.gcd(e-1, p-1)+1) * (math.gcd(e-1, q-1)+1) for e in tmp_list: if dic[e] == 9 : tmp = tmp + e print(tmp)
# Escribir un programa que almacene las asignaturas de un curso # (por ejemplo Matemáticas, Física, Química, Historia y Lengua) # en una lista, pregunte al usuario la nota que ha sacado # en cada asignatura, y después las muestre por pantalla # con el mensaje En <asignatura> has sacado <nota> # donde <asignatura...
__author__ = 'juliewe' if __name__=='__main__': filename='/Volumes/LocalScratchHD/juliewe/Documents/workspace/Compounds/data/WNCompounds/teststuff/oneline' instream = open(filename) lines=[] for line in instream: lines.append(line.rstrip()) fields=lines[0].split('\t') print len(fields...
# Copyright 2016 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 by applicable law or ...
import pandas as pd data = open("CityTemps.csv") for row in data: print(row.split(",")) """ table = pd.read_csv("CityTemps.csv") print(table) print("Fetching only years") print(table["Year"]) print("----iloc----") print(table.iloc[1:5]) """
#!/usr/bin/python swiss_websites = [] f = open('input_ex5.txt','r') for line in f: line = line.strip() if line[-3:] == '.ch': swiss_websites.append(line) f.close() print(swiss_websites)
import xml.dom.minidom # 创建文档 doc = xml.dom.minidom.Document() # 创建节点(属性):文本 root_node = doc.createElement('books') name_attr = doc.createAttribute('name') name_attr.value = '马帅哥' # .... txt_node = doc.createTextNode('数据') # 把属性加入根节点 root_node.setAttributeNode(name_attr) # 把文本加入节点 root_node.appendChild(txt_node) # 把...
class SAMPLESCAN(): def scan(self, axis, start, end, step, exposure): print("Sample scan for eiger") ## variables sensor = [] motor = [] prescan_pos = 0 DEBUG=0 ## Eiger channels Eiger_acquire = create_channel_device("PINK:EIGER:cam1:Acquire", type='...
#!/usr/bin/python3 import minimalmodbus import serial import time class HM310P(): rDepth = 100 def __init__(self): self.supply = minimalmodbus.Instrument('/dev/dcpowersupply', 1, minimalmodbus.MODE_RTU) self.supply.serial.baudrate = 9600 self.supply.serial.startbits = 1 self.s...
import AVFoundation from PyObjCTools.TestSupport import TestCase, min_os_level class TestAVCaption(TestCase): def test_enum_types(self): self.assertIsEnumType(AVFoundation.AVCaptionAnimation) self.assertIsEnumType(AVFoundation.AVCaptionDecoration) self.assertIsEnumType(AVFoundation.AVCapti...
from django.contrib.auth.models import User from django.db import models from datetime import datetime class TipoMaterial(models.Model): nombre=models.CharField(max_length=100,blank=True,default=" ") status=models.BooleanField(default=True) def __str__(self): return '{}'.format(self.nombre) clas...
# // leetcode 351 # //Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys. # //| 1 | 2 | 3 | # //| 4 | 5 | 6 | # //| 7 | 8 | 9 | # //Invalid move: 4 - 1 - 3 - 6 # /...
# Copyright 2015-2016 Yelp Inc. # # 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 writin...
def aprovacao(n): return 'aprovado' if n >= 7 else 'reprovado' if __name__ == '__main__': print(aprovacao(10)) print(aprovacao(8)) print(aprovacao(6)) print(aprovacao(0)) print(aprovacao(7))
# code_report Solution # https://youtu.be/CvJz_RgTYgU n = int (input ()) for i in range (n): x = int (input ()) print (-1 if x % 5 != 0 else (0 if x % 2 == 0 else 1))
from django.contrib.auth.models import User from django.db import models class FHSUser(models.Model): user = models.OneToOneField(User, primary_key=True) is_married = models.BooleanField(default=False) num_kids = models.IntegerField(default=0) num_ticket = models.IntegerField(default=0) profession ...
import datetime from pymongo import MongoClient cl = MongoClient() db_bank = cl['banking'] db_bank['Calvin'].insert_one({"kid": "Calvin", "type": "deposit", "amount": 6.00, "description": "School and house work", "date": str(datetime.date.today())}) db_bank['Samuel'].insert_one({"kid": "Samuel", "type": "deposit", "...
# -*- coding: utf-8 -*- """ Tests for dnsimple updater. Since we rely on an external library implementing the actual interfacing with the remote service, the tests in here merely check the behavior of the Dyndnsc wrapper class. """ import unittest try: import unittest.mock as mock except ImportError: import m...
import logging from datetime import datetime as dt from io import StringIO import time import pandas as pd import psycopg2.extras import pytz from tzlocal import get_localzone from tagbase_server.utils.db_utils import connect from tagbase_server.utils.io_utils import compute_file_sha256, make_hash_sha256 from tagbase...
import os from selenium import webdriver #chromeDriPath=os.path.abspath(r'E:\Python3\Ptthon3.6Install\Scripts\chromedriver.exe') driver=webdriver.Chrome() driver.get("http://www.baidu.com") print(driver.title) driver.close()
Enoncé Dans ce challenge, on utilise un format de données qui est une version simplifiée du XML. Les noms des balises ne sont composés que d'une lettre minuscule, une balise ouvrante étant représentée par cette lettre seule et la balise fermante étant représentée par le caractère -, suivi de la lettre. Par exemple, la...
from ..core import my_player class Knight(object): def skillset(self): player_level = my_player.get_level() player_hp = my_player.get_health() if player_level < 3: skills_dict = { "1. Slash: " : player_hp * 1/6, "2. Heavy Strike: " : player_hp * 1/5 } return skills_dict elif player_...
#looking at profile curves import numpy as np import scipy as sc import matplotlib.pyplot as plt #Switch these out for the appropriate files directory = '/Users/carmenlee/Desktop/13082020_pip1_1/' profile = np.genfromtxt(directory +'profile.csv') horizontal = np.genfromtxt(directory +'horizontal.csv') frame = np.ge...
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer import scattertext as st import time import scattertext.categoryprojector.pairplot t0 = time.time() newsgroups_train = fetch_20newsgroups(subset='train', remove=('headers', 'footers', 'quotes'...
import pandas as pd from pandas_datareader import data as pdr import pymysql, calendar, time, json from datetime import datetime from threading import Timer import pymysql import sys import yfinance class DBUpdater: def __init__(self): self.conn = pymysql.connect(host='localhost', user='hong', password='ho...
import os import discord from discord.ext import commands class SelfRole(commands.Cog): """ This class does the following given a message ID on the server: - For every reaction on the message, it assign a role to the users who have reacted to the message. - A mapping of emojis <-> Role can be ...
import turtle def up(): turtle.goto(turtle.xcor(),turtle.ycor()+50) def down(): turtle.goto(turtle.xcor(),turtle.ycor()-50) def left(): turtle.goto(turtle.xcor()-50,turtle.ycor()) def right(): turtle.goto(turtle.xcor()+50,turtle.ycor()) turtle.onkeypress(up,"w") turtle.onkeypress(down, "s") turtle.onkey...
import os os.system('mcrl22lps -nfTv ball_game.mcrl2 ball_game.lps') os.system('lpsuntime -v ball_game.lps ball_gameu.lps') os.system('lpsrealelm --max=11 -v ball_gameu.lps ball_gamer.lps') os.system('lps2lts -v ball_gamer.lps ball_game.lts')
from MaximumDecisionTree import MaximumDecisionTree import random import numpy as np class RandomForest: def __init__(self, n_estimator=5, maximum_samples=100, max_depth = 2, sampling_type='bagging'): self.n_estimator = n_estimator self.sampling_type = sampling_type self.maximum_sample = m...
n = 10 r_shift = n >> 1 print(r_shift) l_shift = n << 1 print(l_shift) k = 3 if 7 & (1 << k-1): print("set")
class MyString(): def __init__(self, str=""): # initializes the object self.str=str #Returns the current string. def getString(self): return self.str #Returns a string that consists of all and only the vowels in the current string. #Only letters a, e, i, o, and u (both lower and ...
import pygame, sys from random import randint from pygame.sprite import Sprite #Game parameters screen_width = 800 screen_height = 800 black = (0,0,0) white = (255, 255, 255) red = (255,0,0) score = 0 button_down = False #Initializing game pygame.init() screen = pygame.display.set_mode((screen_width, screen_height)) ...
import pyexcel import json with open('./courses.json') as json_data: data = json.load(json_data) pyexcel.save_as(records=data, dest_file_name="akashi.xls")
# - *- coding: utf- 8 - *- from aiogram import types from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.mail import send_mail from django.conf import settings from django.core.urlresolvers import reverse from contact.forms import * def contact(request): if request.method == 'POST': # If the form has been submitted... ...
from schema import * from flask import Flask, render_template, request, jsonify, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, login_user, logout_user, current_user, login_required, UserMixin from werkzeug.urls import url_parse from werkzeug.security impo...
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: repeat_dict = {} comparisons = [] if arr == [] or len(arr) == 1: return True for val in arr: if val not in repeat_dict: repeat_dict[val] = 1 ...
import cv2 import numpy as np import matplotlib.pyplot as plt import skimage.io as io import skimage.transform as transform import bound as bo def main(): foreground=bo.get_foreground() masknew=foreground.copy() masknew[masknew>0]=1 background=io.imread('/home/jayasurya/Desktop/storerack.jpg')/255.0 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import base64 from json import JSONDecoder import simplejson import requests import time key = "your key" secret = "your secret" url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' url_add = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface" def find_face(imgpa...
from __future__ import print_function from tensorflow.python.keras.models import load_model import tensorflow as tf import numpy as np from PIL import Image MODEL_NAME = 'cat10086.hd5' #MODEL_NAME = 'cattrain3.hd5' dict={0:'Backward', 1:'Forward', 2:'Left', 3:'Right',4:'Stop'} graph = tf.get_default_graph() def cl...
x < y x > y x == y x >= y x <= y x != y # Compare if two variables point to the same object x is y x is not y # Determine if a value is in a collection x in collection x not in collection
"""http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/""" import fileinput inputLines = fileinput.input() #I didn't manage to solve this one. I looked it up after staring for about an hour. #Also its currently n^2 and doesn't pass so I'm shelving this one for a day when I've slept. #Tu...
""" 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-common-prefix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution(object): ...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: libdzyl # # Created: 26-05-2014 # Copyright: (c) libdzyl 2014 # Licence: <your licence> #------------------------------------------------------------------------------- import ma...
# Defino mi funcion def sumar (num1, num2): return( num1 + num2 )# Retorno el resultado #region Main operacion = sumar(4, 5) # A la variable operacion, le voy asignar el resultado de la funcion suma(num1, num2) print(f"El resultado es: {operacion}") # Puedo llamar a la funcion, las veces que sea n...
from django.db import models # TODO: product's price is separated by packing class Produk(models.Model): """docstring for Product.""" nama = models.CharField(max_length=100) modal = models.IntegerField(default=0) harga = models.IntegerField(default=0) berat = models.IntegerField(default=0) stok...
import tensorflow as tf import numpy as np from PIL import Image import scipy.misc import utils import model import segmentizer import net #test_path = 'learning/00001.jpg' #test_path = 'learning2/57.jpg' #test_path = 'input.jpg' #learning_list = utils.get_files('resized_img/learning') learning_list = utils.get_files(...
class Record: def init(self, n, s): Record.name = n Record.score = s p = Record() q = Record() p.init('123', 20) q.init('456', 30) print(p.name, p.score)
password=input("Enter a password: ") capital_letter=0 lower_letter=0 digit_number=0 special_character=0 for c in password: if c.isupper(): capital_letter=capital_letter+1 elif c.islower(): lower_letter=lower_letter+1 elif c.isdigit(): digit_number=digit_number+1 else: sp...
MEDIA_LINKS = [("https://www.facebook.com/sharer.php?u=http://andrewbberger.com", "fa fa-facebook-official" ), ("https://www.twitter.com/share?url=http://andrewbberger.com", "fa fa-twitter-square" ), ("https://www.linkedin.com/shareArticle?mini=true&amp;url=http://andrewbberger.com", "fa f...
import random res = random.sample(range(1, 500),10) res.sort() print ("Random number list is : " + str(res))
#!/usr/bin/env python """This script extracts the partition global tags dependency trees from the CondDB Release Notes. This script is intended to be used with a cgi interface to extract possible global tags dependency tries from a release_notes.xml file of a Det/SQLDDDB package. At a web page form the user have to sp...
"""Create yhbatch jobs in GuangZhou TianHe2 computer cluster. """ import os import stat import argparse from datetime import datetime if __name__ == "__main__": cmdparser = argparse.ArgumentParser(description="yhbatch jobs") cmdparser.add_argument("-I", "--input", dest="input", required=True, ...
import os from time import localtime, strftime from flask import Flask, request, render_template, jsonify, redirect, url_for, flash, send_from_directory from flask_login import LoginManager, login_user, current_user, logout_user, login_required from flask_socketio import SocketIO, send, emit, join_room, leave_room, c...
from django.db import models # Create your models here. class Employee_Category(models.Model): name = models.CharField(max_length=255) abbr = models.CharField(max_length=5) cost = models.DecimalField(max_digits=7, decimal_places=2) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = model...
import numpy as np import pandas as pd import glob import os import numpy as np import sys import masstitr_tools as mt from Bio import Seq # %% # ============================================================== # // parameters # ============================================================== # count cutoff threshold FIL...
""" Refer to handout for details. - Build scripts to train your model - Submit your code to Autolab """ import torch import torch.nn as nn import torch.utils.data as data_utils import torch.nn.functional as F import numpy as np import hw2.all_cnn import hw2.preprocessing def write_results(predictions, output_file='pr...
from django.urls import path from django.conf.urls import url from apps.user.views import RegisterView, ActiveView, LoginView app_name = 'apps.user' urlpatterns = [ url(r'^register/$', RegisterView.as_view(), name='register'), # 注册页面 url(r'^active/(?P<token>.*)$', ActiveView.as_view(), name='active'), ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.IoTBPaaSMerchantOrderInfo import IoTBPaaSMerchantOrderInfo class AlipayOpenIotbpaasMerchantorderRefreshResponse(AlipayResponse): def __init__(self): supe...
class Person: self.messages = [] def __init__(self, name): self.name = name def addMessage(self, message): self.messages.append(message)