text
stringlengths
38
1.54M
from django.db import models from jsonfield import JSONField from django import forms from django.core.validators import MinLengthValidator # Create your models here. class Book(models.Model): isbn = models.BigIntegerField(primary_key=True) title = models.CharField(max_length=128) memo = JSONField(default...
import requests import json import os import time from push import push _push=push() uid=os.environ["uid"] token=os.environ["token"] data={ "uid" : uid, "token" : token, } TTbody=data headers={ 'Host': 'node.52tt.com', 'Content-Type': 'application/json', 'Origin': 'http://ap...
# -*- coding: utf-8 -*- """ Created on Tue Jul 7 10:48:18 2020 @author: bryce """ import numpy as np inp = np.random.rand(5,2) def sigmoid(inp): return np.array([(1+np.exp(-x))**-1 for x in inp]) sigmoid(inp)
from functools import partial def renameTable(table: str, table_new, conn, identifier='`'): cur = conn.cursor() sql = "ALTER TABLE {2}{0}{2} RENAME TO {2}{1}{2};".format(table, table_new, identifier) print(sql) cur.execute(sql) conn.commit() renameTablePostgre = partial(renameTable, identifier='"...
""" Twitter Bootstrap 4 - helper methods """ from textwrap import dedent from uuid import uuid4 from django import template from django.utils.safestring import mark_safe from plotly.graph_objs._figure import Figure register = template.Library() @register.simple_tag() def bs4_thead(columns: str) -> str: ths = ""...
from exts import db from datetime import datetime ''' 比如说,将 user 模型映射到数据库中: 1、在 models.py 中建好数据表模型,并在 manage.py 中导入模型 2、在根目录下:python manage.py db init (初始化数据库迁移环境,只在项目第一次使用时执行) 3、执行:python manage.py db migrate (将模型映射到数据库中,此刻数据库中增加数据库版本,模型还未真正映射成功) => 数据库升级 这里遇到第二行命令报错: #retur...
""" Utils that are implemented in scikit-learn. """ import sklearn.utils.extmath as extmath cartesian = extmath.cartesian
from sensors.interfaces import GPIOs from sensors.tachometer import Tachometer GPIO_ADDRESS_A = 15 gpios = GPIOs([GPIO_ADDRESS_A, ]) interfaces = { 'gpios': gpios, } encoder = Tachometer(interfaces) print(encoder.get_value())
#!/usr/bin python from subprocess import call from time import gmtime,strftime,sleep import os import picamera import io import sys from PIL import Image import math,operator import tweepy import urllib import re #import numpy as np width = 1280 heigth = 960 treshold = 20 # trigger for change detecti...
import os.path import be.repository.access as dbaccess import commonlib.messaging.messages messagecust_store = dbaccess.stores.messagecust_store def new(owner_id, name, content): return messagecust_store.add(owner=owner_id, name=name, content=content) def get(owner_id, name): mcust = messagecust_store.get_on...
# Volatility # Copyright (C) 2008-2013 Volatility Foundation # Copyright (c) 2008 Brendan Dolan-Gavitt <bdolangavitt@wesleyan.edu> # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published b...
import datetime r""" this creates an empty file """ filename=datetime.datetime.now() #create empty filename def create_file(): """this creates an empty file""" with open(filename.strftime("%y-%m-%d-%h-%M"),"w")as file: file.write("") create_file()
from django.forms import ModelForm, widgets from django import forms from .models import Product class ProductForm(ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'name' : forms.Textarea(attrs={'class':'form-control'}), 'weight' : forms.NumberI...
# instr_dec.py # instruction decoder: combinatorial logic block # input: MIPS 32-bit instruction # sets up processor control blocks import pyrtl # instantiate a memory block storing sample instructions (32-bit each) # reads one instruction per cycle sample_instructions = [201326592, 286326786, 4202528, 2366177284] m...
# This Python file uses the following encoding: utf-8 import sys def levenshtein_distance(statement, other_statement): import sys from difflib import SequenceMatcher if not statement or not other_statement: return 0 statement_text = statement.lower() other_statement_text = other_statement.lower() similar...
from .MetricDataLoader import MetricDataLoader, MetricGroups from .GeneralDataLoader import GeneralDataLoader from .loader import Loader
from ElementoMapa import ElementoMapa class Bomba (ElementoMapa): #construye la bomba def __init__ (self): self.__activada = False #getter y setter de la activacion def get_activada(self): return self.__activada def set_activada(self, activada): self.__activada = activ...
from abc import ABC class Vehicle: def __init__(self, registration_number, ticket, vehicletype=None): self.registration_number = registration_number self.__type = vehicletype self.__ticket = ticket def assign_ticket(self, ticket): self.__ticket = ticket class Car(Vehicle): ...
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize from Cython.Distutils import build_ext extensions = [ Extension("fonctC", ["script.py"]) # à renommer selon les besoins ] setup( cmdclass = {'build_ext':build_ext}, ext_modules = cytho...
#coding:utf-8 import sys import fasttext import json import logging from sklearn.model_selection import train_test_split from collections import defaultdict logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',level=logging.INFO) class fasttext_trainer: def __init__(self,modelname): sel...
# Create your views here. from django.http import HttpResponse from django.conf import settings from jinja2 import Environment, FileSystemLoader, Markup jinja = Environment(loader=FileSystemLoader(settings.TEMPLATE_DIRS), autoescape=True) from applicati import model base = model.createBase('./pickles').data.applicat...
#!/usr/bin/python #-*- coding:utf-8 -*- #********************************************************** #Filename: 110_range_int_as_element.py #Author: Andrew Wang - shuguang.wang1990@gmail.com #Description: --- #Create: 2016-10-04 15:45:14 #Last Modifieda: 2016-10-04 15:45:14 #******************************************...
from pages.frames.framePage import frame_Page_fields from utilities.BaseClass import BaseClass from utilities.reusablemethods import CustomMethods import pytest_check as check import pytest class Test_validate_mouse_hover(BaseClass): @pytest.mark.skip def test_mousehover_click(self): log = self.getLo...
#!/usr/bin/python import hashlib,binascii import sys input = sys.argv[1] hash = hashlib.new('md4',input.encode('utf-16le')).digest() print binascii.hexlify(hash)
#String Built-in Functions #min(value)-returns the minimum of the letter in the string a="hello welcome to python proggramming language" res=min(a) print(res) #as space has the minimum so it prits space
from __future__ import print_function from das_client import get_data import subprocess #from pdb import set_trace def query(query_str, verbose=False): 'simple query function to interface with DAS, better than using Popen as everything is handled by python' if verbose: print('querying DAS with: "%s"' % que...
import datetime from math import sqrt import operator import time from xml.dom import minidom import xml.parsers.expat import psycopg2 import requests import config rs = requests.Session() rs.headers.update({'User-Agent': 'sbot'}) if config.bot.eve_dsn is not None: db = psycopg2.connect(config.bot.eve_dsn) crest_p...
animals = ['chicken', 'cow', 'snail', 'elephant'] print(sorted(animals)) print(sorted(animals, key=len)) decorated = [(len(w), w) for w in animals] print(decorated) decorated.sort() result = [ d[1] for d in decorated] print(result) # at once print( [ d[1] for d in sorted( [(len(w), w) for w in animals] ) ] )
import contextlib import functools import json import os import pytest from dcicutils.env_base import LegacyController from dcicutils.common import APP_CGAP, APP_FOURFRONT # , LEGACY_GLOBAL_ENV_BUCKET from dcicutils.env_manager import EnvManager from dcicutils.env_utils import ( is_stg_or_prd_env, is_cgap_env, is...
def answer(s): if len(s) <=200 and len(s) > 0: count = 0 #for i in range(len(s)): while s[:len(s)/2] == s[len(s)/2:]: count += 1 s = s[:len(s)/2] count += 1 print "pattern: %s" %(len(s)) print "count: %s" %(count) s = "abccbaabccba" print answer(s...
import random import copy def clearScreen(): print(chr(27) + "[2J") # Escape sequence to clear screen def generateBoard(): whitelist = list(range(1,92)) board = [list(), list(), list(), list(),list()] for x in range(0,5): for y in range(0,5): i = random.randint(0,len(whitelist) - ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'XySetup.ui' # # Created by: PyQt5 UI code generator 5.4.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("F...
# _*_ coding:utf-8 _*_ __author__ = 'T' from scipy.spatial.distance import pdist from scipy.spatial.distance import squareform from scipy.linalg import eigh import numpy as np from sklearn.datasets import make_moons import matplotlib.pyplot as plt from sklearn.decomposition import PCA def rbf_kernal_pca(X, gamma, n...
##gcd program #num1 = int ( input ( ' Enter the number 1 = ' ) ) #num2 = int ( input ( ' Enter the number 2 = ' ) ) #min = num1 if num1 < num2 else num2 # to find smaller number #larg = 1 #for i in range ( 1, min+1 ): #if num1 % i == 0 and num2 % i == 0: #larg = i ## print GCD #print ( ' GCD of '...
import tensorflow as tf import numpy as np import pymysql tf.set_random_seed(700) seq_length = 7 data_dim = 1 hidden_dim = 10 output_dim = 1 learning_rate = 0.01 iterations = 2000 #num_layers = 3 # connect db con=pymysql.connect(host='52.78.192.119',port=3306,user='root',password='Cap2bowoo!',db='abee...
import json import os from pathlib import Path from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, overload import confuse # type:ignore import dotenv from pydantic.generics import GenericModel from hibiapi import __file__ as root_file CONFIG_DIR = Path(".") / "configs" DEFAULT_DIR = Path(root_fil...
# -*- coding: utf-8 -*- """ Created on Tue Oct 11 22:15:59 2016 @author: QiuXun https://leetcode.com/problems/two-sum/ """ class Solution(object): def __init__(self): self.vals = [] def twoSum(self, nums, target): # construct a dictionary from the list 'nums' # with v...
# Marianne Lawless #Programming and Scripting Project 2018 # Iris dataset downloaded from https://archive.ics.uci.edu/ml/datasets/iris import numpy # Read data file into array data = numpy.genfromtxt('data/iris.csv', delimiter=',') data[0] # Access the first line of data file# (data[:,0]) # Access the firs...
# __all__ =[ # 'augmentations', # 'datasets', # 'logger', # 'parse_config', # 'transforms', # 'utils' # ]
# coding: utf-8 import theano from theano import tensor as T import numpy as np data = np.array([[1, 2, 3]], dtype=theano.config.floatX) x = T.dmatrix(name='x') w = theano.shared(np.asarray([[0.0, 0.0, 0.0]], dtype=theano.config.floatX)) z = x.dot(w.T) update = [[w, w + 1.0]] net_input = theano.function(inputs=[], ...
import utils, time, socket, sys, re, os os.system("mkdir -p /opt/cto/log/") logger = utils.getLogger("/opt/cto/log/installation.log","a") logger.info("*******INSTALLATION OF PLATFORM BEGIN******") cm_server_host=utils.getXmlValue("manager","host") logger.info("Cloudera Manager from XML "+cm_server_host) ntp_s...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Description Models need to be parsed and put together, this saves time on that, if it has been parsed before and not updated ~~~~~~~~~~~~~~~ :license: MIT :author: Stephen Dop """ from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from sqlalchemy.or...
def my_mp3_playlist(file_path): text = "" splitted = [] grouped = [] longest = "" count = 0 freq_authour = "" with open(file_path, "r") as f: text = f.read().replace("\n", "") splitted = text.split(";") for i in range(0, len(splitted)-3, 3): grouped += [[splitted[i], splitted[i+1], splitted[i+2]]] # f...
from shutil import copyfile, move from libtuto.config_file_data import ConfigFileData from os.path import isfile class InvalidConfigList(Exception): pass class ConfigFileOverride: def __init__(self, override_data_list): """ :type override_data_list: List[ConfigFileData] """ i...
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 15:57:09 2019 @author: zixing.mei """ import lightgbm as lgb import random import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.linear_model import LogisticR...
arr=[12,14,22,8,1,6,0] for i in range(len(arr)): for j in range(i+1,len(arr)): if arr[i]>arr[j]: arr[i],arr[j]=arr[j],arr[i] print(*arr) # for i in range(len(arr)): # for j in range(len(arr)-1): # if arr[j]>arr[j+1]: # arr[j],arr[j+1]=arr[j+1],arr[j] # print(*...
# Third-Party Imports from django.core.exceptions import ValidationError from rest_framework import serializers # App Imports from core import models from core.constants import CHECKIN, CHECKOUT class AssetSerializer(serializers.ModelSerializer): checkin_status = serializers.SerializerMethodField() allocatio...
# -*- coding: utf-8 -*- # # Copyright 2018 isobar. All Rights Reserved. # # Usage: # python teeth-whitening.py pic.jpg # import os import sys import argparse import cv2 import dlib import numpy as np from skimage import io from PIL import Image from scipy.spatial import distance import IsobarImg DEBUG = False ...
# coding: utf-8 """ URLs de l'application Utilisateurs """ from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^ask/(?P<uid>\d+)$', 'social.views.page.add_friend', name='page-add-friend'), )
prisListe = [ {"salat" : 12, "fisk" : 99, "melk" : 12, "brod" :12}, {"salat" : 22, "fisk" : 60, "melk" : 18, "brod" :21}, {"salat" : 8, "fisk" : 120, "melk" : 10, "brod" :19}, {"salat" : 18, "fisk" : 40, "melk" : 30, "brod" :59}, {"salat" : 15, "fisk" : 200, "melk" : 40, "brod" :9}, ] butikker ...
# Generated by Django 3.1.7 on 2021-04-11 14:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('loginanddashboard', '0015_auto_20210411_1053'), ] operations = [ migrations.CreateModel( name='AllowancesDeductions', ...
import math num = int(input()) num = math.fabs(num) count = 1 num = num // 10 while num > 0: num //= 10 count += 1 print(count)
from __future__ import print_function import inspect import os def is_debugging(): for frame in inspect.stack(): if frame[1].endswith('pydevd.py'): return True return False def follow_link(fname): print(fname, end=" ") if os.path.islink(fname): print("\n\t->", end="") ...
import numpy as np from pyphocorehelpers.indexing_helpers import build_pairwise_indicies from scipy.ndimage import gaussian_filter1d # plotting: import matplotlib.pyplot as plt def _compute_single_lap_reliability(curr_lap_filtered_spikes_df, variable_extents_array, min_subdivision_resolution:float = 0.01, spike_blu...
import json from ctypes import ( c_char_p, c_size_t, c_uint8, c_uint32, c_uint64, c_bool, c_void_p, byref, pointer, addressof, ) from .lib import ( _lib, _encode, _flags, RNP_KEY_EXPORT_ARMORED, RNP_KEY_EXPORT_PUBLIC, RNP_KEY_EXPORT_SECRET, RNP_KEY_E...
from django.db import models class Sequence(models.Model): """ DNA sequence that can be added and then requested by name. Sequence can have only "ACTGactg" letters, maximum 20000. Name is up to 100 chars. Both fields are mandatory. """ name = models.CharField(max_length=100, blank=False) se...
import urllib.request import urllib.parse import urllib.error url="http://www.hhhhhddddd123.com" ''' try: request_obj=urllib.request.Request(url=url) response=urllib.request.urlopen(request_obj) except urllib.error.URLError as e: print(e.reason) ''' try: responese=urllib.request.urlopen("http://www.doba...
from maze_builder.meshes.mesh import MeshBuilder, MeshTransformation, MeshWarp from maze_builder.meshes.scene import * from maze_builder.meshes.yafaray import dump_yafaray from maze_builder.meshes.obj import dump_obj from maze_builder import random2 from .template import resource import random from maze_builder.util im...
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess import argparse import socket from time import sleep import grpc import uuid import sys import traceback from common.config import Config from maum.m2u.facade import dialog_pb2 from maum.m2u.da import provider_pb2 as provider from maum.m2u.da.v1 import t...
from torch.utils import data from abc import ABC, abstractmethod from abc import ABC, abstractmethod from torch.utils import data class BaseDataset(data.Dataset, ABC): def __init__(self, source, target): self.source = source self.target = target self.X = None self.y = None self.features = Non...
########################################### # Let's Have Some Fun # File Name: 123.py # Author: Weilin Liu # Mail: liuweilin17@qq.com # Created Time: Sat Oct 19 17:09:01 2019 ########################################### #coding=utf-8 #!/usr/bin/python # 123. Best Time to Buy and Sell Stock III class Solution: def ...
from flask_security.forms import RegisterForm from wtforms import StringField, validators # registration form class RegistrationForm(RegisterForm): first_name = StringField('first_name', [validators.length(min=2, max=50)]) second_name = StringField('second_name', [validators.length(min=2, max=50)]) phone_...
import os begining = "program_files += [('" ending = ", 'DATA')]" with open("imgScanSpec.txt", "w" ) as textFile: path = os.path.join(os.getcwd(), "img\\") pathForPrint = path.replace("\\", "\\\\") for file in os.listdir(path): if file.endswith(".png"): fullPath = pathForPrint + file textFile.write( begini...
#TASK-10: #1)Write a Python program for all the cases which can check a string contains only a certain set of characters (in this case a-z, A-Z and 0-9). def check(test_str): import re pattern = r'[a-zA-Z0-9.]' if re.search(pattern, test_str): print('valid') else: print('In...
#from conta import Conta #funciona passar um objeto no init de uma classe python, mesmo sem necessidade de importar para o arquivo class Correntista: def __init__(self, nome, cpf, Conta): self.__cpf = cpf self.__nome = nome #limite está em conta não em correntista #self.__limite = l...
# -*- coding: utf-8 -*- from openerp import models, fields, api import logging _logger = logging.getLogger(__name__) class o2netQuotationItem(models.Model): _name = 'o2net.quotation.item' _description = "o2net - Quotation item" @api.depends('unit_price', 'quantity') def _compute_total_price(self): ...
import pygauth, sys from googleapiclient.discovery import build if len(sys.argv) == 1: print('Please provide a channel id') exit() creds = pygauth.get_user_creds_file('credentials.json', ['youtube']) youtube = build('youtube', 'v3', credentials=creds) resp = {'nextPageToken': None} items = [] x = 0 while 'ne...
# # Copyright 2016 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accom...
import unit_generation import math def DataRegBank(numUnits): f = open('Data_Reg_Bank.v', 'w') f.write(unit_generation.header('DataRegBank', 'For '+str(numUnits)+' units')) #module declaration f.write('module DataRegBank(') for i in range(numUnits): f.write('in{}, '.format(i)) f.wr...
from gym.envs.registration import register register( id='pvz-env-v0', entry_point='gym_pvz.envs:PVZEnv' ) register( id='pvz-env-v1', entry_point='gym_pvz.envs:PVZEnv_V1' ) register( id='pvz-env-v01', entry_point='gym_pvz.envs:PVZEnv_V01' ) register( id='pvz-env-v2', entry_point='gym_...
with open("puzzle_input.txt") as puzzle: a = list(puzzle) master = set() def bag_of_bags(bags): parents = [] for bag in bags: bag_color = bag.split(" bags contain ")[0] for g in a: if bag_color in g: if not g.startswith(bag_color):...
import kivy kivy.require('1.0.6') from glob import glob from random import randint from os.path import join, dirname from kivy.app import App from kivy.logger import Logger from kivy.uix.scatter import Scatter from kivy.properties import StringProperty import numpy as np from PIL import Image from sk...
""" byceps.services.webhooks.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional, Set from ...database import db from .models import OutgoingWebhook as DbOutgoingWebhook from .transfer.models impor...
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ if n==0: return 0 if n==1: return 1 if n==2: return 2 n1=1 n2=2 for i in range(3,n+1): ...
import tensorflow as tf SCALE = 1.0 def block_cole(layer_num, input, num_kernels, is_train): conv1 = tf.layers.conv3d( inputs=input, filters=num_kernels, kernel_size=[3, 3, 3], strides=[1, 1, 1], padding='same', use_bias=True, activation=tf.nn.relu, ...
from django.db import models # 友站模块的models class Category(models.Model): name = models.CharField(max_length=100,verbose_name='类别名称') def __str__(self): return self.name class CoolSite(models.Model): category = models.ForeignKey(Category,verbose_name='所属类别',on_delete=models.CASCADE) u...
#!/usr/bin/env python import unittest from dominion import Game, Card, Piles import dominion.Card as Card ############################################################################### class Card_Patron(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = [Card.CardType.ACTIO...
from pathlib import Path class PathManager: BASE_DIR: Path = Path(__file__).resolve().parents[2] DATA: Path = BASE_DIR / "data" ROOT_DIR: Path = BASE_DIR / 'punctuator' TESTS: Path = ROOT_DIR / "tests" SRC: Path = ROOT_DIR / "src" CREDENTIALS: Path = ROOT_DIR / "credentials" # data direc...
''' Records.Normalize Records.Normalize.Finance. Records.Normalize.Finance.BeyondBanking Records.Normalize.Finance.PaypalFaraja ''' import os, copy, re from Database import Database from utils.CsvObject import * from utils import Container #=============================================================...
# STRAND SORT # It is a recursive comparison based sorting technique which sorts in increasing order. # It works by repeatedly pulling sorted sub-lists out of the list to be sorted and merging them # with a result array. # Algorithm: # Create a empty strand (list) and append the first element to it popping it from th...
import string def verify(isbn): isbn = isbn.replace("-", "") invalid_chars = string.ascii_uppercase.replace("X", "") has_no_invalid_chars = all(not c in isbn for c in invalid_chars) has_correct_length = len(isbn) == 10 has_correct_sum = sum(((10 - i) * int(c) if c !...
import matplotlib.pyplot as plt import numpy as np plt.figure(1) #just plot x values in range 0, 10 step 0.5 x = np.array([-0.99768, -0.69574, -0.40373, -0.10236, 0.22024, 0.47742, 0.82229]) m = len(x) #generate y values x^2-10x+25 y = np.array([2.0885, 1.1646, 0.3287, 0.46013, 0.44808, 0.10013, -0.32952]...
from scrapy.http import Request from scrapy.selector import Selector from scrapy.spider import Spider from yaome.items import YaomeItem class Yaome_spider(Spider): name = 'yaome' allowed_domains = ['yaohuo.me'] cookies = { 'GUID':'9571651818064021', 'ASP.NET_SessionId':'adkuv1yppgpfhkuuyg2nwn55', ...
# -*- coding: utf-8 """Integration tests for command response handling.""" # pylint: disable=missing-docstring,too-few-public-methods from itertools import imap from textwrap import dedent from twisted.internet.defer import inlineCallbacks, fail, succeed from twisted.trial.unittest import TestCase from ...connectio...
# Generated by Django 3.1.4 on 2020-12-11 22:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('facility', '0001_initial'), ('members', '0001_initial'), ] operations = [ migra...
import csv import xml.dom.minidom import sys def GPSCoord(row): # combine lat-longs from their columns, returned as a string. return '%s,%s' % (row['longitude'],row['latitude']) def createPlacemark(kmlDoc, row, order): # This creates a element for a row of data. # A row is a dict. # Added option for place...
__author__ = 'Danyang' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sumNumbers(self, root): result = [] self.dfs(root, "", result) result = [int(element) for element in result] retur...
""" Merge Sort Invented by John Von Neumann: http://en.wikipedia.org/wiki/Merge_sort """ import unittest from random import sample class TestMergeSort(unittest.TestCase): def test_1(self): N = 1000 v = list(reversed(range(N))) self.assertEqual(mergesort(v), list(range(N))) v = sa...
import numpy as np import json import math from PreProcess import current_milli_time, getProcessedConcepts, data_dir concepts, raw = getProcessedConcepts(path_to_concept_file=data_dir + "AllConcepts.txt") with open(data_dir + "captions_train2014.json", "r", encoding="utf-8") as f: dataStore = json.load(f) #annota...
""" Copyright (c) 2014 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Softwar...
#!/usr/bin/python3 def main(): dict1={'1':"green",'2':"black",'3':"white",'4':"red"} print(dict1) key=input("Enter key to remove from dictionary=") if key in dict1: dict1.pop(key) print(dict1) if __name__=='__main__': main()
import os import torch import numpy as np import random def set_seed(seed): os.environ['PYTHONHASHSEED'] = str(seed) torch.manual_seed(seed) # cpu torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # gpu np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic...
# 코드에서 시간 단축할부분: dis가 중복 계산되므로 이것도 dp로 저장해놓고 불러오기 # 차순서 구하려고 뒤로 다시 돌아갈때 앞에서 dp[col][col-1]이 어디서 온건지 전부 저장해놓았으면 # 돌아갈때 row찾는 반복을 안해도 되서 시간이줄듯 # mv=2*W*M 이 자주호출되므로 이것도 저장해놓고쓰기 N=int(input()) W=int(input()) wl=[[1,1],[N,N]] for i in range(W): wl.append(list(map(int,input().split()))) def dis(x,y): return abs(wl...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height ...
import PIL,os from PIL import Image import numpy as np from scipy import linalg as LA class PoolImages(): def __init__(self,directory): #set of images to compare with the testimage self.full_file_paths = self.get_filepaths(directory)#"./photos/training" print('number of training ...
from funcy.flow import silent from funcy.funcs import complement from funcy.seqs import take, first from .account import Account from .instance import shared_steemd_instance from .post import Post from .utils import is_comment class Blog: """ Obtain a list of blog posts for an account Args: ...
""" Class that will contain a document (Basic unit -- "Primary Data-Structure) """ from util import * from sentence import * class Document: def __init__(self, toInfo = None, fromInfo = None, data=None): self.__sentences = [] self.__sCount = -1 #Number of sentences self.__toInfo = to...
from sklearn import linear_model import numpy as np import language_check import pandas as pd import random """ Compute evaluation matrix. """ def weights_matrix(predicted, actual, score_max): actual = np.array(actual) weights = [] for i in range(score_max + 1): row = [] for j in range(...
# -*- coding: utf-8 -*- """ © Copyright 2014. Joon Yang & Jaemin Cheun. All rights reserved. Significantly cuts down the computation by not evaluating a QValue when we discover that it is worse than a previously examined Q value """ import progress class ExpectipruneAgent: def __init__(self, depth = '1'): s...
#!/user/bin/python # Author: Yi Xing, Date: 05/28/2015 # Course: CS6200 Information Retrieval Summer 2015 # This script get each query from elasticsearch, # pass the query to models class import os import re import models from nltk.stem.porter import * from nltk.corpus import stopwords STOPLIST = stopwords.words('e...