text
stringlengths
8
6.05M
#!/usr/bin/python2.7 """ Driver FIle to start execution """ ################################ ####### Driver file to ######### ####### start execution ######## ###### Author : Pavel Sur ###### ################################ import sys,os sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__))...
""" Module MontyLingua MONTY LINGUA - An end-to-end natural language processor for English, for the Python/Java platform Author: Hugo Liu <hugo@media.mit.edu> Project Page: <http://web.media.mit.edu/~hugo/montylingua> Copyright (c) 2002-2004 by Hugo Liu, MIT Media Lab All rights reserved. N...
filename=input(("enter the filenme")) extension=filename.split('.') print("extension",extension[-1])
import numpy as np from matplotlib import pyplot as plt import seaborn as sns def adjust_spines(ax, spines, offset=3, smart_bounds=False): for loc, spine in ax.spines.items(): if loc in spines: spine.set_position(('outward', offset)) spine.set_smart_bounds(smart_bounds) el...
import socket """ ******功能描述说明****** 1.获取键盘数据,并将其发送给对方 2.接收数据并显示 """ def send_msg(udp_socket): """发送信息""" msg = input("\n请输入您要发送的信息:") dest_ip = input("\n请输入您要发送的ip:") dest_port = int(input("\n请输入对方的端口号:")) # 发送数据到指定的电脑上的指定程序中,需要编码为bytes类型的数据进行发送 udp_socket.sendto(msg.encode("utf-8"), (dest_i...
from django.contrib import admin class ConsumerAdmin(admin.ModelAdmin): fields = ('name', 'key', 'secret', 'status') readonly_fields = ('key', 'secret') def save_model(self, request, obj, form, change): obj.status = 'accepted' if change is False: obj.generate_random_codes() ...
''' Write a program that randomly chooses and displays four digits, each from one to nine, with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression....
from interface import Qubit, QuantumDevice import numpy as np import qutip as qt from qutip.qip.operations import hadamard_transform from typing import List class SimulatedQubit(Qubit): qubit_id: int parent: "Simulator" def __init__(self, parent_simulator: "Simulator", id: int): self.qubit_id = ...
# -*- coding: utf-8 -*- from typing import List class Solution: def numberOfBeams(self, bank: List[str]) -> int: last_lasers, result = 0, 0 for row in bank: current_lasers = row.count("1") if current_lasers and last_lasers: result += current_lasers * last_l...
from datetime import datetime,timedelta,timezone import ast import pytz import json from user_input.models import UserDailyInput from quicklook.serializers import UserQuickLookSerializer from django.db.models import Q from collections import OrderedDict import quicklook.calculations.garmin_calculation from quicklook....
# -*- python -*- class Patient(object): def __init__( self, id, name, allergies ): self.id = id self.name = name self.allergies = allergies self.bed_number = None def __repr__( self ): return( "{" + " " + "type:" + " " + "Patient" + "...
"""Change polling model Revision ID: 20c45fff9ccb Revises: 1efa9375e67b Create Date: 2020-07-05 16:12:47.521137 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '20c45fff9ccb' down_revision = '1efa9375e67b' branch_labels...
from re import sub from rest_framework import serializers from django.urls import reverse from django.utils.html import strip_tags from django.contrib.auth.models import User from .models import Post class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name',...
"""Plot data from table of pressures and fluxes from proplyd arc fits """ from astropy.table import Table from matplotlib import pyplot as plt import json import numpy as np import seaborn as sns AU = 1.49597870691e13 PC = 3.085677582e18 d_Orion = 440.0 k_Boltzmann = 1.3806503e-16 cos80 = 0.173648177667 tab = Table.r...
# -*-coding:utf-8-*- import time import numpy as np from gensim.models.doc2vec import Doc2Vec from sklearn.externals import joblib import labsql class SvmInfer: def __init__(self): self.test_set = {} self.clf = joblib.load("./svm_models/train_model.m") self.conn = labsql.LabSQL('172.168....
from .views import CoffeeShopViewSet, NewsletterViewSet, BookViewSet,CoffeeShopBooksViewSet from rest_framework import routers from django.urls import path, include app_name = 'api-coffee-shops' router = routers.DefaultRouter() router.register(r'coffee_shops', CoffeeShopViewSet) router.register(r'coffee_shops/(?P<id>\...
import numpy as np small = 1e-6 def createFAST_EllipticWingBlade(span, nNodes): dx = span/(nNodes-1.0) x = np.arange(0,span+small, dx) - span*0.5 c = np.sqrt(1.0 - (2.0*x/span)**2) c[0] = small c[-1] = small with open('EllipticWing_Aerodyn_Blade.dat','w') as f: f.write('------- AERODY...
def pericolo_minimo(mappa): def conversion(mappa): grafo = {nodo:[] for nodo in range(len(mappa) * len(mappa[0]))} col_size = len(mappa) row_size = len(mappa[0]) for col in range(len(mappa)): for row in range(len(mappa[col])): nodo = (row_size * row) + c...
from backpack.core.derivatives.basederivatives import BaseDerivatives class FlattenDerivatives(BaseDerivatives): def hessian_is_zero(self): return True def ea_jac_t_mat_jac_prod(self, module, g_inp, g_out, mat): return mat def _jac_t_mat_prod(self, module, g_inp, g_out, mat): ret...
n=int(input('Enter:')) a=0 b=1 if n==1: print(a) else: print(a,end=' ') print(b,end=' ') for i in range(n-2): c=a+b a=b b=c print(c,end=' ')
""" - module that houses an object of type uPub """ class uPub_data(object): """docstring for `uPub_data`.""" def __init__(self, line): import hashlib """assigns values to the object. INPUT: MD file containing all data; path to image """ self.title = None # title of the microPublication self.path_...
# 数据去均值后协方差矩阵不变,特征值与特征向量也不变 # 数据标准化后的协方差矩阵等于相关系数矩阵,等于原始数据的相关系数矩阵 #机器学习采用的是规范化后的协方差矩阵 # numpy.std() 求标准差的时候默认是除以 n 的,即是有偏的,np.std无偏样本标准差方式为 ddof = 1; # pandas.std() 默认是除以n-1 的,即是无偏的,如果想和numpy.std() 一样有偏,需要加上参数ddof=0 ,即pandas.std(ddof=0) #用规范化的数据进行奇异值分解和特征分解,奇异值s的平方等于特征值,特征向量均相同,即<1><2><3>的特征向量相同, # 但<1><2>的特征值是<3>的m...
"""Tests for wait_for_travis""" import pytest from constants import ( NO_PR_BUILD, TRAVIS_FAILURE, TRAVIS_PENDING, TRAVIS_SUCCESS, ) from wait_for_travis import wait_for_travis pytestmark = pytest.mark.asyncio @pytest.mark.parametrize("statuses,result", [ [[NO_PR_BUILD, NO_PR_BUILD], NO_PR_BUIL...
a={'tel':25,'hin':36,'eng':15} k=input("enter sub:") if k in a: print("present, value = ",a[k]) else: print("not found")
def temp(): temp = float(input("Enter temperature:")) units = input("In which units C or F?:") if units == "c": temp = ((9/5)*temp)+32 print("That's",temp,"F") elif units == "F": temp = (temp-32)*(5/9) print("That's",tmp,"C") else: print("The unint should be w...
import calendar import math import numpy as np import threading import re import time # input data from the manager to the engine: timestamp,duration,bitrate,width,height def find_bitrate_stats(documents, method): """ Calculate simple statistics for a collection of bitrates Args: documents: A MongoDB ...
# -*- coding: utf-8 -*- """Unittests for models. """ __license__ = """ This file is part of Janitoo. Janitoo 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 Foundation, either version 3 of the License, or ...
# Copyright 2018 Davide Spadini # # 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...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Pass.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Pass_Window(object): def setupUi(self, Pass_Window): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('relationships', '0009_auto_20150717_2035'), ] operations = [ migrations.AddField( model_name='offer', ...
"""Form management utilities.""" import abc import re from collections import OrderedDict from django.forms import TypedChoiceField from django.forms.fields import Field from django.forms.widgets import RadioSelect from django.shortcuts import render from django.utils.encoding import force_str from django.utils.trans...
from typing import List from sqlalchemy import func, and_ from sqlalchemy.orm.exc import NoResultFound from bitcoin_acks.constants import ReviewDecision from bitcoin_acks.database import session_scope from bitcoin_acks.github_data.graphql_queries import ( comments_graphql_query, reviews_graphql_query ) from b...
import logging from flask.blueprints import Blueprint from waitlist.permissions import perm_manager from flask_login import login_required, current_user from waitlist.base import db from waitlist.storage.database import Account, AccountNote from flask.templating import render_template import flask from flask.globals im...
# Copyright (c) Members of the EGEE Collaboration. 2004. # See http://www.eu-egee.org/partners/ for details on the copyright # holders. # # 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 #...
from django.apps import AppConfig class ArtworkConfig(AppConfig): name = 'artuium_server.artwork'
import mysql.connector import sys db = mysql.connector.connect(host = "localhost", user = "dbuser04", passwd = "salasana", db = "pizzaDB", buffered = True) cur = db.cursor() #main function is a gam...
from __future__ import print_function import unittest """ Test the example deployer """ class TestDeployer(unittest.TestCase): ENV = {} ARGS = {} METADATA = {} def test_exit_0(self): """ Test the deployer exits 0 """
from settings import settings from office365.runtime.auth.user_credential import UserCredential from office365.sharepoint.client_context import ClientContext credentials = UserCredential(settings['user_credentials']['username'], settings['user_credentials']['password']) ctx = ClientContex...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import User class VisitorSignUpForm(UserCreationForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): ...
import numpy as np # principal component analysis from hylite.filter.mnf import plotMNF from hylite import HyData def PCA(hydata, output_bands=20, band_range=None, step=5): """ Apply a PCA dimensionality reduction to the hyperspectral dataset using singular vector decomposition (SVD). *Arguments*: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 19 19:49:18 2017 @author: ares """ import numpy as np import helpers as hp from scipy.stats import truncnorm M = 40 # Size of Patch Array timelength = 3000 stim = np.zeros([M,M,timelength]) for ind in range(timelength): stim[:,:,ind] = hp.get...
from sys import stdin word = str(stdin.readline().strip()) if "ss" in word: print("hiss") else: print("no hiss")
# from datetime import datetime, date # d = datetime.now() # print(d) # print(d.year, d.month, d.day, d.hour, d.minute, d.second) if True: print("true") else: print("false") total = 'aaa' + \ 'bbbbb' + \ 'cccc' print(total) str='123456789' print(len(str)) print(str[0]) print(str[0:-1]) print(str[...
import enchant dipper = "abcdefghijklmnopqrstuvwxyz" d = enchant.Dict("en_US") decrypted_msg = [] score = [] def get_keys(message): for key in range(0, 27): mabel = decrypt2(key) zipping(message, mabel) def encrypt(Message,key): Encrypted_Message = "" Message = Message.lower() fo...
import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense from tensorflow.keras import Sequential from tensorflow.keras.optimizers import Adam from sklearn import datasets from sklearn import preprocessing ''' 1. trees.csv를 읽어들여서 아래에 대해 Vo...
# -*- coding:utf8 -*- from django.http import HttpResponse def home(request): return HttpResponse("ok")
import unittest from katas.kyu_6.does_my_number_look_big_in_this import narcissistic class NarcissisticTestCase(unittest.TestCase): def test_true(self): self.assertTrue(narcissistic(7)) def test_true_2(self): self.assertTrue(narcissistic(371)) def test_false(self): self.assertFa...
arr=[5,3,4,8] min_arr=arr[0] # we assume that [0] is min of arr for _ in arr: if min_arr >_: min_arr=_
#!/usr/bin/env python # -*- coding: utf-8 -*- # # otra_app78.py # from Tkinter import * # Importamos el modulo Tkinter def DrawList(): # Creamos una lista con algunos nombres plist = ['Pablo','Renato','José Alonso'] for item in plist: # Insertamos los items en un Listbox ...
# coding: utf-8 import re from yabot.models.vote import VotePool from yabot.models.member import Member class VoteMonitor(object): def process_text(self, send_from, text): pass def process_command(self, send_from, text): match = re.match(ur'投票 (\d+)', text) if not match: ...
from django.urls import path, include, re_path from . import views app_name = 'datawarehouse' urlpatterns = [ path('', views.DatawarehouseView.as_view(), name='index'), # path('review', views.DatawarehouseView.as_view(), name='index'), path('mahasiswa/<int:id>', views.MahasiswaView.as_view(), name='mahasi...
# agents.py # ----------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klein (kle...
#-*-coding:utf-8-*- #这是认证蓝本的登录表单 from flask_wtf import Form from wtforms import StringField,PasswordField,BooleanField, SubmitField from wtforms.validators import Required,Length,Email,Regexp,EqualTo from wtforms import ValidationError from ..models import User class LoginForm(Form): email=StringField('邮箱',valid...
import random x = random.randrange(1,7) def roll_die(sides): r = random.randrange(1, sides + 1) return r
"""Policy daemon management command.""" import asyncio from contextlib import suppress import functools import logging import signal from django.core.management.base import BaseCommand from ... import core logger = logging.getLogger("modoboa.policyd") def ask_exit(signame, loop): """Stop event loop.""" lo...
from datetime import timedelta from .const import Timeframe _MAX_DAYS_PER_TIMEFRAME = { Timeframe.TICKS: 1, Timeframe.MINUTES1: 365, Timeframe.MINUTES5: 365 * 2, Timeframe.MINUTES10: 365 * 3, Timeframe.MINUTES15: 365 * 4, Timeframe.MINUTES30: 365 * 5, Timeframe.HOURLY: 365 * 6, Timefr...
import numpy as np from scipy.linalg import expm import math class Logistic: def __init__(self, learning_rate=0.001, num=1000): self.learning_rate = learning_rate self.num_iterations = num def fit(self, x, y): arr = np.ones(x.shape[0]) x = np.append(arr.reshape(arr.shape[0],1), x, axis=1) self.x = x s...
import sigpy as sp import numpy as np import sigpy.mri as mr import sigpy_e.nft as nft def jsens_calib(ksp, coord, dcf, ishape, device = sp.Device(-1)): img_s = nft.nufft_adj([ksp],[coord],[dcf],device = device,ishape = ishape,id_channel =True) ksp = sp.fft(input=np.asarray(img_s[0]),axes=(1,2,3)) mps = mr...
import sys sys.path.append('../500_common') import lib_seq a = "Chrome11" b = "Profile 1" path = "../504_kyoto01/data/result.html" lib_seq.main(a, b, None, None, waitTime=10, preTime=20, check=False)
import sys import os sys.path.append( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'proto'))
import graphlab import numpy as np def top_words(wiki, name): row = wiki[wiki['name'] == name] word_count_table = row[['word_count']].stack('word_count', new_column_name=['word','count']) return word_count_table.sort('count', ascending=False) def top_words_tf_idf(wiki, name): row = wiki[wiki['name'] =...
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 02:39:50 2020 @author: Nishal Sundarraman """ import pandas as pd import matplotlib.pyplot as plt import numpy as np dataset=pd.read_csv('train.csv') temp=dataset.iloc[:,:].values from sklearn.impute import SimpleImputer si=SimpleImputer(missing_val...
#!/usr/bin/env python3 # # A very basic DREAM Python example. This script generates a basic # DREAM input file which can be passed to 'dreami'. # # Run as # # $ ./basic.py # # ################################################################### import numpy as np import sys sys.path.append('../../py/') from DREAM.D...
#!/usr/bin/env python3 """Business Logic for training and preserving classification algorithms from skicit learn package. Usage: python3 words.py <URL> """ import pickle import Data.data as dl from Common import constants from datetime import datetime from sklearn.preprocessing import StandardScaler from sklearn...
#!/usr/bin/python3 # pihsm: Turn your Raspberry Pi into a Hardware Security Module # Copyright (C) 2017 System76, Inc. # # 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 Foundation, either version 3 of the...
import os def menu(account): while(True): print("<Main menu>") print("1. View and Modify Profile") print("2. View and Modify list of exercise") print("3. Analyze my exercise record") print("4. Set and View my exercise goal") print("5. Submit today's exercise record")...
from turtle import Turtle from math import pi def polyline(t, n, length, angle): """ Draws n segments line with the given length and angle in degrees between them. t: Turtle n: segments in polyline length: length of the segment angle: angle (degrees) between segments """ for i in rang...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re from astree.StatementSequence import StatementSequence # AST represents a program's abstract syntax tree class AST(StatementSequence): @staticmethod def preprocess(source): # Add endline after ';' source = source.replace(';', ';\n') ...
from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify class Category(models.Model): class Meta: db_table = 'category' category = models.CharField(max_length = 200) slug = models.SlugField(unique = True) #vivod v adminke ...
a = int(input("変数aの値を入力してください")) if (a == 0): print("変数 a の値は 0 です") elif (a == 1): print("変数 a の値は 1 です") else: print("変数 a の値は 0,1 以外の文字列です")
# _*_ coding: utf-8 _*_ import random game_count = 0 all_counts = [] while True: game_count += 1 guess_count = 0 answer = random.randint(0,99) while True: guess = int(input("请猜一个数字(0-99):")) guess_count += 1 if guess == answer: print("恭禧你,猜中了") print("你总共猜了" + str(guess_count) + "次") ...
# 使用 randint() import random # 定義 Encrypt 類別 class Encrypt: def __init__(self): self.setcode() def setcode(self): # 取得 a 、 b 值 a = random.randint(0, 9) print(a) # 印出 a b = random.randint(0, 9) print(b) # 印出 b # 利用公式建立密碼表 self.code = "" c = "a" i = 0 while i < 26: ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 01:55:03 2020 @author: sumant """ while True: try: print() print("Welcome To My Calculator") print("========================") print("1. ADD") print("2. SUB") print("3. MUL") print(...
# -*- encoding:utf-8 -*- # __author__=='Gan' # Find the contiguous subarray within an array (containing at least one number) which has the largest product. # For example, given the array [2,3,-2,4], # the contiguous subarray [2,3] has the largest product = 6. # If 0 in nums, the solution failed. class Solution(objec...
from manim import * import random WIN = 'W' LOSS = 'L' WIN_LOSS_LIST = ([WIN]*33) + ([LOSS]*66) WIN_PROFIT = 75 LOSS_PROFIT = -25 def get_profit(result): return WIN_PROFIT if result == WIN else LOSS_PROFIT def s_tex(*args, **kwargs): return Tex(*args, **kwargs).scale(0.6) def fischer_yates(list):...
# inject the lib folder before everything else from typing import Optional from waitlist.base import db from waitlist.permissions.manager import StaticRoles from waitlist.storage.database import Account, Character, Role, APICacheCharacterInfo from waitlist.utility.utils import get_random_token import waitlist.utility....
import requests from flask import Flask app = Flask(__name__) SENSOR_NAMING = { "10-000802e4e190": "Raspberry Pi", "10-000802e42e3f": "Raumtemperatur", } BASE_URL = "http://192.168.1.14:9090/api/v1/" @app.route("/") def hello(): res = requests.get(BASE_URL + "query?query=sensor_temperature_in_celsius")...
from aimacode.logic import PropKB from aimacode.planning import Action from aimacode.search import ( Node, Problem, ) from aimacode.utils import expr from lp_utils import ( FluentState, encode_state, decode_state, conjunctive_sentence, ) from my_planning_graph import PlanningGraph from functools import lru_cac...
from model import Todo import motor.motor_asyncio client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://root:example@localhost:27017/TodoList?authSource=admin') database = client.TodoList collection = database.todo async def fetchOneTodo(title): document = await collection.find_one({"title":title}) retur...
# #================================================================================================== # Jasy Template # Copyright 2013 Sebastian Fastner #-------------------------------------------------------------------------------------------------- # Based upon # Core - JavaScript Foundation # Copyright 2010-20...
from enum import Enum class FitnessConfig(Enum): LOWEST = 0 AVG = 1 HIGHEST = 2
from clpy.types.list import make_list from clpy.types.vector import make_vector from clpy.types.number import make_int from clpy.types.string import make_str class Space(object): def __init__(self): pass def eq(self, a, b): return a.eq(b) def hash(self, a): return a.hash() de...
import numpy as np from pypm import ICP from picp.main import icp_config, art from picp.plot_trajectory import icp_p_to_gaussian from picp.simulator.maps import create_basic_hallway, from_ascii_art from picp.simulator.scan_generator import ScanGenerator from picp.util.pose import Pose import matplotlib.pyplot as plt ...
# A class is the blueprint of an object class FirstClass: def __init__(self): b = 90 """This is the docstring""" # It can se accessed using __doc__ variable a = 10 def printtext(self): print("I am function") def printfunc(self): print("I am Function") fir = FirstClass...
from scipy import optimize # We define our function for later use when solving for Steady State: def solve_for_ss(n,tau,rho,alpha): """ solve for the steady state level of capital-per-worker Args: tau (float): taxation (fraction of income) rho (float): patience parameter n (float): popu...
#Apendix: import numpy as np import os import cv2 import time import matplotlib.pyplot as plt from scipy import interpolate def eqHist(original): image = original.copy() image[:,:,0] = cv2.equalizeHist(image[:,:,0]) image[:,:,1] = cv2.equalizeHist(image[:,:,1]) image[:,:,2] = cv2.equalizeHist(image...
from django.shortcuts import render, redirect from django.contrib.auth import logout from django.views.generic.base import TemplateView from django.views.generic.base import View from django.http import HttpResponse def home(request): return render(request, 'home.html') def my_logout(request): logout(reques...
from django.db import models from pulp import * import numpy as np Nb_creneaux = 13 class Patient(models.Model): nom = models.CharField(max_length=100) motif = models.CharField(max_length=500) jour = models.IntegerField() medecin = models.IntegerField() choix_1 = models.IntegerField() choix_2...
# https://www.hackerrank.com/contests/june-world-codesprint/challenges/equal-stacks def diminu_sum(nums): total = sum(nums) for x in nums[-1::-1]: total -= x yield total ''' def all_same(items): return all(x == items[0] for x in items) def all_same(items): try: iterator = iter(item...
import numpy as np def linear_kernel(X1, X2=None,**kwargs): if X2 is None: X2 = X1 K = X1.dot(X2.T) return K def polynomial_kernel(X1, X2=None, **kwargs): degree = kwargs.get('degree',2) if X2 is None: X2 = X1 return (1 + linear_kernel(X1, X2))**degree def rbf_kernel(X1, X2=N...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity def get_title_from_index(df, index): return df[df.Index == index]["Actors"].values[0] def get_index_from_title(df, actor): return df[df.Actors == actor][...
import random, math import util NUM_BITS_IN_NUM = 3 CITIES_NUM = 2 ** NUM_BITS_IN_NUM class TravelingSalesman: data = None best_fitness = 9999999 count_fitness = 0 total_count_fitness = 10 def new_individual(self): if not self.data: self.data = [] for num in range(...
# # @lc app=leetcode.cn id=90 lang=python3 # # [90] 子集 II # # @lc code=start class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() res, track = [], [] def backtrack(nums, depth): res.append(track[:]) for i in range(depth, len(nums...
import tornado.web import os import config from views import index class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/students1', index.Students1Handler), (r'/students2', index.Students2Handler), (r'/students3', index.Students3...
import tensorflow as tf from tensorflow import keras import numpy as np def st(s1): jsonFile = open("Fashion.json", "r") loadedModelJson = jsonFile.read() jsonFile.close() loadedModel = tf.keras.models.model_from_json(loadedModelJson) loadedModel.load_weights("Fashion.h5") loadedModel.compile(loss="sparse...
import json import numpy as np from autodisc.helper.data import JSONNumpyEncoder, json_numpy_object_hook from autodisc.helper.data import set_dict_default_values def test_set_dict_default_values(): # simple dict def_dict = {'a': 1, 'b': 2} trg_dict = {'b': 20, 'c': 30} test_dict = {'a': 1, 'b': 20, '...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verify that dependent rules are executed iff a dependency action modifies its outputs. """ import TestGyp import os test = TestGyp.Tes...
import os import sys import time filename = input("Enter an input file name: ") exists = os.path.isfile("./%s" % filename) notEmpty = os.path.getsize("./%s" % filename) > 0 if exists and notEmpty: file = open ("./%s" % filename, "r") else: print ("File doesn't exist or is empty.") exit freqList = list()...
# Copyright 2017 The Forseti Security Authors. 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 ap...
import pandas as pd from pandas.testing import assert_series_equal from powersimdata.network.usa_tamu.constants.zones import abv2state, id2abv from prereise.gather.demanddata.nrel_efs.map_states import ( decompose_demand_profile_by_state_to_loadzone, shift_local_time_by_loadzone_to_utc, ) def test_decompose_...