text
stringlengths
38
1.54M
from flask import Flask, render_template, request, redirect, url_for, session,\ send_file from forms import DateForm, InstructorForm, StudentForm import datetime import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import os app = Flask(__name__) app.config['SECR...
#! /usr/bin/env python3 import xml.etree.ElementTree as ET import sys import argparse import json arg_parse = argparse.ArgumentParser() arg_parse.add_argument('age', help='The maximum uptime to filter',type=int) arg_parse.add_argument('file', help='Xml file to read. Use - for stdin') args = arg_parse.parse_args() #...
# modified from https://pypi.org/project/full-width-to-half-width FULL_TO_HALF_TABLE = {i + 0xFEE0: i for i in range(0x21, 0x7F)} HALF_TO_FULL_TABLE = {i: i + 0xFEE0 for i in range(0x21, 0x7F)} def f2h(string: str) -> str: """ Convert into half-width. """ return string.translate(FULL_TO_HALF_TABLE) def h2...
from django.db.models.signals import post_save, pre_delete, post_delete from django.dispatch import receiver from problems.models import * import logging logger = logging.getLogger(__name__) def skip_signal_if_required(func): def wrapper(sender, instance, **kwargs): if not getattr(instance, "skip_signa...
#! usr/bin/env python import logging class SendPacket(): def __init__(self): logging.info("Controller is configured to handle packets coming from switch.") def send(self,datapath, msg, port, action): data = None parser = datapath.ofproto_parser if msg.buffer_id == d...
import contextlib @contextlib.contextmanager def test_context(): print('a') yield print('b') def run_context(c): print('one') with c: print('two') yield print('three') print('four') def test_it(): print('U') tc = run_context(test_context()) print('V') ...
import numpy as np def min_pooling(img, out_size): out_img = np.zeros(out_size) ori_h, ori_w = img.shape[:2] out_h, out_w = out_size y_stride = round(ori_h/out_h) x_stride = round(ori_w/out_w) thresh=0.05 for y in range(out_h): for x in range(out_w): if y == out_h-1 and...
class gbXMLServiceType(Enum,IComparable,IFormattable,IConvertible): """ This enumeration corresponds to the systemType attribute in gbXML and is used for specifying the service for the building or space. enum gbXMLServiceType,values: ActiveChilledBeams (22),CentralHeatingConvectors (1),CentralHeatin...
from flask import Flask, request from flask_restful import Resource, Api from similarity.normalized_levenshtein import NormalizedLevenshtein from flask_cors import CORS from fuzzywuzzy import fuzz from operator import itemgetter app = Flask(__name__) CORS(app) api = Api(app) from krs import get_krs_obj companies_arr...
#!/usr/bin/env python """ QC Heads Up Display (HUD) Displays sensor information from and commands sent to the QC Created by: Josh Saunders Date Created: 4/2/2016 Date Modified: 5/2/2016 """ # Python libraries from __future__ import print_function import sys import cv2 import math import numpy as np # We're using ROS h...
# 对数据集进行处理的公共类 class Dataset(object): @staticmethod def normalize_data(datas, idx, mus, stds): ''' 归一化方法:减去均值再除以标准差 ''' datas[:, idx:idx+1] = (datas[:, idx:idx+1] - mus[idx]) / stds[idx] @staticmethod def normalize_datas(datas, mus, stds): ''' 对开盘价、最高价、最低价、收盘价等进行归一...
from typing import List class Solution: def __init__(self): self.cache = {} def cherryPickup(self, grid: List[List[int]]) -> int: return max(0, self.F(grid, 0, 0, 0)) def F(self, grid, r1, c1, r2): n = len(grid) if (r1, c1, r2) not in self.cache: re...
# Generated by Django 2.2.4 on 2019-08-16 19:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='current_cash', ...
from django import forms import pandas as pd import numpy as np from multiselectfield import MultiSelectField from .models import EnrollmentApplication,VizInfoModel from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() class VizInfoForm(fo...
''' The purpose of this function is to simulate and assess the perormance of a 4 stock portfolio Inputs: - Start Date - End Date - Symbols for the equities (eg. GOOG, AAPL, GLD, XOM) - Allocations to the equities at the beginning of the simulation (e.g. 0.2, 0.3, 0.4, 0.1) Outputs: - Standard deviation of daily r...
"""The base Controller API Provides the BaseController class for subclassing. """ import logging from pylons.controllers import WSGIController from pylons.templating import render_mako as render from paste.deploy.converters import aslist from ppdi.model.meta import Session from ppdi.model import ModeratorPin from ...
import logging from DMS.ipredictor.models import ANN, ANNI from DMS.ipredictor import tools from sklearn.preprocessing import StandardScaler import numpy as np import pandas as pd if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) data = tools.data_reader('WTI.xlsx', intervals=T...
# fast IO import sys input = sys.stdin.readline def print(x, end='\n'): sys.stdout.write(str(x) + end) # IO helpers def get_int(): return int(input()) def get_list_ints(): return list(map(int, input().split())) def get_char_list(): s = input() return list(s[:len(s) - 1]) def get_tuple_ints(): r...
#!/usr/bin/python import logging import time from kafka.client import KafkaClient, FetchRequest, ProduceRequest, OffsetRequest DEBUG = True def debug(var): if DEBUG is True: print(var) class KfkClient(object): def __init__(self, ip): self.client = KafkaClient(ip, 9092) self.fd = Non...
import pickle def dump(obj, file_name, *args, **kwargs): """Writes the pickled representation of obj to a file.""" with open(file_name, "wb") as fp: pickle.dump(obj, fp, *args, **kwargs) def dumps(obj, *args, **kwargs): """Alias of pickle.dumps""" return pickle.dumps(obj, *args, **kwargs) def...
# -*- coding: utf-8 -*- """ Created on Wed Mar 8 17:54:44 2017 @author: Mebius """ def powerset_recursion_comp(l): # Base case: the empty set if not l: return [[]] # The recursive relation # Do a powerset call for l[1:] # Add lists of all combinations of the 1st element (l[0]...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-07 20:53:18 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def exist(self, board, word): if not board or not word: return False visit = [[0 for _ i...
import os import re try: # use C-compiled module for python 2.7 (3.3 will do that by default) import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET __AUTHOR__='Lifecell OSS group' __COPYRIGHT__='Lifecell UA Company, 2018 Kiev, Ukraine' __version__ = '1.2' __license__ = ...
# coding: utf-8 import json import urllib from helper import http from helper import utils PLATFORM_NAME = 'lewan' APP_ID = '11111' PAY_KEY = 'xxxxxxxxxxxxxxxxxxxxxx' GET_USERINFO_URL = 'http://www.lewanduo.com/mobile/user/verifyToken.html' PUBLIC_KEY = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...
#!/usr/bin/env python PKG = 'seabotix' import roslib; roslib.load_manifest(PKG) import sys import numpy as np from math import * import std_msgs.msg import rospy from resources import tools from kraken_msgs.msg import thrusterData6Thruster from kraken_msgs.msg import thrusterData4Thruster from kraken_msgs.msg impo...
''' HACKTASK 2 # I want to write a short Python script that uses regular expressions to extract information from the full transcript of the Ninth Democratic debate in Las Angeles, from February 19, 2020. # First, turn this script from https://www.nbcnews.com/politics/2020-election/full-transcript-ninth-democratic-deba...
from search.model.impl.local.HillClimbingSearch import HillClimbing from search.model.impl.local.HillClimbingSearch import StochasticHillClimber from problems.model.impl.EightQueensProblem import EigthQueensProblem from problems.model.impl.EightQueensProblem import EightQueensHeuristic p = EigthQueensProblem() h = Eig...
from pointTransform import * import subprocess import glob #files = glob.glob('image_*.png') groundtruth=50 #files=glob.glob('images/smaller/image*.png') #groundtruth = 36 #files = glob.glob('images/larger/image*.png') groundtruth=36 #files=glob.glob('images/newfullres/fullres*.png') # Files were actually mislabe...
import datetime from QA.AppDatabaseTester import AppDatabaseTester class AppMergeTest(AppDatabaseTester): def __init__(self, config): end_date = datetime.datetime.strptime(config['DATES']['END_DATE'], '%Y%m%d') super().__init__(config, 'DATABASE', datetime.date(year=1976, month=1, day=1), end_dat...
from setuptools import setup, find_packages from exchanges import __version__ setup( name='exchanges', version=__version__, description='exchange adapters', author='Aye-Jay', include_package_data=True, packages=find_packages(), install_requires=[ 'Flask==0.12.2', 'pandas==0....
#Python内置的访问数据库 import requests #pyecharts图表库导入(Map地图,Line折线图,Bar柱形图) from pyecharts import Map,Line,Bar #将json导入 import json #生成地图使用的数据--腾讯 mapUrl="https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery34100282751706540052_1583633749228&_=1583633749229" #发送请求获取数据--地图数据 mapData=requests.get(mapUrl).t...
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # 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 ...
from collections import deque import numpy class LinearFeedbackShiftRegister(object): """ Implements a Linear Feedback Shift Register. Given some initial values and recurrence relation coefficients, generates the sequence given by some specified recurrence relation. """ def __init__(self,...
# -*- coding:utf-8 -*- class Solution: def maxInWindows(self, num, size): # write code here if size == 0: return [] if not num: return None length = len(num) return_res = [] for i in range(length-size+1): res = num[i:i+size] ...
import pandas as pd import numpy as np a=pd.Series([1,2,3,4]) print(a) b=pd.Series([1,2,3,4],index=(10,20,30,40)) print(b) print(a[2]) print() c=pd.Series({"a":1,"b":2,"c":3}) print(c) print(c["b"]) print() print() d=pd.Series(3,index=(1,2,3,4,5)) print(d) print() print()
def FindPeaks(self,norm=-1,dograph=False): """Returns number of 'significative peaks' in an image.""" # IMPORT STUFF import numpy as num from pdb import set_trace as stop from numpy.nd_image import shift from numpy.nd_image.filters import uniform_filter import pyfits import os #from ...
# Import the modules from pathlib import Path from datetime import datetime import time from textwrap import wrap from functions import * data_folder = Path("in/") file_to_open = data_folder/"Python_exercise1.xlsx" data = obtain_excel_data(file_to_open, "data_table") for i in range(0, len(data)): msg = data.at[i...
class ExitStatus: OK = 0 INVALID_RLI_CONFIG = 1 NO_RLI_CONFIG = 2 GITHUB_EXCEPTION_RAISED = 3
# -*- coding: utf-8 -*- ############################################################################# # # Cybrosys Technologies Pvt. Ltd. # # Copyright (C) 2021-TODAY Cybrosys Technologies(<https://www.cybrosys.com>) # Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>) # # You can modify it under...
figure_type = str(input()) if figure_type == "square": side = float(input()) result = side * side elif figure_type == "rectangle": sideA = float(input()) sideB = float(input()) result = sideA * sideB elif figure_type == "circle": radius = float(input()) from math import pi result = pi *...
import csv import psycopg2 import os """ This is a ONE TIME run script to enter in the SREW station details into the database. Enter all SREW stations into database for which we have a lat long for In other words enter all valid SREW stations into the local database Valid station IDs are contained within a static fi...
# -*- coding: utf-8 -*- """ MathSlider.py Created on Wed Dec 28 07:45:24 2016 @author: slehar """ import matplotlib.pyplot as plt from matplotlib.widgets import Slider from matplotlib.widgets import RadioButtons from matplotlib import animation import numpy as np import sys from collections import deque x = 0.0...
import unittest from common import read_file from ele_operation.FMS.sys_manage import cust_payway_set from ele_operation import py_operation import start_program import time import os from HTMLTestReportYIF import HTMLTestRunner from ddt import ddt,data,unpack from common.log_decorator import * o = py_operation.operati...
import ksensors import time import messageboard k = ksensors.ksensors() state = False # False = STOP!; True = GO mb = messageboard.MessageBoard("collision") # print(str(mb)) def goodPosition(x, y): # area1 = # bottom left : 108, 85px # top right : 132, 67px # area2 = # bottom left: 180, 85px # top ...
import logging import time from multiprocessing.dummy import RLock from operator import itemgetter import psycopg2 from decorators import synchronized class Database: PROFILES_FIELDS = ['owner_id', 'first_name', 'last_name', 'sex', 'screen_name', 'last_seen', 'bdate', 'verified', ...
import sys import numpy as np from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn import metrics from utils import * if __name__ == "__main__": if len(sys.argv) <= 2: print ("Usage: python kmean.py [creditCard|MNIST] [nonReduced|PCA|ICA|RP|MI]") exit(1) file...
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the rights to use, co...
import psycopg2 as pg2, psycopg2.extras as pg2_extras import web conn = pg2.connect(host="localhost", port=5432, dbname="test_db", user="b") cur = conn.cursor(cursor_factory=pg2_extras.DictCursor) stories = web.get_eastmoney_stories() web.write_to_db_china_news(stories, cur, conn) cur.close() conn.close()
import unittest import anuga import numpy import os boundaryPolygon=[ [0., 0.], [0., 100.], [100.0, 100.0], [100.0, 0.0]] verbose=False class Test_boundary_flux_integral_operator(unittest.TestCase): def setUp(self): pass def tearDown(self): try: os.remove('test_boundaryfluxinteg...
import cv2 def redim(img, largura): # função para redimensionar uma imagem alt = int(img.shape[0] / img.shape[1] * largura) img = cv2.resize(img, (largura, alt), interpolation=cv2.INTER_AREA) return img # Cria o detector de faces baseado no XML df = cv2.CascadeClassifier('haarcascade/haarcascade_fronta...
import unittest import main class TestMain(unittest.TestCase): def test_2(self): self.assertEqual(main.calc(111111), True) self.assertEqual(main.calc(223450), False) self.assertEqual(main.calc(123789), False) self.assertEqual(main.calcAdv(112233), True) self.assertEqual(main...
class Solution: # @param A, a list of integers # @return an integer def firstMissingPositive(self, A): arrayLen = len(A) for idx in range(0, arrayLen) : if A[idx] < 1 : continue temp = A[idx] A[idx] = -1 if temp <= ar...
import md5 from sys import exit class Position(object): def __init__(self, x, y, path_taken): self.x = x self.y = y self.path_taken = path_taken self.hash = "pgflpeqp" + path_taken def test_new_direction(self): if self.x == 4 and self.y == 4: solution = se...
def readline(filepath): input = [] with open(filepath) as fp: line = fp.readline() cnt = 1 while line: input.append(line) line = fp.readline() cnt += 1 return input def main(): stopwords = ['bags.','no','other',',','bag.','1','2','3','4','5','6',...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 30 00:32:03 2017 @author: mmr """ import bs4 import sys import requests def get_result(): df = requests.get('http://ketqua.net').text soup = bs4.BeautifulSoup(df, 'lxml') number_award = {0: 1, 1: 1, 2: 2, 3: 6, 4: 4, 5: 6, 6: 3, 7: 4} ...
import random def quick_sort(arr): def sort(low, high): if high <= low: return mid = partition(low, high) sort(low, mid - 1) sort(mid, high) def partition(low, high): pivot = arr[(low + high) // 2] while low <= high: while arr[low] < piv...
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 21:17:10 2021 @author: HP """ import pickle import math import numpy as np import json import numpy as np from scipy.stats import entropy from math import log, e import pandas as pd mem_event_1=pickle.load(open("mem_event_1","rb")) hcount=pickle...
from typing import Union from probability.custom_types.external_custom_types import AnyFloatMap from probability.custom_types.internal_custom_types import AnyBetaMap, \ AnyDirichletMap from probability.distributions import Beta, Dirichlet class BayesRuleMixin(object): _prior: Union[float, Beta, AnyFloatMap,...
# Lowest common ancestor in binary tree or BST # https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ - For python BST code # https://www.youtube.com/watch?v=13m9ZCB8gjw&t=15s - Video # Key learnings : # 1: Implement Binary tree fast in python # 2: Two approaches for this problem # 1: Print path and...
from django.contrib import admin from qbeats_home.models import mrnStream admin.site.register(mrnStream)
import re import subprocess ROOT_FILENAME = 'throwback' f_p8 = open(ROOT_FILENAME + '.p8', 'r+', newline='\n') lua = open(ROOT_FILENAME + '.lua', 'r', newline='\n').read() p8 = f_p8.read() new_p8 = re.sub(r'__lua__\n.*\n__gfx__', '__lua__\n{}\n__gfx__'.format(lua), p8, flags=re.DOTALL) f_p8.seek(0) f_p8.write(new_p8...
# Generated by Django 2.0.2 on 2018-02-16 19:28 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
words = input().split() pal_word = input() pal_list = [el for el in words if el == el[::-1]] found_word = [word for word in pal_list if word == pal_word] counter = 0 for el in pal_list: if el == pal_word: counter += 1 print(pal_list) print(f"Found palindrome {counter} times")
__author__="Aurelija" __date__ ="$2010-07-15 12.27.32$" import re from os.path import join from Utilities.ReleaseScripts.cmsCodeRules.pathToRegEx import pathsToRegEx, pathToRegEx def getFilePathsFromWalk(osWalkResult, file, exceptPaths = []): listOfFiles = [] file = pathToRegEx(file) for root, dirs, fi...
from django.conf import settings from django.utils.hashcompat import md5_constructor def get_anticaptcha_token(): # The purpose of this anticaptcha token is just to generate # a random value so we simply hash something that's always # available, but different in most django installs return md5_constructor(settings...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import opal.models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('anaesthetic', '0021_auto_20171022_1651'), ] operations = [ migrations.Cr...
#:1 Video to pictures converter import ctypes frame = 1 FrameNumber = str(frame) directory = "C:\CuratedWallpaper" + "\\" imagename = "000" imageformat = ".png" imagePath = directory + imagename + FrameText + imageformat def changeBG(imagePath): ctypes.windll.user32.SystemParametersInfoW(20, 0,...
#*- coding: utf-8 -*- # """Tickets System Usage: tickets [-dgkzt] <from> <to> <date> Options: -h --help Show this screen. -d 动车 -g 高铁 -k 快速 -z 直达 -t 特快 """ import requests import colorama from docopt import docopt from stations import Station...
import pygame from plane_sprites import * class PlaneGame(object): """飞机大战主游戏""" def __init__(self):#时间地点人 print("游戏初始化") # 1. 创建游戏的窗口 self.screen = pygame.display.set_mode((480, 700)) # 2. 创建游戏的时钟 self.clock = pygame.time.Clock() # 3. 调用私有方法,精灵和精灵组的创建 self.__create_sprites() def start_game(self): ...
import geopandas as gpd import pandas as pd import requests import click @click.command() @click.option('--shapefile', prompt='Please point to associative shapefile', default='BoundaryShapefiles/Ecological Sub-sections/tx_subsection.shp', help='Original Shapefile Geometries.') def find_bou...
import logging import sentry_sdk from sentry_sdk.integrations.celery import CeleryIntegration from sentry_sdk.integrations.flask import FlaskIntegration from sentry_sdk.integrations.logging import LoggingIntegration from sentry_sdk.integrations.redis import RedisIntegration from sentry_sdk.integrations.sqlalchemy impo...
# Generated by Django 3.1 on 2020-10-23 17:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0086_auto_20201023_1002'), ] operations = [ migrations.AddField( model_name='ruggroup', name='type', ...
from .base import * DEBUG = True SECRET_KEY = '-5og^w3c^tcsp^n)9wk+2bvb(2j_vm=8o38j8t8@r4q%b&j=y_' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ALLOWED_HOSTS = ['localhost', 'crypstation.test'] # to execute tasks locally synchronous # CELERY_ALWAYS_EAGER = True
"""model utils""" from PIL import Image import numpy as np import keras.backend as K def resize_image(image, size): """Resize image with aspect ratio kept image: Image, input image size: tuple of int, (w, h) target size Return: resized image """ iw, ih = image.size w, h = size ratio ...
from datetime import datetime import factory import pytz from factory import fuzzy from factory.django import DjangoModelFactory from .models import Temperature # Defining a factory class TemperatureFactory(DjangoModelFactory): class Meta: model = Temperature time = factory.fuzzy.FuzzyDateTime( ...
# Create your models here. from __future__ import unicode_literals from django.db import models from django_mailbox.signals import message_received from django.dispatch import receiver class MailStorage(models.Model): sender = models.CharField(max_length=255) subject = models.CharField(max_length=255) date = model...
import sys import os import hashlib #read from terminal input = sys.argv binaryFile = input[1] #convert to hex: search for "FFD8FFE0" print("type", type(binaryFile)) f = open(binaryFile, "rb") data = f.read() # print(data) path = os.getcwd() print ("The current working directory is %s" % path) try: os.mkdir(path...
# Generated by Django 2.2.7 on 2020-02-18 11:26 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MatricResult', fields=[ ('s_id', models.Aut...
import asyncio from utils.vars import * from utils.helper import get_nonce from web3 import Web3, exceptions from utils.notification import send_notification from utils.helper import check_balance, check_slp_balance import json w3 = Web3(Web3.HTTPProvider(RONIN_PROVIDER_FREE)) with open("entity/abis/slp_abi.json") as ...
from Testing import testPenData, testCarData, average, stDeviation import csv with open('Pen0.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Data Type', 'Perceptrons', 'Average Accuracy',...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class SearchForm(FlaskForm): searchfield = StringField('Search field', validators=[DataRequired()]) searchbutton = SubmitField('Search')
from django.shortcuts import render, redirect #from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm,ContactsUpdateForm from .models import Profile impor...
""" Module for Linear N-Dimensional Interpolation """ import numpy as np from scipy.interpolate import LinearNDInterpolator as LinearNDInterp from scipy.interpolate import interp1d from .approximation import Approximation class Linear(Approximation): """ Multidimensional linear interpolator. :param flo...
from test_sort import Tests # Elements on the left of the pivot should be lower and the elements on # the right side of the pivot should be greater def quicksort(l): left = [] right = [] equal = [] if len(l) > 1: pivot = l[0] for elem in l: if elem < pivot: ...
import os, uuid class TempFile: def __init__(self, directory): self.filename = os.path.join(directory, uuid.uuid4().hex) self.f = open(self.filename, 'w+b') def __del__(self): self.f.close() os.remove(self.filename) def get(self): return self.f def read(self):...
'''Convert a grammar to CNF and print it to stdout.''' from cfg import core, cnf CFG = core.ContextFreeGrammar CNF = cnf.ChomskyNormalForm G = CFG(''' S -> ASA | aB A -> B | S B -> b | ''') print 'G:' print G print print 'G\':' print CNF(G)
""" Title: Linked list random node Problem: Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently ...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Standard imports import os.path import datetime import time # Django imports from django.test import TestCase from django.test import Client from django.conf import settings from django.utils import timezone # App imports from imageboard.models import Board, Thread, Post import imageboard.exceptions as i_ex from c...
""" This module contains tools for handling dataset specifications. """ import copy from typing import Union import platform version = platform.python_version() if float(version[:3]) <= 3.6: raise EnvironmentError('At least Python 3.7 is needed for ordered dict functionality.') from ruamel.yaml import YAML class D...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from datetime import datetime import argparse from os import path import sys import tensorflow as tf import captcha_model as captcha from tensorflow.python.client import device_lib FLAGS...
from ..generate_data_structures import * from ..main import * from algorithm import * import argparse import re import os parser = argparse.ArgumentParser('Multiple sections extension') parser.add_argument('constraints') parser.add_argument('students') parser.add_argument('schedule') args = parser.parse_args() const...
import unittest from html_page import HtmlPage class TestHtmlPage(unittest.TestCase): def test_default(self): html_page = HtmlPage() rendered = html_page.render() self.assertEqual(rendered, "<p></p><p><img src=\"\"/></p><p></p>") def test_with_content(self): html_page = HtmlPa...
import requests import time import json def SendMsg(host: str, current_qq: int, send_content: str, to_user: int): url = "%s/v1/LuaApiCaller?qq=%d&funcname=SendMsg&timeout=10" % (host, current_qq) payload = "{\n \"toUser\":%d,\n \"sendToType\":1,\n \"sendMsgType\":\"TextMsg\",\n \"content\":\"%s\"," \ ...
# Change making coins = [25,10,5,2,1] n = 10 def make_change(coins, target): paths = [] memo = set() def explore_paths(total, combo={}): nonlocal paths # Base cases if total > target: return False if total == target: paths.append(combo) # Rec...
import utime import machine import json import ubinascii from app.motor import motor from app.halleffect import halleffect class train(): def __init__(self, mqtt): #variables self.status = None self.hops = 1 self.speed = -0.3 #self.direction = 0 self.on_checkpoint = ...
from worldbankapp import app import json, plotly from flask import render_template, request, Response, jsonify from scripts.data import return_figures @app.route('/', methods=['POST', 'GET']) @app.route('/index', methods=['POST', 'GET']) def index(): country_codes = [['Lithuania', 'LTU'], ['Estonia', 'EST'], ['L...
# -*- coding: utf-8 -*- from flask_assets import Environment css_cdnjs = ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css', 'https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1...
import utils # quicksort def swap(A,i,j): tmp=A[i] A[i]=A[j] A[j]=tmp def quicksort(A,p,q): if p<q: i=partition(A,p,q) quicksort(A,p,i-1) quicksort(A,i+1,q) def quicksort_iterative(A,p,q): S=[] # stack S.push((p,q)) while (len(S)>0): p,q = S.pop() if (p<q): i=partition(A,p,q) S.push(A,i+1,q)...
import logging from loader import db # задаем логи для того что-бы код дебажить logging.basicConfig(level=logging.INFO) async def on_startup(dp): import filters import middlewares filters.setup(dp) # Устанавливает фильтры middlewares.setup(dp) # Устанавливает middleware await db.create_table()...