text
stringlengths
8
6.05M
""" Time/Space Complexity = O(N) """ class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: d = dict() for i in pieces: if len(i) == 1: d[i[0]] = None else: d[i[0]] = i[1:] li...
import sys import pickle class Margaret: def __init__(self): self.d = {} try: self.d = self.deserialize() except FileNotFoundError: pass def prompt(self): # self.d = {'Margaret': []} self.deserialize() message = input("<") # try: # self.d['Margaret'].append(messag...
# Copyright 2019 3YOURMIND GmbH # 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, soft...
# Author : 柠檬班-亚萌 # Project : scb23 # Time : 2021/8/26 20:02 # E-mail : 3343787213@qq.com # Company : 湖南零檬信息技术有限公司 # Site : http://www.lemonban.com # Forum : http://testingpai.com ''' 1、编写自动化测试用例,代码自动读取数据 # read_data() 2、发送请求,得到响应结果 # func() 3、执行结果(响应结果) VS 预期结果 4、写入最终的真实结果到测试用例 # write_data() ''' import reques...
# -*- coding: utf-8 -*- import config import json import glob import jpglitch import numpy as np from io import BytesIO import os import PIL.Image import random import re import requests import subprocess as sub import sys from urllib.parse import quote import uuid from wand import image as wand_image s = requests....
class NumArray(object): def __init__(self, nums): self.dp = [0] * (len(nums) + 1) # C[i] self.n = len(nums) # n is used for add self.nums = nums # a[i], it will be update many times for i in range(len(nums)): self.add(i+1, nums[i]) # start from 1 def add(self,...
import configparser import logging import os import time import scripts.baseseeds as bs from scripts.graph import * dirname = os.path.dirname(__file__) conf = configparser.ConfigParser() conf.read(dirname + '/resources/config') config = conf['kmeans'] class AgregGraph(Graph): # Children class of Graph, for this sp...
f=open("C:/Users/Lenovo-PC/Desktop/New folder/sample.txt",'a') f.write("dept: BE-ECE") f.close() f=open("C:/Users/Lenovo-PC/Desktop/New folder/sample.txt",'r') print(f.read()) count =0 fp =open("C:/Users/Lenovo-PC/Desktop/New folder/sample.txt") for line in fp: count += 1 print((line.strip()))
from link_checker import link_checker import sys import json from decimal import Decimal import time lc = link_checker(sys.argv[1], sys.argv[3]) lc.check_site(sys.argv[2]) d = {'checked_links':lc.checked_links, 'bad_links':lc.bad_links} finish_time = time.time() d['time'] = finish_time print(d) json_file = open('...
"""Author Arianna Delgado Created on June 23, 2020 """ """Product of elements in two lists using list comprehension. """ #Decles three lists. first_list = [1,2,3,4,5] second_list = [6,7,8,9,10] empty_list = [] #Uses loop to solve the proplem. '''for i in range(len(first_list)): empty_list.append(first_list[i] *...
from sklearn.neural_network import MLPClassifier import pandas as pd import numpy as np import joblib def test_neuralnet(clf,X_test,y_test): print(clf.score(X_test,y_test)) if __name__ =='__main__': data = pd.read_csv("data_set.csv") msk = np.random.rand(len(data)) < 0.6 train = data[msk] test =...
# ex) a = [1, 2, 3, 4, 5] def solve(arr): sum = 0 for x in arr: sum += x return sum
for i in range(1,8,2): for j in range(7,i,-2): print(" ",end='') for j in range(1,i+1): print("*",end='') print() for i in range(5,0,-2): for j in range(5,i-1,-2): print(" ",end='') for j in range(1,i+1): print("*",end='') print()
__all__ = ['Airview', 'Opportunistic'] from .Airview import * from .Opportunistic import *
"""empty message Revision ID: 2fad9019718 Revises: ef462ea10e Create Date: 2016-10-25 19:49:59.268902 """ # revision identifiers, used by Alembic. revision = '2fad9019718' down_revision = 'ef462ea10e' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please...
""" Asset mutations """ from typing import List, Optional, Union from functools import partial from typeguard import typechecked from ...helpers import (Compatible, convert_to_list_of_none, format_metadata, format_result, ...
from random import choice """Initiates game""" print("Welcome to battleship!") print("Menu:") print("1. Single-player \n 2. Multi-player \n 3. Help \n 4. Credits \n") game_choice = input() if game_choice == "1": """makes a board""" rows = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] """...
import tornado.web class ApiPageHandler(tornado.web.RequestHandler): def get(self): self.render("api.html")
from networkz.algorithms.chordal.chordal_alg import *
import json from datetime import datetime from main_index.captcha.image import ImageCaptcha from django.core.paginator import Paginator from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect from main_index.car import Car, Car_item from main_index.models import TBook, TCatego...
# This file was automatically created by FeynRules 2.3.29 # Mathematica version: 10.0 for Mac OS X x86 (64-bit) (September 10, 2014) # Date: Thu 27 Jul 2017 17:29:36 from object_library import all_lorentz, Lorentz from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot try: import form_fa...
name = "cesar" print(name[2]) name1 = ["cesar", "gil", "ben"] print(name1[2])
import copy import os import chainer import chainer.functions as F import numpy as np from chainer import DictSummary from chainer import Reporter from chainer.training.extensions import Evaluator from overrides import overrides from sklearn.metrics import f1_score import config class ActionUnitEvaluator(Evaluator)...
import numpy as np def gaussian_xy(x_limit, y_limit): """ generate random (x,y) coordinates using Gaussian distribution; the mean of the Gaussian if set to the middle of the max - min range; the std of the Gaussian is set to a quarter of the max - min range; rejection sampling is used if the gener...
class Solution: def candy(self, ratings) -> int: left = [0]*len(ratings) right = [0]*len(ratings) for i in range(1,len(ratings)): if ratings[i]>ratings[i-1]: left[i]=left[i-1]+1 count = left[-1] for i in range(len(ratings)-2,-1,-1): ...
## # Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. # # File: TrafficNetworkModel.py # # Purpose: Demonstrates a traffix network problem as a conic quadratic problem. # # Source: Robert Fourer, "Convexity Checking in Large-Scale Optimization", # OR 53 --- Nottingham 6-8 Septembe...
import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import OneCycleLR import matplotlib.pyplot as plt #%matplotlib inline import numpy as np import torchvision import torchsummary from torchsummary import ...
#在windows平台下面fast_FDS没有配置好因此不配置了。 from django.core.files.storage import Storage from fdfs_client.client import Fdfs_client class FDFSStorage(Storage): '''FDFSStorage文件存储类''' def _open(self,name,mode='rb'): '''打开文件时使用''' pass def _save(self,name,content): ''' 保存文件时使用 ...
from django.contrib import admin from Insta.models import Post, PostTwo, InstaUser # Register your models here. admin.site.register(Post) admin.site.register(PostTwo) admin.site.register(InstaUser)
''' Problem Statement Given a set of numbers that might contain duplicates, find all of its distinct subsets. Example 1: Input: [1, 3, 3] Output: [], [1], [3], [1,3], [3,3], [1,3,3] Example 2: Input: [1, 5, 3, 3] Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3], [3,3], [1,3,3], [3,3,5], [1,5,3,3] ''' def g...
from django.db import models # Create your models here. class Project(models.Model): name = models.CharField(max_length=50,verbose_name='Nome') navers = models.ManyToManyField('navers.Naver', related_name='projects') user = models.ForeignKey('users.User',related_name='projects_list',on_delete=models.PROTEC...
from functools import cached_property class Clipboard: """ The clipboard holds a url that should be copied and then pasted. The url is expected to be stored in a token that has been created by :meth:`onegov.core.request.CoreRequest.new_url_safe_token`. The reason behind this is that the url is used t...
import requests resp = requests.get('http://www.google.com/pic') #if resp.status_code != 200: # This means something went wrong. #raise ApiError('GET /tasks/ {}'.format(resp.status_code)) # for todo_item in resp.json(): # print('{} {}'.format(todo_item['id'], todo_item['summary'])) assert resp.status_code=...
from builtins import * aa_name3s = 'ala cys asp glu phe gly his ile lys leu met asn pro gln arg ser thr val trp tyr'.upper().split() rif_atype_names = ('CNH2 COO CH1 CH2 CH3 aroC Ntrp Nhis NH2O Nlys Narg Npro OH ONH2 OOC S'.split() + 'Nbb CAbb CObb OCbb Hpol Hapo Haro HNbb VIRT CH0 HS NtrR SH1'....
#-*- coding: utf-8 -*- import turtle import math import random # 배경설정 screen = turtle.Screen() screen.bgcolor("black") screen.title("Turtle Run Ver.2") # 가장자리 그리기 mypen = turtle.Turtle() mypen.penup() mypen.setposition(-300, -300) mypen.pendown() mypen.pensize(3) for side in range(4): mypen.forward(600) mypen.le...
import shutil, os import ROOT from array import array import math import pickle import numpy as np import copy from TopEFT.Tools.user import combineReleaseLocation as releaseLocation import re def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. http://stackoverflow.c...
A='!'+'"#$%&'+"'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" x = A.find(input()) if x in range (15,25): print('YES') else: print('NO')
import sqlite3 import csv import os import time import traceback import sys from whine_classes import WhineBottle import json from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # gebruiken we overal dus global db_path = os.environ....
import sys class Grader(): def calCulate(_self,g): if int(g)>90: return "A" elif int(g)>80 and int(g)<90: return "B" else: return "C" def genCard(_self,g,name,a): msg = str(name) msg = msg+"@fullsail.edu" msg = msg+"\nHere is your grade for "+str(a)+" assingment: "+_self.calCulate(g) msg = ms...
from django.contrib import admin # @UnresolvedImport from .models import Shop, Item # Register your models here. admin.site.register(Shop) admin.site.register(Item)
from django.db import models from seller.models import Seller # Create your models here. class Marketplace(models.Model): name = models.CharField(max_length=100) document = models.CharField(max_length=20) phone_number = models.CharField(max_length=20) email = models.EmailField(max_length=200) selle...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-06 21:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Hackers', '0002_auto_20160309_2244'), ] operations = [ migrations.AlterField...
'''Student Repository Data repository of courses, students, and instructors Author: Ming-Wei Hu Last Updated: November 16th, 2020 ''' # Imports from datetime import datetime, timedelta from typing import Iterator, Tuple, List, Dict, Set, IO, Any, Callable, Optional from decimal import Decimal, ROUND_HALF...
""" Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostar que tipo de triângulo será formado: - Equilátero: todos os lados iguais - Isóceles: dois lados iguais - Escaleno: todos os lados diferentes """ r1 = int(input('Valor da reta 1: ')) r2 = int(input('Valor da reta 2: ')) r3 = int(input('Valor da re...
from django.contrib import admin from django.urls import path,include,re_path from . import views urlpatterns=[ re_path(r'catalog^$',views.catalog,name='catalog'), ]
from tests.share.normalize.factories import ( Agent, AgentIdentifier, Article, CreativeWork, Institution, Organization, Patent, Person, Preprint, Publication, Tag, ThroughTags, WorkIdentifier, ) from tests.share.normalize.factories import FactoryGraph class TestShor...
import threading, queue import time import zmq import logging import sys import json sys.path.append("") from utils.logger import config_logger # from logger import config_logger class BasicThread(threading.Thread): ''' This is BasicThread configuration that will be implemented in middleware thr...
#!/usr/bin/env python3 # # Development Order #5: # # This is the meat and bones of the tool, where the actual desired # commands or operation will be run. The results are then recorded # and added to the 'results' JSON data, which will then be sent # back to the test. Both system and api are able to be used here. # # s...
import sys sys.path.append('../DeepIV/experiments/') import data_generator import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_context('notebook',font_scale=1.3) t_grid_size = 1000 max_n = 7 x = np.concatenate([ np.tile(np.linspace(0,10,t_grid_size),max_n)[:,np.n...
r= float(input("Enter Radius of a circle:")) Area= 3.14*r*r print("Area of circle is:",Area)
#break与continue语句:计算小于100的最大素数。 for n in range(100, 1, -1): if n%2 == 0: continue for i in range(3, int(n**0.5)+1, 2): if n%i == 0: #结束内循环 break else: print(n) #结束外循环 break
''' Created on Sep 21, 2015 @author: Jonathan Yu ''' def getMessage(original): words = original.split(" ") vowels = ["a", "e", "i", "o", "u"] onlyVowels = True message = "" for word in words: letters = list(word) for k in range(len(letters)): if letters[k] not in vowels...
from django.urls import path from . import views urlpatterns = [ path('facilitator/dashboard/explore', views.facilitator_Dashboard_explore_courses_page, name="explorecourses"), path('facilitator/dashboard/earnings/<int:pk>/', views.facilitator_Dashboard_myearnings_page, name="earnings"), path('facilitator/...
def tester(start): state = start def nested(label): print(label,state) return nested if __name__ == '__main__': F = tester(0) print(F.__name__) F('spam') F('ham')
in_file = open('input_2.txt', 'r') # in_file = open('test_2.txt', 'r') def split(line): rules, v = line.split(': ') range, char = rules.split(' ') mini, maxi = map(int, range.split('-')) return [mini, maxi, char, v] def isValid(s): mini, maxi, char, string = split(s) return mini <= string.count(char) <= maxi r...
import time from selenium import webdriver import xlsxwriter driver = webdriver.Firefox(executable_path=r"E:\geckodriver.exe") loop_counter = 1 count = 0 url = "https://www.yellowpages.com.au/search/listings?clue=motorcycle+shop&locationClue=Victoria&lat=&lon=" category_name = input("Enter category name : ") state_nam...
import scraping import os from bs4 import ResultSet, Tag def test_imports_request(): assert hasattr(scraping, 'requests'), \ "Import the requests library at the top of your scraping.py file" def test_scraping_defines_url(): assert hasattr(scraping, 'url'), \ "Define a variable called `url` tha...
import numpy as np import matplotlib.pyplot as plt plt.scatter(2, 4) plt.show()
import numpy as np from cs285.infrastructure.utils import convert_listofrollouts class ReplayBuffer(object): def __init__(self, max_size=1000000): self.max_size = max_size # store each rollout self.paths = [] # store (concatenated) component arrays from each rollout sel...
#This file is part of the nodux_account_voucher_ec module for Tryton. #The COPYRIGHT file at the top level of this repository contains #the full copyright notices and license terms. from decimal import Decimal from trytond.model import fields from trytond.pool import Pool, PoolMeta __all__ = ['Move', 'Line'] __metacla...
from mjxcommon import mjxvar import os cron_item_sync_sp = "10 * * * * python3 ~/sroot/bin/sync_srootpws.py sp" subscrib_daemon = '10 * * * * python3 $SROOT/bin/check_and_start.py subscriber "python3 $SROOT/bin/mydistesys/subscriber.py all"' distserver_daemon = '#10 * * * * python3 $SROOT/bin/check_and_start.py distse...
import os import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': dj_database_url.config(), } DATABASES['default']['OPTIONS'] = { 'autocommit': True, } # Sendgrid config EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ['SENDGRID_...
"""User model""" from sqlalchemy import Column, Integer, BigInteger, ForeignKey, DateTime, Float, VARCHAR from models.db import Model from models.base_object import BaseObject class Initialsamples(BaseObject, Model): id = Column(Integer, primary_key=True) ItemNo = Column(Integer) UserNo ...
#! /usr/bin/env python ########################################################################################## # PostColorTrack_MCHE470_Fall2013_cv2.py # # Script to process Mini-Project 3b videos # # Requires OpenCV # # Created: 11/2/13 # - Joshua Vaughan # - joshua.vaughan@louisiana.edu # - http://ww...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools from functools import reduce def pi(N): oddnumber = itertools.count(1, 2) oddnumberPN = itertools.takewhile(lambda n: n < 2 * N, oddnumber) return reduce(lambda x, y: x + y, list(map(oddmap, list(oddnumberPN)))) def oddmap(n): if (n // ...
# Generated by Django 2.2.2 on 2019-11-18 02:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('teachingtask', '0008_teachingtask_is_changed'), ('student', '0003_auto_20190924_1210'), ('skill_register', '...
import pytest from share.transform.chain.utils import contact_extract @pytest.mark.parametrize('input_text, output_text', [ ('Contact: Lisa Floyd-Hanna (Herbarium Curator); Becky McLemore (Collections Manager) (collections@naturalhistoryinstitute.org)', {'email': 'collections@naturalhistoryinstitute.org', 'name':...
""" this question is similar with q16. please reference q16 """
#! /usr/bin/env python # This script assumes the Category and Attribute Prediction benchmark # is in the working directory, in a subdirectory called 'DATA', and # completely uncompressed import os import sys import random import make_sample LIST_CATEGORY_IMG_FILE = os.path.join('DATA', 'Anno', 'list_category_img.tx...
class Solution: def convertToTitle(self, n): """ :type n: int :rtype: str """ result = [] while n != 0: remainder = n%26 if remainder == 0: result.insert(0, 'Z') n = n//26-1 else: resu...
class Node: """ Класс для узла списка. Хранит значение и указатель на следующий узел. """ def __init__(self, value=None, next=None): self.value = value self.next = next def __str__(self): return str(self.value) def __repr__(self): return str(self.v...
class Solution(object): def flatten(self, root): if not root: return None node = root while node: if node.left: rightmost = node.left while rightmost.right: rightmost = rightmost.right rightm...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import copy import numpy as np from torchvision import datasets, transforms import torch import random from utils.sampling import mnist_iid, mnist_noniid, cifar_iid from utils.op...
# coding: utf-8 import re import unicodedata import MeCab class Preprocess(object): def __init__(self, dictionary_path, valid_posid, stop_words=None): # wakati self.mecab = MeCab.Tagger('-Odump -d ' + dictionary_path) self.valid_posid = valid_posid self.stop_words = stop_words ...
# Generated by Django 2.2 on 2019-04-15 23:30 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('onlclass', '0017_bulletin'), ] operations = [ migrations.AddField( model_name='bulletin', ...
"""Build doas common tests""" import daos_build def scons(): """Execute build""" Import('denv') daos_build.test(denv, 'btree', 'btree.c', LIBS=['daos_common', 'gurt', 'cart', 'pmemobj']) daos_build.test(denv, 'btree_direct', 'btree_direct.c', LIBS=['daos_common'...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4131 ._SN', MapName = 'Grancel', Location = 'T4131.x', MapIndex = 1, MapDefaultBGM = "ed60014", Flags = 0, ...
from app.db import db from app.models.entity import Entity class Crag(Entity): id = db.Column(db.Integer, db.ForeignKey('entity.id'), primary_key=True) description = db.Column(db.Text) blocks = db.relationship('Block', backref='crag', primaryjoin="(Crag.id==Block.crag_id)", lazy='joined') area_id = db...
from typing import List import numpy as np import tensorflow.keras.backend as K from ucca4bpm.util.history import Epoch class MaskedAccuracy: def __init__(self, mask_input, name=None): self._mask = mask_input if name is None: self.__name__ = MaskedAccuracy.__name__ else: ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 13 18:50:07 2019 @author: Amirhassan """ # Deep Convolutional GANs # Importing the libraries from __future__ import print_function import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets...
#### Pereira Anthony #### Pierson Quentin #### from random import * import os def initialiser_grille(): """ initialise un tableau de 10x10 avec des -1 :return:tableau générer :rtype:list >>> initialiser_grille() [[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1,-1,-1,-1,...
import copy import json from django_admin_json_editor import JSONEditorWidget from django.utils.safestring import mark_safe from django.template.loader import render_to_string class JSONEditorWidget(JSONEditorWidget): template_name = 'lanthanum/_json_editor_widget.html' def render(self, name, value, attrs=N...
# -*- coding: utf-8 -*- #!/usr/bin/env python3 import re def word_count(phrase): phrase = re.sub(r'^[a-z0-9 ]',r'',phrase) words = phrase.lower().split() count = {} for word in words: w = str(word) count[w] = count.get(word, 0) + 1 return count
import os import math import time import pandas as pd import matplotlib.pyplot as plt import numpy as np from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction...
from datetime import datetime from django.db import models class Category(models.Model): name = models.CharField('カテゴリ名', max_length=255) def __str__(self): return self.name class Post(models.Model): title = models.CharField('タイトル', max_length=255) text = models.TextField('本文', max...
from data import polyvore_dataset, DataGenerator from utils import Config from model import MyModel from tensorflow.keras.callbacks import ModelCheckpoint import matplotlib.pyplot as plt if __name__=='__main__': if Config['Custom_model']: name = 'Custom_model' else: name = 'Transfer_mod...
import logging from raven.contrib.django.raven_compat.models import client from djangosaml2idp.views import IdPHandlerViewMixin from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.http import ...
from flask import Flask, render_template, request, session, redirect, url_for, flash #import db_builder import populateDB import functions#Contains functions to populate the database from passlib.hash import sha256_crypt import time import sqlite3 import os app = Flask(__name__) app.secret_key = os.urandom(8) ##comm...
class Solution: def grayCode(self, n: int): res = [0] for i in range(n): for j in range(len(res)-1,-1,-1): res.append(res[j]+2**i) return res s = Solution() f = s.grayCode(3) print(f)
from locust import HttpLocust, TaskSet, task, between, ResponseError class UserBehaviour(TaskSet): @task(1) def dive(self): self.client.get("/dive-service/dives?diveId=860361450") @task(2) def diver(self): self.client.get("/dive-service/divers?diveId=1") @task(3) def sms(self...
# DOCUMENTATION ---------------------------------------------------------- ''' Description: Create function to retreive pdfs from web page ''' # IMPORT LIBRARIES ------------------------------------------------------- # Python import os import pandas as pd from bs4 import BeautifulSoup from urllib.request import ...
import sys def readNetlist(file): nets = int(file.readline()) inputs = file.readline().split() inputs.sort() outputs = file.readline().split() outputs.sort() # read mapping mapping = {} while True: line = file.readline().strip() if not line: ...
class Cycle: hour = 0 minute = 0 def __init__(self, h, m): self.hour = h self.minute = m def getHour(self): return self.hour def getMinute(self): return self.minute
# -*- coding: utf-8 -*- """ Spyder Editor """ import numpy as np import pandas as pd from sklearn import linear_model from sklearn.cross_validation import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import Lasso from sklearn.linear_model import lasso_stability_path fr...
# !/usr/bin/python # coding=utf-8 # # @Author: LiXiaoYu # @Time: 2013-10-17 # @Info: Epoll Server. from Epolls.Server import Server from Epolls.SocketParser import SocketParser #当前状态码 _STATUS_CODES = 200 #创建服务端 def createServer(app=""): return Server(app) #发送请求 def send(socket_obj, command, body): s = Socke...
import re ''' the sub func in re module is quite useful to implement many complicated replacement. the second parameter can be a function which describes how to replace the matched pattern. ''' class Solution(object): def decodeString(self, s): while '[' in s: s = re.sub(r'(\d+)\[([a-z]*)\]',...
#Programa: act10.py #Propósito: clasificar unas circunferencias #Autor: Jose Manuel Serrano Palomo. #Fecha: 17/10/2019 # #Variables a usar: # x1,y1,x2,y2 y r1,r2 son los puntos de la circunferencia # d es la distancia entre los centros de las circunferencias # #Algoritmo: # LEER x1,y1 x2,y2 y r1,r2 # Calculamos d <-- (...
""" Functions for retrieving strings from files """ import os def string_from_file(string, strip=True): """ Return an unaltered string or the contents of a file if the string begins with @ and the rest of it points at a path. If 'strip' is True, remove leading and trailing whitespace (default be...
from pypi_org.services import user_service from pypi_org.viewmodels.shared.viewmodelbase import ViewModelBase class IndexViewModel(ViewModelBase): def __init__(self): super().__init__() self.user = user_service.find_user_by_id(self.user_id)
# sample_nine_a.py import sys import os import platform import wx # class My_Frame # class My_App #------------------------------------------------------------------------------- if os.name == "posix": print("\nPlatform : UNIX - Linux") elif os.name in ['nt', 'dos', 'ce']: print("\nPlatform : Windows") else...