text
stringlengths
38
1.54M
import os import shutil import random X = 2000 try: os.mkdir('isochronous-dataset') except: print('Deleting previous contents') for directory in os.scandir('isochronous-dataset'): shutil.rmtree(directory.path) for directory in os.scandir('dataset'): print('Copying {} random images for class {...
# https://www.hackerrank.com/challenges/mini-max-sum/problem a = [int(i) for i in input().split()] z1 = a[1] +a[2] + a[3] + a[4] z2 = a[0] +a[2] + a[3] + a[4] z3 = a[0] +a[1] + a[3] + a[4] z4 = a[0] +a[1] + a[2] + a[4] z5 = a[0] +a[1] + a[2] + a[3] print(min(z1,z2,z3,z4,z5),max(z1,z2,z3,z4,z5))
import numpy as np from chainer import functions as F from chainer import links as L class WN(L.Linear): def __init__(self, *args, **kwargs): super(WN, self).__init__(*args, **kwargs) self.add_param('g', self.W.data.shape[0]) norm = np.linalg.norm(self.W.data, axis=1) self.g.data...
#!/usr/bin/env python # # debugger # Michal Horejsek <horejsekmichal@gmail.com> # https://github.com/horejsek/python-debugger # from distutils.core import setup setup( name = 'debugger', packages = [ 'debugger/', ], version = '1.3', url = 'https://github.com/horejsek/python-debugger', ...
#Naive Bayers in Fraud Detection #Naive Bayer's Formula P(A/B) = P(BIA)*P(A)/P(B) import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import seaborn as sns import datetime ''' Note: The dataset used for this algorithm is completely a mock da...
def create_empty_block(): from datetime import datetime dic = { "subject": "", "creation_time": datetime.now().strftime("%Y%m%d%H%M%S"), "due_date": "00000000000000", "tags": [], "level": "Easy", "status": "Not Started Yet", "completeness": "0", "comment": "", "number": -1 } empt...
class Solution: def numsSameConsecDiff(self, N: int, K: int) -> List[int]: output=[] def dfs(digit, N): if N==0: output.append(digit) return last_digit=digit%10 if last_digit>=K: ...
tolerance_limit = {'soc': 0.05, 'current': 0.1} def in_max_tolerence_limit(value, nextValue, maxDelta): if nextValue - value > maxDelta: return False return True def validate_sensor_reading(values, parameter_type): last_but_one_reading = len(values) - 1 for i in range(last_but_one_reading): ...
import json k = int(input()) main = json.loads(input()) in_ = [json.loads(input()) for x in range(k-1)] ans = {} for publication in main['publications']: p = 0 for a in publication['articleCounts']: if a['year'] == '2017' or a['year'] == '2018': p += int(a['articleCount']) ans[publicat...
#Create the list of epic programmers epic_programmer_list = ["Tim Berners-Lee", "Guido van Rossum", "Linus Torvalds", "Larry Page", "Sergey Brin",] #Add myself to the end of the list epic_programmer_list.append("Me") epic_...
"""A module to store some results that are parsed from .txt files.""" import os from configparser import ConfigParser from types import SimpleNamespace import pandas as pd import numpy as np from skm_pyutils.table import list_to_df from dictances.bhattacharyya import bhattacharyya from .main import main as ctrl_mai...
from script import get_space_between_digits spacing_range = (1, 5) space = get_space_between_digits(spacing_range) def test_answer_type(): assert isinstance(space, int) def test_range(): """Range has to be between the upper and lower limit""" upper = space <= spacing_range[1] lower = space >= spac...
############################################################################################ # # Project: Peter Moss COVID-19 AI Research Project # Repository: EMAR Mini, Emergency Assistance Robot # # Author: Adam Milton-Barker (AdamMiltonBarker.com) # Contributors: # Title: EMAR Mini Servo Cla...
# Generated by Django 3.1.4 on 2021-03-07 11:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0012_auto_20210129_1224'), ] operations = [ migrations.AlterField( model_name='product'...
# Generated by Django 2.0.4 on 2018-04-23 08:09 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('operation', '0002_auto_20180423_1350'), ] operations = [ migrations.AddField( ...
# NUMPY NOTES # numpy arrays are closer to hardware. Thus, their execution/operation times are significantly lesser # compared to the usual pythonic lists. import numpy as np import time import sys # One dimensional array a = np.array([1, 2, 3]) print(a) # Two dimensional array b = np.array([[1, 2, 3], [4, 5, 6]]) pr...
from rest_framework.views import APIView from rest_framework.response import Response from .serializers import * class EventView(APIView): @staticmethod def get(request): events = Event.objects.filter(user=request.user) serializer = EventSerializer(events, many=True) return Response({...
class Solution: def findPermutation(self, s: str) -> List[int]: ans = [] for i, c in enumerate(s): if c != 'I': continue ans += list(range(i+1, len(ans), -1)) ans += list(range(len(s)+1, len(ans), -1)) return ans
#!/bin/python import sys #from time import time def make_kmers(read,k): if len(read)>=20: for i in range(len(read)-(k-1)): yield read[i:i+k] #tstart=time() outfile=sys.argv[1] f=open(outfile,'a') for line in sys.stdin: line=line.strip() allkmers=make_kmers(line,19) allkmers=filter(lambda x: str.find(x,"N")...
from django.shortcuts import render from django.http import JsonResponse from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view, permission_classes from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOU...
import unittest from L08 import * class SyntaxTest(unittest.TestCase): def teststorbokstav(self): """ Testar saknad stor bokstav """ self.assertEqual(kollaMolekyl("aa"), "Saknad stor bokstav.") def testlitettal(self): """ Testar om något tal är mindre än 1 """ self.assertEqu...
# from transformers import AlbertModel, AlbertTokenizer from experiments.predefined import update from experiments.predefined.base_wiki import env, base_config, siamese_config, joint_config, bert_base_config, \ roberta_base_config, xlnet_base_config, seq512_config, seq256_config, seq128_config, seq64_config, conc...
import json import logging from speedtest import Speedtest logging.basicConfig(level=logging.INFO, filename='data.log', format='%(message)s') st = Speedtest() st.get_best_server() st.download() st.upload() logging.info(json.dumps(st.results.dict()))
#!/usr/bin/python import os, datetime, time, re, sys import commands import pexpect def log_info(str_trace): '''print "\033[32m%s%20s:%03d %s\033[0m" %(datetime.datetime.now().strftime('%m%d-%H:%M:%S.%f'), sys._getframe().f_back.f_code.co_name, sys._getframe().f_back.f_lineno, str_trace);''...
import numpy as np from matplotlib.pylab import * import re from itertools import groupby print '\n' targetfile = raw_input('What File would you like to Analyse? ') infile = open(targetfile, 'r') line = infile.readline() title = line[1:].rstrip() sequence_lines = [] while 1: line = infile.readline().rstrip() ...
from __future__ import division import copy import glob import logging import logging.handlers from lxml import etree import optparse import psutil import requests import socket import subprocess import sys import os import time import yaml DESCRIPTION_SKELETON = { 'name': 'XXX', 'time_max': 60, 'value_typ...
from django.db import transaction from django.utils.decorators import method_decorator from django_filters.rest_framework import DjangoFilterBackend from drf_yasg.utils import no_body, swagger_auto_schema from rest_framework import mixins, viewsets, serializers, status from rest_framework.decorators import action from ...
import random import card import settings import data class Deck: cards = [] def __init__(self, number_of_decks): cards = [] for _ in range(number_of_decks): cards += [ card.Card( value, suit if not settings.USE_SUIT_CHAR else da...
T = int(input()) for tc in range(1, T + 1): N = int(input()) if N % 2: total = 1 + N // 2 else: total = -1 * N // 2 print(f'#{tc} {total}')
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import cv2 import tensorflow as tf from tensorflow import keras from sklearn.utils import shuffle from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator #Load Images images = np.load('kanna...
print ("hellpw") print ("Hellow againa") print ("this is fun.") print ('yay!Printing.') print("i'd much rather you 'not'.") print('i "said" do not touch this.')
""" Production Settings for Heroku """ import environ # If using in your own project, update the project namespace below from euclidean.settings.base import * env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # False if not in os.environ DEBUG = env('DEBUG') # Raises django's Improperly...
Python 3.6.0a1 (v3.6.0a1:5896da372fb0, May 16 2016, 15:20:48) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information...
#!/usr/bin/env python2.7 """ To run locally: python server.py Go to http://localhost:8111 in your browser. """ import os from sqlalchemy import * from sqlalchemy.pool import NullPool from flask import Flask, request, render_template, g, redirect, Response import psycopg2 tmpl_dir = os.path.join(os.path.dirname...
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding import numpy as np import unicodedata import string import re import random from preprocessing import Lang, Preprocessing from neuralkeras import Network def printInfo(input_lang, output_lang, p...
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.login import LoginManager from flask.ext.assets import Environment from ybk.frontend import frontend from ybk.user import user from ybk.api import api from ybk.admin import admin from ybk.models import User blueprin...
def matrix_search(number, matrix): row = 0 column = len(matrix)-1 while row < len(matrix) and column >= 0: if matrix[row][column] == number: return True if number > matrix[row][column]: row +=1 else: column -= 1 return False matrix = [ [10,...
from datetime import datetime, timedelta from CommonServerPython import * from CommonServerUserPython import * import traceback import json import base64 import urllib3 # Disable insecure warnings urllib3.disable_warnings() # pylint: disable=no-member ''' CONSTANTS ''' DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 ...
# coding=utf-8 import ConfigParser from CreateSQL import SQLCluster import sys import json import utiltool.DBOperator from LogModule import setup_logging import logging setup_logging() logger = logging.getLogger(__name__) # 配置utf-8输出环境 reload(sys) sys.setdefaultencoding('utf-8') class MenTable: def __init__(sel...
# 30 december 2016 - phil welsby from socket import * Hostname = '' PortNumber=12345 Buffer=500 ServerAddress=(Hostname, PortNumber) UDP_Server_Socket=socket(AF_INET, SOCK_DGRAM) UDP_Server_Socket.bind(ServerAddress) while 1: print 'The server is ready to receive data from the client' ClientData, ClientAddr...
def nomeMaiusculo(nome, sobrenome): nomeCompleto = nome + ' ' + sobrenome return nomeCompleto.title() hacker = nomeMaiusculo('ninja', 'doido') print(hacker) # neste caso a funcao tem um retorno que e o nome completo formatado # o return e o valor que a funcao vai devolver pra quem a chamou.
from django.conf.urls import include, url from .views import MacroBotView urlpatterns = [ url(r'^f8aa22868a60e6570970045b01cecf7f05c9f78f0a7b4824f3/?$', MacroBotView.as_view()) ]
# -*- coding: utf-8 -*- """ rdreilib.eauth ~~~~~~~~~~~~~~~~ An Easy Authentication WSGI middleware inspired by the django auth system. :copyright: 2008, 2009 by Pascal Hartig <phartig@rdrei.net> :license: BSD, see doc/LICENSE for more details. """ from models import User, Group, Permission, AnonymousUser from ...
########################################################################## # # Copyright (c) 2011-2014, John Haddon. All rights reserved. # Copyright (c) 2011-2014, Image Engine Design Inc. All rights reserved. # Copyright 2019, Hypothetical Inc. All rights reserved. # # Redistribution and use in source and binary ...
# -*- coding: utf-8 -*- import re import redis import json class FlaskDocPipeline(object): def process_item(self, item, spider): item['text']=re.sub(r'\s+', ' ',item['text']) self.redis.lpush('flask_doc:items',json.dumps(dict(item))) return item def open_spider(self,spider): sel...
# Copyright (c) 2021 Alastair Macleod # # 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, copy, modify, merge, publish, di...
import string_changer as sc #If you want to use this module, you must need string_changer.py. #Maybe, you can get string_changer.py from repository containing this module. inpfilename = input("Please enter the file name you want to use.\n") inpfile = open(inpfilename, "r") #Open the pdb file containing watar box of TI...
"""With a CSV with interfaces, description, trunk status and VLANS list, create one line per vlan for Static path creation Usage: Static_paths_data_creation.py (-h | --help) Static_paths_data_creation.py --version Static_paths_data_creation.py -v <variables> Options: -h --help ...
from rest_framework import serializers from .models import lesson from drf_extra_fields.fields import Base64ImageField from django.contrib.auth.models import User class LessonSerializer(serializers.HyperlinkedModelSerializer): title_image = Base64ImageField() term1_image = Base64ImageField() term2_image =...
from django.db import models class UserModel(models.Model): USER_ROLES = ( ("NU", "Normal"), ("SU", "Admin") ) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=30) full_name = models.CharField(max_length=30) user_type = models.CharF...
import codecs import json #all vars for default to start! class svnSettings: count = 2 dir_local = [] dir_server = [] concurrent_id = 0 dir_toGenerate = [] last_revison = [] config = None source_config_file = "C:\Desarrollo-Practica\PySvn\manage_versions\config.json" def ...
# -*- coding: utf-8 -*- """Mapping of Python types to SQL types""" import io import uuid import numpy as np import sqlalchemy import utool as ut from sqlalchemy.exc import StatementError from sqlalchemy.sql import text from sqlalchemy.types import Integer as SAInteger from sqlalchemy.types import TypeDecorator, UserDe...
# Generated by Django 2.0.4 on 2018-04-25 16:40 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0006_auto_20180424_2143'), ] operations = [ migrations.AlterField( model_name='task', ...
import json import re import os import logging import urllib.parse from blocks import ( LEARN_OR_TEACH, TEACH_FORM, LEARN_FORM, generate_teacher_request_block, generate_join_block ) from api import ( create_channel, invite_to_channel, unarchive_channel, get_channel, delete_messa...
# Generated by Django 2.1.3 on 2018-12-04 10:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('forum', '0055_auto_20181130_1833'), ] operations = [ migrations.CreateModel( name='Categorie_action', fields=[ ...
import unittest import sys, os sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'src')) from evaluate.employment_check import check from utilities.evaluation_result import EvaluationResult from applicant_status_test import ApplicantStatusTest class CheckEmploymentTest(Appl...
# Generated by Django 3.1.5 on 2021-01-25 20:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('words', '0001_initial'), ] operations = [ migrations.AlterField( model_name='word', name='word', field=m...
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ import string import pygraphviz as pgv def trifusion(T) : if len(T)<=1 : return T T1=[T[x] for x in range(len(T)//2)] T2=[T[x] for x in range(len(T)//2,len(T))] return fusion(trifusion(T1),trifusion(T2)) def fu...
import numpy as np def loadDataSet(fileName): """ 加载数据集 input: fileName: string output: dataMat: Mat labelMat:Mat """ dataMat = []; labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = line.strip().split('\t') dataMat.append([flo...
from sense_hat import SenseHat from time import sleep import curses screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(1) sense = SenseHat() currentOption=0 R=[255,0,0] O=[0,0,0] displayValue=[ [ O,O,R,R,R,R,O,O, O,R,O,O,O,O,R,O, O,R,O,O,O,O,R,O, O,O,R,R,R,R,O,...
import array import itertools import math import time from collections import Counter from decimal import Decimal, getcontext, localcontext from tqdm import tqdm # From https://docs.python.org/3/library/decimal.html def pi(): """Compute Pi to the current precision. >>> print(pi()) 3.1415926535897932384626...
# Generated by Django 3.2.6 on 2021-08-23 05:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('principal', '0001_initial'), ] operations = [ migrations.CreateModel( name=...
import sys, os, argparse import json import numpy as np import matplotlib.pyplot as plt import pandas as pd import joblib from collections import OrderedDict import uproot import tensorflow as tf import zfit from userConfig import loc, train_vars, train_vars_vtx from matplotlib import rc rc('font',**{'family':'serif',...
def sort_it(list_, n): return ', '.join(sorted(list_.split(', '), key=lambda i: i[n-1])) ''' Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word. The letters should be compare...
'''Script to generate MDS plots for a DE trajectory on the chosen benchmark ''' import os import sys import json import pickle import argparse import numpy as np from matplotlib import pyplot as plt from sklearn.manifold import MDS import ConfigSpace from denas import DE from matplotlib import rcParams rcParams["f...
import numpy as np from astropy.io import fits from datetime import datetime from timeit import default_timer import os,pwd from matplotlib.backends.backend_pdf import PdfPages from ... import info from ...config import Config from .. import header_utils from .residuals import Residuals from .extract import Extract ...
#!/usr/bin/env python # -*- coding:UTF-8 -*- # File Name : data_aug.py # Purpose : # Creation Date : 21-12-2017 # Last Modified : Fri 19 Jan 2018 01:06:35 PM CST # Created By : Jeasine Ma [jeasinema[at]gmail[dot]com] import numpy as np import cv2 import os import multiprocessing as mp import argparse import glob fro...
import speech_recognition from gtts import gTTS import os #create brain for bot, first time it might be null bot_brain = ""; #create ear for bot to listen bot_ear = speech_recognition.Recognizer() while True: with speech_recognition.Microphone() as mic: print("\nBot: I'm listening") #audio = bot_e...
#!/usr/bin/env python #coding:utf8 __author__ = 'xiaokong' from module.plugin import Plugin class poc(Plugin): type = 'CMS' cmsname = 'keyicms' querytype = 'site' description = 'KeyiCMS login in by Cookie whithout auth' def __init__(self): self.payload = "AS...
# -*- coding: utf-8 -*- # Adapted from <http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example> from django import forms CHOICES = [('NB', 'Naive Bayes'), ('LR', 'Logistic Regression')] class DocumentForm(forms.Form): algorithm = forms.ChoiceField(choices=CHOICES) docfile = forms...
print("**************************************************************LIST COMPREHENSION & GENERATOR EXPRESSION**************************************************************") #Q.1- Write a python program to print the cube of each value of a list using list comprehension. l=[] n=int(input('enter no.of values ')) for i ...
import importlib import logging from pyjob.exception import PyJobUnknownTaskPlatform TASK_PLATFORMS = { "local": ("pyjob.local", "LocalTask"), "lsf": ("pyjob.lsf", "LoadSharingFacilityTask"), "pbs": ("pyjob.pbs", "PortableBatchSystemTask"), "slurm": ("pyjob.slurm", "SlurmTask"), "sge": ("pyjob.sge...
class Target: stock = "" invested = False max_investment = 1 last_bottom = -1 last_top = -1 smalest = 1 # Invalid value to say we don't have one buy_price = -1 greed_price = -1 loss_price = -1 count = 0 def __init__(self, stock, max_investment, smalest): self.s...
from datetime import datetime from sqlalchemy import create_engine, func, text from sqlalchemy.orm import Session from db_declaration import Base, Source, Video, Comment, Author VERSION = 17 SQL_FILE = 'LNSyoutube_v17.db' DB_PATH = "/Users/paulineziserman/GoogleDrive/these_db/Bases/" def get_count(q): count_q =...
def test_get_person_position(): assert get_person_position('b', [['F', 'X', 'F', 'F', 'F', 'X'], ['g1', 'F', 'F', 'F', 'F', 'e'], ['F', 'b', 'F', 'F', 'F', 'F'], ['X', 'F', 'g2', 'F', 'F', 'X'], ['F', 'X...
# Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos # e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). # No final, mostre a lista ordenada na tela. listaNum = [] for x in range(5): num = int(input(f'Digite o {x+1}º número: ')) if x == ...
################################################################################# # WaterTAP Copyright (c) 2020-2023, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National Laboratory, # National Renewable Energy Laboratory, and National Energy Technology # Labo...
#数据类型5-字典 #1.标志{} 关键字dict #2.a={} 空字典 #3.字典的存储格式是 key:value 键值对 #4.字典里面value可以是任何类型的取值 #5.取值方式:根据key取值 字典名[key] (不能通过索引,因为字典是无序的) # a={} # print(type(a)) #返回类型 dict a={"name":"华华","age":18,"money":99.99,"score":[99,100,88]} print(a) print(a["name"]) #问题: #in/not in不确定是否适用于字典,返回都是false?还是用法不对? # print('"name":"华华"' ...
from art.attacks import BasicIterativeMethod from tools.art.adversarial_attack import AdversarialAttack class BIMAttack(AdversarialAttack): def __init__(self, model, step_size_iter=0.1, max_perturbation=0.3, max_iterations=100, targeted=False, batch_size=16): super().__init__(model=model...
import sys from worldBuilder3 import * import pdfkit def createWorldFromRules(rules,seed="SEED"): ''' rules should be a list of strings each of which when exec'd assings a list of Rule objects to the variable someRules E.g. someRules=[Rule("rule",0,[],[])] ''' generatedRules=[] validRules=[] ssmDes...
import tarfile import datetime import calendar import urllib from cStringIO import StringIO from zipfile import ZipFile from base64 import decodestring from dateutil import parser from collections import defaultdict import requests import json import yaml import bson import base64 import fnmatch from bson import json...
import math import matplotlib.pyplot as plt print("Hello world") # Return the likelihood of a value given parameters of a gaussian. def get_likelihood(value, mu, sigma): # I know there are ways to just directly get the likelihood from some python librarie, but this does it # explicitly return (1 / math.s...
from django.conf import settings from django.conf.urls import include, url from django.utils import timezone from django.views.decorators.cache import cache_page from django.views.decorators.http import etag from django.views.i18n import javascript_catalog import pretix.control.urls import pretix.presale.urls from .b...
from typing import Optional from datetime import datetime class WorkerNode: def __init__( self, id_: str, hostname: str, running_job_id: Optional[str] = None, last_seen: Optional[datetime] = None, jobs_processed: int = 0, is_alive: bool = True, use_w...
# coding=utf-8 from odoo import release from . import models def get_wx_reply_from_aciton(action): _name = action._name if _name==models.wx_action_act_text._name: return action.content elif _name==models.wx_action_act_article._name: articles = action.article_ids return '' elif ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 31 16:31:06 2020 by Miriam Stevens @author: steve276 ABE65100 - ThinkPython - Exercise 5.2 This program uses nested conditionals and recursion to check whether Format's Last Theorem is true for diferent user-input values. """ #part 1 def check_fe...
from symdiff import * # Any copyright is dedicated to the Public Domain. # http://creativecommons.org/publicdomain/zero/1.0/ symdiff('declare_model(x)') symdiff('declare_model(y)') l = model_list(); for i in l: print(('%s' % i))
import re pattern = 'fox' text = 'The quick brown fox jumps over the lazy dog.' for match in re.finditer(pattern, text): s = match.start() e = match.end() print(s, e)
# -*- coding: utf-8 -*- from __future__ import print_function from . import __version__ from . import parse from . import config from .basexml import BaseXML from .util import print_info class Generator(BaseXML): """Construct Karabiner favorite XML tree >>> g = Generator() >>> s = ''' ... <root> ...
#!/usr/bin/env python #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from bes.files.match.bf_match_item_metadata import bf_match_item_metadata from bes.files.match.bf_match_options import bf_match_options from bes.files.bf_entry import bf_entry from bes.files.metadata.bf_met...
def largest_pali(n_digitos): for i in range(((10 ** n_digitos) - 1), 0, -1): for j in range(((10 ** n_digitos) - 1), 0, -1): if str(i * j) == str(i * j)[::-1]: return i*j print(largest_pali(3))
import collections DfsRecord = collections.namedtuple('DfsRecord', 'time type id') def read_input(): available = '.' origin = 'M' destination = '*' dict_available_points = {} rows, _ = get_int_list(input()) index = 0 origin_location = None destination_location = None for i_rows in...
#!/bin/python2 import feedparser import requests import re import os import sqlite3 import commonFunctions, ssdeepcheck import progressbar import sys import datetime CHECKFILE = os.path.join(commonFunctions._SCRIPT_PATH, "lastURLmalc0d.stamp") _DATE = datetime.date.today() def process_xml_list_desc(response): feed...
import logging from typing import List, Optional, Set, cast from bs4 import Tag from yarl import URL from grobber.anime.sources.nineanime import BASE_URL, NineAnime, extract_episode_count, parse_raw_title from grobber.languages import Language from grobber.request import Request from grobber.uid import MediumType fro...
from typing import List from .abstract_db import AbstractDB from model.command import Command class CommandDB(AbstractDB): def __init__(self) -> None: self.__decition_list: List[Command] = [] def get(self, index: int) -> Command: assert isinstance(index, int) return self.__decition_li...
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split # Utility Functions def getDataBatch(dataFile): """Generator function which generates data(from a csv file) in chunks of 10...
import unittest import numpy as np import cv2 from facial_attributes.facial_landmarks import landmarks_rectification from facial_attributes.facial_landmarks import facial_landmarks_detection_dlib from facial_attributes.facial_segment import face_segmentation from utils import face_process class MyTestCase(unittest.Te...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('resultado', views.resultado, name='resultado'), ]
''' if expression: Statement ''' age = int(input("Enter Age : ")) if age>=15: print("Hello Mr.") else : print("Hello Babe!") print("555") print("จบโปรแกรม") # ถ้าต้องการให้เป็นจริงแค่ case เดียว ให้ใช้ elif ''' if expression: Statement elif expression: Statement else : Statement ''' #...
import win32com.client as win32 import cgitb import cgi cgitb.enable() f = cgi.FieldStorage() T = f.getvalue('OpenButton', '1') print(''' <html> <head><meta charset="gbk"> <title>InsertTitle</title></head> <body> <form action="Open.py"> 打开文档:<br> <input type="submit" name="OpenButton" value="打开文档"><br> ''') try: ...