text
stringlengths
38
1.54M
import imdb from imdb.Person import Person ia = imdb.IMDb() #Prompts user to type in movie. name = input('Type in the movie you want to search: ') #This line takes the input and searches the IMDb search system for it. search = ia.search_movie(name) #This takes the first result of the search and makes it the object. #...
from os import listdir from os.path import isfile, join import re import numpy as np from scipy.stats import norm from scipy.stats import lognorm import matplotlib as mpl import matplotlib.pyplot as plt import preprocessing as prep import pdfplot as pdfplt import kldplot as kldplt name = "update-performance" fig = pl...
from django import template # import settings # from pyparsing import basestring register = template.Library() @register.filter('startswith') def startswith(text, starts): if isinstance(text, basestring): return text.startswith(starts) return False @register.filter(name='get') def get(obj, key): ...
####### DATABASE AND PYTHON ######## # Connect to SQL Server database using pyodbc import pyodbc server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID=...
#dependencies to create flask app and machine learning model From flask import flask, render_template, request App = Flask(__name__) #if we create our own model can use pickle. Model_TSLA = pickle.load(open(‘test_model.pkl’,’rb’)) #create route for home route @app.route("/") def home(): return render_templat...
import math from camera import RGBD from DQN import DQN from Env import Robot, CubesManager import copy import rospy robot = Robot() cum = CubesManager() cum.reset_cube(False) robot.test1() robot.reset()
import time, os, math, sys import ROOT ROOT.gROOT.SetBatch(True) def main(options,args) : print 'Starting retrieve.py to retrieve file on Grid or Condor.' print 'Loading Root...' ROOT.gROOT.ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C") submitDir = options.dir if os.path.exists(submitD...
#-------------------------------------------------------------------------------------------------# # General Configrations #-------------------------------------------------------------------------------------------------# from enum import Flag, auto MAX_DEPTH = 2 # maximum depth of DFS trees FILE_TYPE = 'csv' # ou...
# Generated by Django 2.1.5 on 2019-02-24 03:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock_picker', '0006_auto_20190224_1138'), ] operations = [ migrations.AlterField( model_name='stock', name='logo', ...
from django.contrib.auth import authenticate, logout, login from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.db.models import Avg from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views import View from django....
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-15 21:31 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateMo...
import pygame from pygame.sprite import Sprite class Star(Sprite): """Класс спрайтовой звезды.""" def __init__(self, ai_settings, screen): """Инициализирует звезду и задает ее позицию.""" super().__init__() self.screen = screen self.ai_settings = ai_settings # С...
# -*- coding: utf-8 -*- from kivy import platform from kivy.base import stopTouchApp from kivy.core.window import Window, Keyboard from kivy.properties import StringProperty, ObjectProperty from kivy.uix.boxlayout import BoxLayout from core.categoryScreen import CategoryScreen from core.mainScreen import MainScreen fro...
import numpy as np import cv2 import csv from find_BB_and_depth import find_BB_and_depth # import load_mat_to_python from linreg_closedform import LinearRegressionClosedForm as LinearRegression from PIL import Image # from NeuralNet import runNeuralNet import sys def estimateSize(): # Part 0: Loading the data wi...
from scrapy import Request from scrapy.spiders import Spider from douban.items import DoubanItem import json class MovieSpider(Spider): name = 'movies' currentPage = 1 # 定义headers属性,设置用户代理 headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "Apple...
# Generated by Django 2.2.6 on 2020-04-30 03:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('publicaciones', '0001_initial'), ] operations = [ migrations.CreateModel( n...
bil1 = int(input("MASUKAN BILANGAN KE-1 :")) bil2 = int(input("MASUKAN BILANGAN KE-2 :")) bil3 = int(input("MASUKAN BILANGAN KE-3 :")) terbesar = bil1 if(bil2>terbesar): terbesar=bil2 if(bil3>terbesar): terbesar=bil3 print("BILANGAN TERBESAR DARI KE-3 BILANGAN TERSEBUT ADALAH :", terbesar)
import numpy as np from networkx.utils import * import os from generalize_ising_model.ising_utils import save_graph, makedir # Average Value path_input = '/home/user/Desktop/' simulation_name = 'experiment_1' path_output_data = path_input + simulation_name path_outputexp_exp = path_output_data + '/average_value/' defa...
from flask import Flask from flask_restful import Api from config import app_config from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from flask_jwt_extended import JWTManager db = SQLAlchemy() jwt = JWTManager() api = Api(prefix='/api/') def create_app(config_name): app = Flask(__name__) ...
""" @author : Sundesh Raj UTA_ID : 1001633297 CSE6363 Machine Learning Final Project """ import math import os #importing Python heap class to perform heap queue operations #https://github.com/python/cpython/blob/3.7/Lib/heapq.py import heapq import time import operator from csv import reader #suppress unwanted war...
import os class c: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def getMac(path): f = open(path) a = f.read() a=a.replace("OBSS", "").replace("* BSS", "").replace("* BSS...
# -*- coding: utf-8 -*- """ Created on Fri Apr 20 17:01:36 2018 @author: Andy Everitt Detects desk using contours from depth image """ import numpy as np import cv2 import os import pyrealsense2 as pyrs """ test00 - Bedroom desk, unobstructed -> knee. (unaligned color & depth) test01 - Bedroom desk, unobstructed...
import re def get_after(string, after_this): assert isinstance(string, str) or isinstance(string, unicode) assert isinstance(after_this, str) or isinstance(after_this, unicode) return string[string.index(after_this) + len(after_this):] def get_before(string, before_this): assert isinstance(string,...
import pandas as pd import pickle from joblib import load # from collections import OrderedDict from json2html import * import sklearn # Update file path to app specific path test_df = pd.read_csv("app/home/model/test_df.csv") def pred_function(x): """ NOTE: Files required for correct functionality! Ta...
current_users=['John','B','c','d','e','h'] print(current_users) current_user=[] #定义一个变量 for x in current_users: current_user.append(x.lower())#将列表转化为小写 print(current_user)#测试是否转化了小写 print(current_users)#测试原列表是否没被更改 new_users=['JOHN','b','f','g','p'] for new_user in new_users : if new_user.lower() in current_...
import os import csv # Path to collect data from the Resources folder csvpath = os.path.join('election_data.csv') with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) csv_header ...
import hashlib class Ed25519P(): p = 2**255 - 19 L = 2**252 + 27742317777372353535851937790883648493 d = (-121665 * pow(121666, p-2, p)) % p def __init__(self, x, y): if x is None or y is None: raise ValueError("x or y are None") self.x = x % self.p self.y = y % se...
from ..decorators import * from numbers import Real @validate_args([Real, Real, Real]) @ignite_global def helper_circle(self, *args): self.ellipse(*args, args[2]) @validate_args([Real, Real, Real]) @ignite_global def helper_stroke_circle(self, *args): self.stroke_ellipse(*args, args[2]) @v...
import os NUM_CLIENTS = 4 if __name__ == "__main__": # change to current directory to run the script os.chdir(os.path.dirname(os.path.realpath(__file__))) # run server.py in another cmd window os.system("start cmd /K python server.py") # run client.py in another cmd windows for client_id in r...
from flask import Flask, request, jsonify import json import cleaner import model_util import nltk app = Flask(__name__) nltk.download('punkt') @app.route("/rest/classify", methods=['POST']) def classify(): data = request.get_json() input_tokenized = tokenizer.texts_to_matrix([cleaner.clean_message(data['cont...
import os import numpy as np def get_size(start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size print '\t Total memory usage in this a...
'''5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке. ''' START, END = 32, 127 PAIR_NUM = 10 for j in range(PAIR_NUM): pairs = '' first = START + PAIR_NUM * j f...
from collections import OrderedDict from pymongo.errors import BulkWriteError from database import DB from models.withdrawn_stuff import WithdrawnStuff from settings import users_fields class User(object): def __init__(self): cols = DB().mydb.collection_names() if 'users' not in cols: ...
# this version is old and may not work def train(): best_model = {} best_test_acc = 0.0 for epoch in range(num_epochs): print('\n------------Training------------\n') model.train() time1 = time.time() for i, (query, pos, neg) in enumerate(train_loader): query = qu...
""" Function to find the length of the given linked list Input: lst --> linked list head Return value: length TC: O(n) SC: O(1) """ from Node import Node from LinkedList import LinkedList from insertion_tail import insert_at_tail def length(lst): length = 0 cur = lst.get_head() while cur: length += 1 cur = cu...
# from datasets.pascalvoc import PascalVOC from datasets.corrosion import Corrosion from torch.utils.data import DataLoader import generators.deeplabv2 as deeplabv2 import torch import torch.nn as nn from torch.autograd import Variable import argparse import os import numpy as np from utils.metrics import scores import...
import setuptools setuptools.setup( name="distill", author="Julian Mack", description="toy NLP knowledge distillation", packages=["distill"], include_package_data=True, )
# from account.forms.using_proxy_models import * # from account.forms.using_boolean_values import * from account.forms.using_multiple_choices import *
"""By Kutay/Berkay DÖNMEZ""" #should get bs4, html5lib, lxml packages first import scipy.constants as sc import xarray as xr import numpy as np from datetime import datetime, timedelta from dask.distributed import Client import matplotlib.pyplot as plt from metpy.plots import SkewT from metpy.units import units from ...
from easydict import EasyDict as edict import json config = edict() config.TRAIN = edict() ## Adam config.TRAIN.batch_size = 4 # [16] use 8 if your GPU memory is small, and use [2, 4] in tl.vis.save_images / use 16 for faster training config.TRAIN.lr_v = 1e-4 config.TRAIN.beta1 = 0.9 ## initialize G conf...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.model import no_value_fields from frappe.translate import set_default_...
'''Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.''' produtos = ('Lápis', 1.75, 'Borracha', 2.00, 'Caderno', 15.90, 'Estojo', 25.00, 'Transferidor', 4.20, 'Compasso...
#!/usr/bin/python # -*- coding: latin-1 -*- # leetcode 67 class Solution(object): def addBinary(self, a, b): if len(a) < len(b): a, b = b, a size = len(a) add = 0 result = [] for i in range(1, size + 1, 1): curValue = int(a[-i]) if add =...
import networkx as nx import numpy as np from matplotlib import pyplot as plt import pprint import argparse import json from wiki import (get_candidates, edge_between, find_most_linked, generate_links_dict, check_edge, get_pageviews, trim_candidates, create_backlinks_count_dict, parallelise_requests) import settings ...
def processar_resposta(cl): if cl == '1': po = float(input('Qual a tensão?: ')) pi = float(input('Qual a corrente?: ')) pt = po * pi print(f'A potencia é: {pt}P') elif cl == '2': pl = float(input('Qual a potencia?: ')) pk = float(input('Qual a corrente?: ')) ...
# -*- coding: utf-8 -*- from django import forms from .models import Ouser class ProfileForm(forms.ModelForm): class Meta: model = Ouser fields = ['link','avatar']
class MyCalendar: def __init__(self): self.events = [] def book(self, start: int, end: int) -> bool: for s, e in self.events: if end <= s or start >= e: continue else: return False self.events.append([start, end]) return T...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-03 22:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('web', '0015_merge_20160903_1820'), ('web', '0015_merge_20160903_1430'), ] operations ...
#!/usr/bin/env python import pytest import os import devtools_shorthand_sql.instructions_parser as parser def test_map_raw_field_data_type(): # field type exists, upper result = parser.map_raw_field_data_type('INT') assert result == 'INT' # field type exists, lower result = parser.map_raw_field_d...
# -*- coding: UTF-8 -*- #!/usr/bin/env python #from time import sleep from urllib.parse import urlparse from lxml import etree import requests from application.conf import HEADERS from application.defaults import TIMEOUT def check_alexa(url, timeout=TIMEOUT): """ Returns Alexa rank of given web site url ...
#!/usr/bin/env python # Outside libraries import pygame # Python libraries import random import time from math import sin, cos, pi ################################################################################ ########################## PARTICLE DEFINITION ################################# ####################...
from django.urls import path, include from rest_framework.routers import DefaultRouter from playlist import views router = DefaultRouter() router.register('tracks', views.TrackViewSet) router.register('ingredients', views.GenreViewSet) app_name = 'playlist' urlpatterns = [ path('', include(router.urls)) ]
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix import xarray as xr import plotly import plotly.offline as py from plotly.tools import FigureFactory as FF from cesium import featureset from .config import cfg def feature_scatterplot(fset_path, features_to_plot): """Create scat...
#! python # -*- coding: UTF-8 -*-# enable debugging import cgitb import mysql.connector mydb = mysql.connector.connect( host="192.168.73.6", port="3306", user="erabiltzailea", password="1234", database="jatetxea" ) def produktuaTabla(): mycursor = mydb.cursor() mycursor.execute("SELECT * FRO...
import numpy as np from sklearn import svm from sklearn.feature_selection import VarianceThreshold # 1. get training and test set of X & Y import csv X = [] Y = [] X_test = [] accVec = [] avgVec = [] numFolds = 10 degreeVec = [3,4,5,6,7,8,9,10] # Training datasets with open('train_vale.csv') as csvfile: readCSV = ...
#!/usr/bin/env python import operator from functools import reduce from django.contrib import messages from django.db.models import Q from django.views.generic import ListView, CreateView, UpdateView, DeleteView from .models import EstandarAcceso, Perfil, Persona class GenericListView(ListView): model = object...
#Scientific Calculator # Import tkinker and other libraries from tkinter import * import math import parser import tkinter.messagebox root = Tk() root.title("Scientific Calculator") root.configure(background = 'white') root.resizable(width=False, height=False) root.geometry("480x568+450+90") calc = Frame(root) calc.g...
# Generated by Django 2.2.6 on 2020-01-02 10:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0006_auto_20200102_0936'), ] operations = [ migrations.AddField( model_name='comment', name='date_pub', ...
targets = [int(x) for x in input().split()] target_counter = 0 shot_target = input() while not shot_target == "End": shot_target = int(shot_target) if shot_target in range(len(targets)): if not targets[shot_target] == -1: temp = targets[shot_target] targets[shot_target] = -1...
# -*- coding:utf-8 -*- from fileio import * from utils import * from models import * import sys def generate_ad_account_graph(fn, not_family_ads, ad_shareddevices): nodes = dict() edges = dict() for line in open(fn): ad, device, os_, ua, ext_id, pro_category, count = line.strip('\n').split('\00...
from belize.dao.CanalDAO import CanalDAO from belize.dao.MensagemDAO import MensagemDAO from belize.modelo.CanalParaListagemVM import CanalParaListagemVM from belize.modelo.CanalVM import CanalVM from pyorient import OrientDB from belize.modelo.UsuarioVM import UsuarioVM from belize.modelo.WorkspaceVM import Workspace...
""" Classes and methods for storing and manipulating time data, including: - The TimeMetadata model for defining metadata for TimeData - The TimeData class for storing TimeData - Implementations of time data readers for numpy and ascii formatted TimeData - TimeData processors """ from loguru import logger from typing ...
# code a= 3 b= 4 print("a is", a, "b is",b) if a > b : print(a , "is bigger than ", b) # break cell here Add another if statement to the code above to check if b is greater than or equal to a
# https://leetcode.com/problems/squares-of-a-sorted-array/ # Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. # Example 1: # Input: nums = [-4,-1,0,3,10] # Output: [0,1,9,16,100] # Explanation: After squaring, the array beco...
import pickle import csv import pandas as pd import os import random from sklearn.utils import shuffle import numpy as np from math import cos, asin, sqrt #reading the saved model form pickle file pickle_in = open("static/knn/knn.pickle","rb") model = pickle.load(pickle_in) indices = model['indices']...
import FWCore.ParameterSet.Config as cms ecalFEDWithCRCErrorProducer = cms.EDProducer("EcalFEDWithCRCErrorProducer", InputLabel = cms.InputTag("source") )
segundos=1 print ('\n') while (segundos>=0): segundos=eval(input('Escreva um número de segundos\n(um número negativo para terminar)\n? ')) if (segundos >= 0): dias = segundos / 86400 print ('O numero de dias correspondente é', dias)
import sys import random import numpy as np from astropy.io import fits np.set_printoptions(threshold=np.inf) def parse_s82(filename): # read out s82 ID of each source and their ra / dec ID, ra, dec = [], [], [] with open(filename) as f: lines = f.readlines() for line in lines: ...
from rest_framework import routers from .views import HomeworkResultViewSet, PersonalHomeworkViewSet router = routers.SimpleRouter() router.register(r'results', HomeworkResultViewSet, basename='Homework')# страница для мониторинга всех ДЗ и их фильтрации router.register(r'myhomework', PersonalHomeworkViewSet, basenam...
"""Constraint Tests""" import pytest from ..lib.constraint import ( Constraint, SimpleConstraint, SimpleConstraintABC, ) def test_simpleconstraint_reprocess_match(): """Test options for reprocessing""" sc = SimpleConstraint( value='my_value', reprocess_on_match=True ) matc...
class FoxAndGame: def countStars(self, result): return sum(r.count('o') for r in result)
''' 3. Matrix product Question : Given a matrix, find the path from top left to bottom right with the greatest product by moving only down and right ''' import sys from functools import reduce def pathProduct(grid): def dfs(grid,r,c,path): nonlocal maxprod if r == len(grid)-1 and c== len(grid[0])-1: p...
from hypothesis import given from clipping.planar import (intersect_segments, subtract_segments, unite_segments) from tests.utils import (SegmentsPair, SegmentsTriplet, are_compounds_similar, ...
""" Show default for 'preserved_as_paper_default' bin/instance run show_preserved_as_paper_default.py """ from opengever.document.interfaces import IDocumentSettings from opengever.maintenance.debughelpers import setup_app from opengever.maintenance.debughelpers import setup_option_parser from opengever.maintenan...
import time def toString(List): return ''.join(List) strings = [] def allLexicographicRecur (string, data, last, index): length = len(string) for i in range(length): data[index] = string[i] if index==last: strings.append(toString(data)) else: allLexicographic...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-02-11 05:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0004_auto_20180211_1056'), ] operations = [ migrations.AlterFie...
# flake8: noqa from django.conf.urls import patterns, url, include from docorsauth import views urlpatterns = patterns('', url( r'^accounts/register/$', views.register, name='registration_register' ...
import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv') ill_df = df.query('Province_State == "Illinois"') filter = ['Admin2', 'Lat', 'Long_'] for i in range(15, 32): filter.append('10/'...
from functools import wraps def str_bool(value): """ Parse bool from string Usage: >>> str_bool("1") True >>> str_bool("0") False >>> str_bool("TRUE") True >>> str_bool("false") False :param value: str :return: bool """ value = value.strip().lower() if...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'auth.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, ...
""" Simple Flask App to Predict Iris Species""" import json import logging import sys from flask import Flask, render_template, session, redirect, url_for from flask import request from flask.ext.wtf import Form from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from wtforms imp...
import cv_service_1 import unittest class CvService1(unittest.TestCase): def setUp(self): self.app = cv_service_1.app.test_client() self.app.testing = True def test_healthcheck_code(self): response = self.app.get('/cv1/healthcheck') self.assertEqual(response.status_code, 200) ...
from Coronavirus import SarsCoV2 import colorama from colorama import Fore from Bio.Seq import Seq import Bio.SeqIO as BIO from Bio import AlignIO from Bio import pairwise2 from Bio.pairwise2 import format_alignment from fuzzywuzzy import fuzz from fuzzywuzzy import process from Bio import Entrez import mysq...
# 以二叉树对应的完全二叉树为参照,空白节点处使用#字符填充,使用层次遍历表示二叉树,节点间使用空格分割,如4 2 7 # 3 6 9, # 输出其镜像 """ way1 暴力美学 1.空白节点用#填充,因此可以把它当作完全二叉树 2.完全二叉树除叶节点所在层外,每层节点数满足2**n,n是所在高度高度减1, 如第一层有2**0个节点,第二层有2**1个节点 3.计算层数 sum = 0 ,i = 0 循环:last_sun = sum ,sum += 2**i, i += 1 退出循环: sum >= length 则树的高度为 height = i,叶节点数: leaf_nodes = ...
import tensorflow as tf import pandas as pd df = pd.read_csv('./item_vector.csv') num_input = 157 num_hidden = 64 num_code = 10 num_output = num_input learning_rate = 0.01 X = tf.placeholder(tf.float32, shape=[None, num_input]) W1 = tf.Variable(tf.truncated_normal([num_input, num_hidden], stddev=0.1)) b1 = tf.Varia...
def main(): print('Generate join pairs') f = open('join_pairs_pbsm_multiplier_larger_medium_datasets.csv', 'w') # bits = range(1, 11) # dias = range(1, 11) # bits = [1, 2] # dias = [1] pbsm_multipliers = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 40000, ...
""" 10.1-5 Whereas a stack allows insertion and deletion of elements at only one end, and a queue allows insertion at one end and deletion at the other end, a deque (double- ended queue) allows insertion and deletion at both ends. Write four O(1)-time procedures to insert elements into and delete elements from both end...
import sys class SuperReducedString(): def __init__(self): pass def processSuperReducedString(self, s): i = 0 while i < len(s) -1: if s[i] == s[i + 1]: s = s[:i] + s[i+2:] i = 0 else: i += 1 ...
from rkd_harbor.test import BaseHarborTestClass from rkd_harbor.tasks.deployment.vault import EncryptVaultTask class EncryptVaultTaskTest(BaseHarborTestClass): def test_functional_file_is_encrypted(self): """Test encryption""" with self.subTest('Encrypt the file'): self.execute_mocked...
from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.db.models.signals import post_save from django.dispatch import receiver import hashlib # Create your models here. class user_details(models.Model): user = models.ForeignKey(User, on_delete=models.CA...
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): d=dict() for x in ar: if x not in d: d[x]=1 else: d[x]+=1 ans=0 for x in d: if d[x]%2!=0: d[x]-=1 ...
# -*- coding: utf-8 -*- """Tests for tmuxp. tmuxp.tests ~~~~~~~~~~~ """ from __future__ import (absolute_import, division, print_function, unicode_literals, with_statement) import os current_dir = os.path.abspath(os.path.dirname(__file__)) example_dir = os.path.abspath(os.path.join(current_d...
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 11:02:38 2018 @author: Admin """ import numpy as np class Operation(): def __init__(self, input_nodes=[]): self.input_nodes = input_nodes self.output_nodes = [] for node in input_nodes: node.output_nodes.append(self) ...
class Solution(object): def majorityElement(self, nums): maxCount = 0 maxNum = 0 for i in set(nums): count = nums.count(i) if count >= maxCount: maxCount = count maxNum = i return maxNum
def merge(a): if len(a) > 1: global c mid = len(a) // 2 L = a[:mid] R = a[mid:] merge(L) merge(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] <=R[j]: a[k] = L[i] i += 1 ...
from unittest import mock from zerver.lib.compatibility import ( find_mobile_os, is_outdated_desktop_app, is_pronouns_field_type_supported, version_lt, ) from zerver.lib.test_classes import ZulipTestCase class VersionTest(ZulipTestCase): data = ( [ case.split() for...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-02-22 16:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('history', '0002_predictiontest'), ] operations = [ migrations.AddField( ...
#!/usr/bin/env python3 from random import randrange, choice from functional.inventory import add_bottle, stock_take, StockLevelError, use_shot # from classy.inventory import add_bottle, stock_take, StockLevelError, use_shot from recipes import RECIPES CRED = '\033[91m' CEND = '\033[0m' # setup bottles SPIRITS = [ ...
# coding: utf-8 # ### 多分类问题中的混淆矩阵 # In[3]: import numpy as np import matplotlib.pyplot as plt from sklearn import datasets digits = datasets.load_digits() X = digits.data y = digits.target # In[4]: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, ...
from math import sqrt, acos, pi from decimal import Decimal, getcontext getcontext().prec = 30 class Vector(object): CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot normalize the zero vector' def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple([Decimal(x) ...