text
stringlengths
38
1.54M
from django.shortcuts import redirect from django.urls import reverse class UpdateProfileMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = request.user if not user.is_anonymous: profile = user.profile ...
from model import * epochs = 2 batch_size = 128 history = model.fit(x_train, y_train, epochs=1, batch_size= batch_size,validation_split=0.1) model.save('AttentionX.h5')
# -*- coding:utf-8 -*- import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torchvision.transforms.functional import normalize import os from .resnet_market1501 import resnet50 import sys # ReID Loss class ReIDLoss(nn.Module): def __init__(self, model_path,...
from graphics import * ## creates a polygon ## list of points = points=[point( ), point( )] ## witch = Polygon(points) ## accumulation and know pattern and loop and get list bigger ##nums = [] is a list ## for i ranget(4) ## val=eval(input("num? ")) ## nums.append(val)? ## points[]= empty list ## for i in ra...
import cv2 import numpy as np import matplotlib.pyplot as plt url1='/home/subhankar/subhankar_110118084.jpeg' url='/home/subhankar/plane.jpeg' image=cv2.imread(url,cv2.IMREAD_GRAYSCALE) #plt.imshow(image) #plt.show() image_BGR=cv2.imread(url,cv2.IMREAD_COLOR) image_RGB=cv2.cvtColor(image_BGR,cv2.COLOR_BGR2RGB) #Resiz...
import sys #from pathlib import Path import lib.Assets as Assets import lib.Character as Character import lib.PurchaseClones as PurchaseClones import lib.Challenge as Challenge # Purchase a clone using Ovid's SVO clone = PurchaseClones.PurchaseClones objs_returned = clone().purchase_clone(5) # usin...
from google.appengine.api import users from google.appengine.ext import db from models.city import City from models.company import Company from models.show import Show from models.venue import Venue from models.performance import Performance import unittest, datetime, random from resources.webtest import TestApp from h...
## Ch04 SC25 RATE = 5.0 INITIAL_BALANCE = 10000.0 numYears = int(input("Enter number of years: ")) balance = INITIAL_BALANCE year = 1 while year <= numYears: interest = balance * RATE / 100 balance = balance + interest print("%4d %10.2f" % (year, balance)) year += 1
from typing import TYPE_CHECKING, Optional from PyQt5.QtWidgets import QLabel, QVBoxLayout, QGridLayout, QPushButton, QComboBox, QLineEdit, QSpacerItem, QWidget, QHBoxLayout from electrum.i18n import _ from electrum.transaction import PartialTxOutput, PartialTransaction from electrum.lnutil import MIN_FUNDING_SAT fro...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'suivitvictimesinistre.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _...
## ## Visualize samples produced by MISO. ## ## TODO: In future interface with spliceplot to produce densities along a gene model ## from scipy import * from numpy import * import matplotlib #from plotting import colors, show_spines, axes_square import matplotlib.pyplot as plt from matplotlib import rc #rc('font',**...
from wagtail.admin.edit_handlers import PublishingPanel, PrivacyModalPanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.widgets import AdminImageChooser class CustomImageChooserPanel(ImageChooserPanel): def widget_overrides(self): return {self.field_name: AdminImageChoose...
from tkinter import * a=Tk() a.title("my first window") a.geometry("500x500+0+0") l1=Label(text='Label1',fg='red',bg='green',font='25').pack() button2=Button(text='submit',fg='black',bg='white',font='38').pack() l2=Label(text='label2',fg='blue',bg='yellow',font='48').pack() button1=Button(text='submit',fg='blue',bg='re...
#import modules from time import sleep from ina219 import INA219 import time t=0 #Cycle for to take measures while True: #Sensor and I2C configuration ina1 = INA219(shunt_ohms=0.1, max_expected_amps = 2.0, address=0x40) ina2 = INA219(shunt_ohms=0.1, max_e...
# Generated by Django 3.1.5 on 2021-01-14 19:47 from django.db import migrations import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('matching', '0004_matching_skills'), ] operations = [ migrations.AddField( model_name='matching', ...
# -*- conding:utf-8 -*- import requests url = "http://192.168.2.237:8118/gs_mall_channel_mk_admin/admin/channelCustomCategory/insertCategory" querystring = {"channelId":"125"} payload = "{\r\n\"channelId\":\"135\",\r\n "\ "\"name\":\"test2\",\r\n " \ "\"channelName\":\"ceshi\",\r\n " \ "\"...
from mock import patch, Mock from tornado import testing, concurrent from zoonado.protocol.acl import ACL from zoonado import client, protocol, exc, WatchEvent class ClientTests(testing.AsyncTestCase): def future_value(self, value): f = concurrent.Future() f.set_result(value) return f ...
# coding:UTF-8 """ 简易http服务器封装模块 @author: yubang """ from werkzeug.serving import run_simple class HttpServer(object): def start_server(self, wsgi_app, host='127.0.0.1', port=8080, debug=True, use_reload=True): """ 启动一个简易的服务器 :param wsgi_app: wsgi接口函数 :param host: 监听的域名 ...
from urllib.request import urlopen from inscriptis import get_text from bs4 import BeautifulSoup from flask import Flask, request from flask_restful import Resource, Api, reqparse # from .storage import models app = Flask(__name__) api = Api(app) class Storage(Resource): # get request for poending def get...
# 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。 # 示例 1: # 输入: # [ #   [1,1,1], #   [1,0,1], #   [1,1,1] # ] # 输出: # [ #   [1,0,1], #   [0,0,0], #   [1,0,1] # ] class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead....
import time, argparse from src.celery_lambda.CeleryLambda import CeleryLambda parser = argparse.ArgumentParser() parser.add_argument('lambda_name', type=str, help="The name of Lambda function") parser.add_argument('-c', '--celery_async', action="store_true", help="turn on to ma...
import coverage import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from project import app, db app.config.from_object(os.environ['APP_MODE']) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def co...
""" This part of code is adopted from https://github.com/Hanjun-Dai/graph_adversarial_attack (Copyright (c) 2018 Dai, Hanjun and Li, Hui and Tian, Tian and Huang, Xin and Wang, Lin and Zhu, Jun and Song, Le) but modified to be integrated into the repository. """ import os import sys import numpy as np import t...
#Embedded file name: traceback2\__init__.py from brennivin.traceback2 import * from traceback import format_exception_only
import requests google = requests.get('http://google.com') print(google.status_code) print(google.content[:200]) print(google.headers) print(google.cookies.items())
from django.contrib import admin from bonds.models import Bond, User @admin.register(Bond, User) class BondAdmin(admin.ModelAdmin): pass
# Master File # # A simulation of Warbling Babbler movement with different phenotypes between several populations # in different landscapes aver the course of several weeks. This uses a randomized dispersal matrix # to determine a rate of migration between populations. # # # !! Only Functional with Two Populations !!...
#!/usr/bin/python #ubuntu 11.10 #*apt-get install mysql-server #*apt-get install python-mysqldb #more information:http://mysql-python.sourceforge.net/MySQLdb.html import MySQLdb ###connect to databases conn = MySQLdb.connect(host='localhost', user='root', passwd='12345678') ###create database cursor = conn.cursor() ...
import operator import sys import ctypes import time import pyautogui import pyjokes import pyttsx3 import pywhatkit import speech_recognition as sr import requests import os import datetime import cv2 from pywikihow import search_wikihow from requests import get import wikipedia import smtplib import geocoder from geo...
from django.db import models from django.core.validators import EmailValidator from django.utils import timezone from django.core.validators import RegexValidator # Create your models here. class Proveedor(models.Model): class Meta: ordering = ['nombre'] nombre = models.CharField(max_length=100, null=...
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets import pyqtgraph.opengl as gl import pyqtgraph as pg import numpy as np import sys # -*- coding: utf-8 -*- import os import PyQt5 import sys from PyQt5 import QtGui, QtWidgets, QtCore import math import sys def get_rot_mat(_axis, _angle_rad): if _axis == 'x': ...
class Move: # def nowInfo(self,infoCount,infoList): # if infoCount<0: # print("조회 중인 고객 정보가 없습니다..") # return 0 # else: # return 1 # def nextInfo(self,infoCount,infoList): # if len(infoList) == infoCount+1: # print("다음 고객 정보가 없습니다.") ...
def solution(s): answer = True tmp = [] for i in s: if i is "(": tmp.append(i) elif len(tmp) is not 0: tmp.pop() else: answer = False if len(tmp) is not 0: answer = False return answer s=["()()","(())()",")()(","(()("] f...
from django.conf import settings from django.db.models import Q from django.http import Http404 from django.shortcuts import redirect, get_object_or_404, render from authn.decorators.auth import require_auth from authn.helpers import check_user_permissions from badges.models import UserBadge from comments.models impor...
# Generated by Django 3.0.2 on 2020-01-28 23:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', '0007_category'), ] operations = [ migrations.AlterModelOptions( name='category', options={'verbose_name': ...
import sys,datetime,os from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox, QTableWidgetItem from PyQt5 import uic from form_cuotas_vencidas_30dias import Ui_form_cuotas_vencidas_30dias from N_cliente import N_datos_personales_cliente, N_party_address, N_party_otros, N_datos_laborales, N_party_garante,N_party_...
from numpy import array, zeros, shape, sqrt, ceil def pixelise(image, pixel_width): image_shape = shape(image) pixelisation_shape = pixelised_shape(image_shape, pixel_width) # print(pixelisation_shape) pixelised_image = zeros(pixelisation_shape) for i in range(pixelisation_shape[0]): imag...
from pydantic import BaseModel, Field, EmailStr class UserLoginSchema(BaseModel): email: EmailStr = Field(...) password: str = Field(...) class Config: schema_extra = { 'exemplo': { 'email': 'teste@teste.com', 'password': 'umasenha' } ...
from vpython import * #sphere() ball = sphere(pos=vector(-5, 0, 0), radius=0.5, color=color.yellow, make_trail=True) wallR = box(pos=vector(6, 0, 0), size=vector(0.2, 12, 12), color=color.purple) wallL = box(pos=vector(-6, 0, 0), size=vector(0.2, 12, 12), color=color.purple) wallT = box(pos=vector(0, 6, 0), size=v...
from api.models import Wallet from ariadne import convert_kwargs_to_snake_case def fetch_wallets(obj, info): try: wallets = [wallet.to_dict() for wallet in Wallet.query.all()] payload = { "success": True, "wallets": wallets } except Exception as error: ...
from djangobench.utils import run_benchmark def setup(): global Book from model_save_new.models import Book def benchmark(): global Book for i in range(0, 30): b = Book(id=i, title='Foo') b.save() run_benchmark( benchmark, setup=setup, meta={ 'description': 'A sim...
## class for handling scripts # class Script(object): ## constructor def __init__(self, nom_script, tool_script, chemin_fichier): super(Script,self).__init__() # script name self.intitule = nom_script # tool self.tool = tool_script # script path self.pat...
# add imports import unittest import sysconfig as sys # Class to contain all the Unit Test for Python class TddWithPython(unittest.TestCase): def test_python_env(self): self.assertEquals('posix', sys.os.name) #this line is required for running the python code if __name__ == '__main__': un...
from math import sqrt a = float(input('Proszę wprowadzić współczynik a: ')) b = float(input('Proszę wprowadzić współczynik b: ')) c = float(input('Proszę wprowadzić współczynik c: ')) if a!=0: delta = b**2-(4*a*c) if delta>0: x1 = (-1*b-sqrt(delta))/(2*a) x2 = (-1*b+sqrt(delta))/(2*a) ...
from projectq import MainEngine from projectq.ops import * from projectq.meta import Dagger import numpy as np BaseX = [H] BaseY = [H, S] BaseZ = [] """ ProjectQ library build for the experiment data analysis """ def io_circuit(eng, input_gate, output_gate): ''' measure circuit1 on given output_gate, ...
from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4 import uic from GA144_fonctions_py2 import * import sys UiMaFenetre, Klass = uic.loadUiType('ArrayForthWindow.ui') class MaFenetre(QMainWindow, UiMaFenetre): def __init__(self, conteneur=None): if conteneur is None : conteneu...
from django.contrib import admin from .models import Income,spending # Register your models here. admin.site.register(Income) admin.site.register(spending)
def get_common_elements(seq1,seq2,seq3): common = set(seq1) & set(seq2) & set(seq3) return tuple(common) print(get_common_elements("abcd",['a','b', 'd'],('b','c', 'd'))) # , {"a","b","c","d", "e"} def get_common_elements_multi(*multy_arg): if len(multy_arg) == 0: return () my_set = set(mult...
from nltk.stem.snowball import SnowballStemmer import string import nltk from nltk.corpus import stopwords PUNCTUATION = string.punctuation SNOWBALLSTEMMER = SnowballStemmer("english") try: STOPWORDS = stopwords.words("english") except: nltk.download("stopwords") STOPWORDS = stopwords.words("english") RAT...
#!/usr/bin/env python3 import os import sys import query_db if __name__ == '__main__': if len(sys.argv) != 3: print("Usage: load_db_tool.py [-D, -d, -a, -l] [filename]") print("-D: Destination File\n -d: Dining File\n -a: Attractions File\n -l: Lodging File") else: fileTy...
import csv import UDLevel import copy import Game_elements def convertBoardToInstances(a, dimension): (rows, cols) = (len(a), len(a[0])) for row in range(rows): for col in range(cols): key = a[row][col] if key == "_": a[row][col] = Game_elements.Floor((row, col)...
""" File that contains all the non-visible routes that are used for communicating with the app. This particular file contains routines that are used for vault specific tasks. """ #External dependency imports import tempfile,os from werkzeug import Headers #Flask imports from flask import request, redirect, url_for, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PyQt5 import QtNetwork from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest from PyQt5.QtCore import QCoreApplication, QUrl, QByteArray import sys class Example: def __init__(self): self.doRequest() def doRequest(self): mobi...
from collections import Counter class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ processed_candidates = sorted(Counter(candidates).items()) rv = [] de...
""" OOrtiz N2O Thermodynamic Data Gathering v:0.0 """ from CoolProp.CoolProp import PropsSI import CoolProp.CoolProp as CP from scipy import * class N20ThermoCompile(): def __init__(self, TrangeMin, TrangeMax, Tincrement, PrangeMin, PrangeMax, Pincrement): self.TrangeMin = TrangeMin ...
import numpy as np def is_in_range(x, limit): return (x >= 0 and x < limit) def is_not_visited(visited_sites, i, j): return not visited_sites[i][j] def is_correct_height(grid, i, j, height): return grid[i][j]==height def is_valid_to_visit(grid, i, j, height, visited_sites, row, col): return (is_...
#Embedded file name: ACEStream\Core\TS\Service.pyo import sys import time import hashlib import random from base64 import b64encode, b64decode import urllib import os import binascii from urllib2 import HTTPError, URLError from traceback import print_exc from xml.dom.minidom import parseString, Document from xml.dom im...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Tiago de Freitas Pereira <tiago.pereira@idiap.ch> """Executes only the train part of a biometric pipeline""" import logging import click from clapper.click import ConfigCommand, ResourceOption, verbosity_option from bob.pipelines.distributed import VALID_DAS...
import numpy as np import matplotlib.pyplot as plt import datetime import cal_obs import jdutil dm_folder = '/data1/Daniele/B2217+47/Analysis/DM/' def DM_evolution(): #Plot DM evolution with archival data core = np.load(dm_folder+'CORE_DM.npy') inter = np.load(dm_folder+'dm_INTER.npy') GMRT = np.load(dm_fold...
import cv2 import numpy as np im = cv2.imread(r'D:\Users\yl_gong\Desktop\abc.jpg') im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) thresh,im = cv2.threshold(im, 100, 255, cv2.THRESH_BINARY) im2, contours, hierarchy = cv2.findContours(im, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) for contour in contours: if cv2.contourA...
from saltjob.salt_http_api import SaltAPI from devops.settings import SALT_REST_URL from saltjob.get_api_token import get_token def transfer_script(tgt,script_dir,script_name): data = { "tgt": tgt, "fun": "cp.get_file", "arg": [ "salt://scripts/{}".format(script_name), ...
from __future__ import division import numpy as np import matplotlib.pyplot as plt from circle_finder import circle_finder CMB_DIST = 14000 CELL_SIZE = 320 ang_rad = np.arange((1/360)*2*np.pi, np.pi/2, (2*np.pi)/(360)) data = np.genfromtxt('/opt/local/l4astro/rbbg94/data/ngp_corr.csv', dtype = complex, delimiter = ',...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('players', '0004_auto_20160602_1959'), ] operations = [ migrations.CreateModel( name='PlayerTypeDetails', ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys def _add_tpu_models_to_path(): dir = os.path.dirname(os.path.realpath(__file__)) tpu_models_dir = os.path.abspath(os.path.join(dir, '..', 'tpu', 'models')) if tpu_models_dir n...
from PIL import Image, ImageEnhance, ImageFilter import cv2 import numpy as np import pytesseract #reading and converting imgae to gray gray= cv2.imread('noisyNumbers.png',cv2.IMREAD_GRAYSCALE) gray = cv2.threshold(gray, 150,150, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] cv2.imshow('Final', gray) cv2....
# coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt #get_ipython().run_line_magic('matplotlib', 'inline') #import mpld3 #mpld3.enable_notebook() # In[ ]: data=pd.read_csv("dataset_1.csv") #reading data # data.head() # In[3]: # x=data['X'] # y=data['Y'] # plt.scat...
class JsonException(Exception): GROUP = None ID = None def __dict__(self): return { 'error': True, 'name': self.__class__.__name__, 'message': self.message, 'group': self.__class__.GROUP, 'id': self.__class__.ID } class UserFrie...
""" The MIT License (MIT) @author: Stephen J. Maher """ import sys import os.path import instancegen as ig if __name__ == "__main__": # printing the help message if (len(sys.argv) == 2 and sys.argv[1] == "--help")\ or len(sys.argv) < 4 or len(sys.argv) == 1: print("Usage: %s instance-class instan...
#! /usr/bin/env python ######################################################################## # # # Resums the non-global logarithms, needs ngl_resum.py # # # # If...
# -*- coding: utf-8 -*- import scrapy from abcrawler import models from abcrawler.items import QuoteItem import datetime class QuotesSpider(scrapy.Spider): name = "quotes" url = input("please enter a valid url : ") # url = 'http://quotes.toscrape.com/page/1/' start_urls = [ url, ] ...
from toontools import Toon import sys import argparse import logging def setlogging(args): if args.DEBUG: print("Set Logging to DEBUG") logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] %(message)s',) else: logging.basicConfig(level=logging.INFO, format='%(message)s',) d...
from django.urls import path, include # https://docs.djangoproject.com/en/dev/topics/auth/default/#module-django.contrib.auth.views app_name = "account" urlpatterns = [ path("", include("django.contrib.auth.urls")), ] # This is a list of the included urls # accounts/login/ [name='login'] # accounts/logout/ [name...
#!/usr/bin/python from setuptools import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name="PyMoira", version="4.3.0", description="PyMoira - Python bindings for the Athena Moira library", author="Evan Broder", author_email="broder@mit.edu", lice...
""" decodeした画像を確認 """ from char_img_autoencoder import CharImgAutoencoder from img_loader import ImgLoader import sys sys.path.append("../") from img_char.img_char_opt import ImgCharOpt from matplotlib import pylab as plt from PIL import Image import numpy as np # グラフに日本語を表示するために必要 import matplotlib font = {'famil...
import app.model as model class Task(object): def initialize(self): model.init_connection()
"""Represents a refused transaction message.""" from marshmallow import EXCLUDE, fields from .....messaging.agent_message import AgentMessage, AgentMessageSchema from .....messaging.valid import UUID4_EXAMPLE from ..message_types import PROTOCOL_PACKAGE, REFUSED_TRANSACTION_RESPONSE HANDLER_CLASS = ( f"{PROTOCOL...
from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize(["kambing.py", "dawet.py"]) )
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2018/10/12 14:59 # @File : t22FindFirstCommonNode.py # @Software: PyCharm # 两个链表的第一个公共结点 # https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-intervi...
import json import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--otgy', type=str) # MultiWOZ hotel-book stay,hotel-book people,hotel-stars,train-book people # SMD distance,temperature parser.add_argument('--remove_fields', type...
from graphene_django import DjangoObjectType import graphene from .models import Projectil class ProjectilType(DjangoObjectType): class Meta: model = Projectil class CreateProjectil(graphene.Mutation): class Arguments: name=graphene.String() sprite=graphene.String() ...
from backend.core.model.dictionary.hash.HashDictionary import HashDictionary from backend.core.model.preprocess.TokenizingPorter2Stemmer import TokenizingPorter2Stemmer from backend.core.model.semantics.ISemanticsStrategy import ISemanticsStrategy from backend.core.util.util import * from backend.shared.NodeCommunicato...
from flask import Flask, redirect, session, request, render_template import random # create a site that when a user loads it creates a random number between 1-100 # stores the number in a session # allow the user to guess at the number and tell them when they are too high or too low app = Flask(__name__) app.secret...
import sys import struct import argparse import numpy as np from builtins import range # Reads an idx file and stores it in a numpy array def read_idx( filename ): try: with open(filename, 'rb') as f: # First two bytes are ignored, second byte is the data type and last byte is the number of di...
from sklearn.externals import joblib import numpy as np import faiss import time from sklearn.decomposition import PCA from sklearn.preprocessing import normalize from multiprocessing import Pool query_file_path = "test_gem.pkl" index_file_path = "index_gem.pkl" query_images, query_features = joblib.load(query_file_p...
""" Contain functions related to the creation, manipulation and the retrival of any useful information of the tic-tac-toe board. """ import numpy as np from copy import deepcopy BLANK_STATE = 0 HUMAN_STATE = 1 BOT_STATE = 2 def create_board(): """ Creates a 3 by 3 numpy array containing BLANK_STATE....
import discord import requests from discord.ext import commands from near.database import get_embeds class Crypto(commands.Cog): def __init__(self, client: commands.Bot): self.client = client # This is the please-wait/Loading embed self.please_wait_emb = discord.Embed(title=get_embeds...
import copy from numpy import float import random """ Entrospector Research project for Dr. Bryan Pickett Developed by Piotr Senkow November 10, 2017 """ class Entropy: def __init__(self, system, system_counts, duplicate, duplicate_counts): self.genome = system self.genome_counts = system_counts...
# Generated by Django 2.2.10 on 2020-03-20 11:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0003_auto_20200320_1645'), ] operations = [ migrations.AlterField( model_name='registrations', name...
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) Wu Dong, 2020 # All rights reserved # @Author: 'Wu Dong <wudong@eastwu.cn>' # @Time: '2020-06-23 11:00' """ 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" "132" "213" "231" "312" "321" 给定 n 和 k,返回第 k 个排列。 说明: 给定 n 的范围是 [1, ...
from sstcam_sandbox import get_checs from CHECLabPy.plotting.setup import Plotter from TargetCalibSB.pedestal import PedestalTargetCalib import numpy as np from os.path import join class Hist2D(Plotter): def plot(self, values, hits, clabel): masked = np.ma.masked_where(hits == 0, values) im = self...
# -*- coding: utf-8 -*- from odoo import http, _ from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager from odoo.exceptions import AccessError, MissingError from collections import OrderedDict from odoo.http import request class PortalMembership(CustomerPortal): def _prepare_ho...
import http.server import sys class RequestHandler(http.server.BaseHTTPRequestHandler): def get_response(self): if self.path.startswith("/get-my-path/"): return b"/" + self.path.split("/", maxsplit=2)[2].encode() elif self.path == "/": return b"OK" return None ...
from __future__ import print_function import os import sys import json from lxml import etree LANGUAGES = json.load(file(os.path.join(os.path.dirname(__file__),'languages.json'))) COUNTRIES = json.load(file(os.path.join(os.path.dirname(__file__),'countries.json'))) PLURALS = json.load(file(os.path.join(os.path.dirname...
from django.urls import path from .import views urlpatterns = [ path('', views.index,name="home"), path('portfolio/', views.portfolio,name='portfolio.page'), path('price/', views.price,name='price.page'), path('blog/', views.blog,name='blog.page'), path('about/', views.about,name='about.page'), ...
def maxSum(arr): incl = 0 excl = 0 for i in arr: new_excl = excl if excl>incl else incl incl = excl + i excl = new_excl if excl>incl: return excl else: return incl inputList = [int(item) for item in input("Enter the list ite...
# GCS Utility Functions # Copyright (C) 2014 Mitchell Barry # Adapted from content distributed through Apache 2.0 License by Google # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Founda...
import sys import numpy as np import scipy from scipy import ndimage def sigmoid(z): s = 1/(1+np.exp(-z)) return s def initialize_with_zeros(dim): w = np.zeros((dim,1)) b = 0 assert(w.shape == (dim, 1)) assert(isinstance(b, float) or isinstance(b,int)) return w,b def propagate(w, b, X, Y): m = X.shape[1] A = s...
import re text = input() pattern = r'>>(?P<product>[A-Za-z]+)<<(?P<price>\d+(\.\d+)?)!(?P<quantity>\d+)' total_spend = 0 print(f"Bought furniture:") while not text == "Purchase": match = re.fullmatch(pattern, text) if match is None: text = input() continue print(match.group("product")) ...
# Generated by Django 2.1.5 on 2019-03-04 14:45 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20190304_1139'), ] operations = [ migrations.AlterField( ...
# 1). A학급의 학생 이름은 다음과 같다: # # Bob # John # Sara # Jack # John # Paul # Belinda # Jessica # # 위 자료를 리스트 a로 정리해본다. x = '''Bob John Sara Jack John Paul Belinda Jessica ''' list1 = x.replace(' ', '').split('\n') print(list1) # 학생 이름을 대문자화 한 리스트 A를 만들어 보시오. x = x.upper() list1 = x.replace(' ', '').split('\n') print...