import argparse
import ccl_bplist
import construct
import plistlib

"""
An old version of yk_bmdata.py that makes use of construct library.
Limitation: Number of ToCs it can parse
"""

__author__ = 'yukai'

# to reduce code width
_ARRAY = construct.Array
_POINTER = construct.Pointer
_REPEAT = construct.RepeatUntil
_INT = construct.ULInt32('integer')
_INT64 = construct.ULInt64('integer64')

_BOOKMARK_DATA = construct.Struct(
    'bookmark_data',
    construct.String('magic', 4),
    construct.ULInt32('length'),
    construct.UBInt32('version'),
    construct.ULInt32('offset'),  # offset to "FirstToC Offset"
    _POINTER(lambda ctx: ctx.offset,
             construct.Struct(
                'ftoc_offset',
                construct.Anchor('abs_offset'),
                construct.ULInt32('offset'),
                _POINTER(lambda ctx: ctx.abs_offset + ctx.offset,
                         _REPEAT(lambda obj, ctx: obj.offset == 0x00000000,
                                 construct.Struct(
                                     'toc',
                                     construct.ULInt32('length'),
                                     construct.SLInt16('type'),
                                     construct.UBInt16('flag'),
                                     construct.ULInt32('level'),
                                     construct.ULInt32('offset'),  # offset to next ToC (0 if none)
                                     construct.ULInt32('count'),
                                     _ARRAY(lambda ctx: ctx.count,
                                            construct.Struct(
                                                'record',
                                                construct.ULInt16('type'),
                                                construct.ULInt16('flag'),
                                                construct.ULInt64('offset'),  # offset to data record
                                                _POINTER(lambda ctx: ctx._._.abs_offset + ctx.offset,
                                                         construct.Struct(
                                                             'data_record',
                                                             construct.ULInt32('length'),
                                                             construct.ULInt32('type'),
                                                             construct.Field('data', lambda ctx: ctx.length)))))))))))
_DATA = construct.Struct(
    'std_data',
    construct.ULInt32('length'),
    construct.ULInt32('type'),
    construct.Field('data', lambda ctx: ctx.length))

def parse():
    result = {}
    bookmark = _BOOKMARK_DATA.parse(raw_data)

    for table in bookmark.ftoc_offset.toc:
        for record in table.record:
            if record.type == 4100:  # pathComponents
                result['path'] = ''
                offsets = interpret(record.data_record, bookmark)  # obtain absolute offsets
                for offset in offsets:
                    path_component = _DATA.parse(raw_data[offset:])
                    result['path'] += '/' + path_component.data.decode('utf-8')
                print('filePath     : {}'.format(result['path']))

            elif record.type == 4101:  # fileIDs
                result['inodes'] = ''
                offsets = interpret(record.data_record, bookmark)  # obtain absolute offsets
                for offset in offsets:
                    inodes = _DATA.parse(raw_data[offset:])
                    result['inodes'] += '/' + str(_INT64.parse(inodes.data))
                print('inodePath    : {}'.format(result['inodes']))

            elif record.type == 4112:  # resourceProps
                print('resourceProps: {}'.format('?'))

            elif record.type == 4160:  # creationDate
                print('creationDate : {}'.format('?'))

            elif record.type == 8192:  # volInfoDepths
                print('volInfoDepths: {}'.format('?'))

            elif record.type == 8194:  # volPath
                result['volPath'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('volPath      : {}'.format(result['volPath']))

            elif record.type == 8197:  # volURL
                result['volURL'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('volURL       : {}'.format(result['volURL']))

            elif record.type == 8208:  # volName
                result['volName'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('volName      : {}'.format(result['volName']))

            elif record.type == 8209:  # volUUID
                result['volUUID'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('volUUID      : {}'.format(result['volUUID']))

            elif record.type == 8272:  # volMountURL
                print('volMountURL  : {}'.format('?'))

            elif record.type == 49169:  # user
                result['user'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('user         : {}'.format(result['user']))

            elif record.type == 61568:  # sandboxInfo
                result['sandbox'] = interpret(record.data_record, bookmark).decode('utf-8')
                print('sandboxInfo  : {}'.format(result['sandbox']))

            else:
                print('record type {} is currently unknown'.format(record.type))

def interpret(data_record, bookmark):
    count = data_record.length // 4
    if data_record.length % 4 > 0:
        count += 1

    if data_record.type == 1537:  # offsets
        offsets = []
        data = data_record.data
        for offset in range(count):
            offsets.append(bookmark.offset + _INT.parse(data))  # base offset + relative offset
            data = data[4:]
        return offsets

    if data_record.type == 257 or 513 or 2305:
        string_data = construct.String('string', data_record.length).parse(data_record.data)
        return string_data

def _debug():
    bookmark = _BOOKMARK_DATA.parse(raw_data)

    print('Magic           : {}'.format(bookmark.magic))
    print('Length          : {}'.format(bookmark.length))
    print('Version         : {}'.format(bookmark.version))
    print('Data Offset     : {}'.format(bookmark.offset))
    print('Absolute Offset : {}'.format(bookmark.ftoc_offset.abs_offset))
    print('First ToC Offset: {}'.format(bookmark.ftoc_offset.offset))

    for table in bookmark.ftoc_offset.toc:
        print('\t===== ToC =====')
        print('\tLength: {}'.format(table.length))
        print('\tType  : {}'.format(table.type))
        print('\tFlag  : {}'.format(table.flag))
        print('\tLevel : {}'.format(table.level))
        print('\tOffset: {}'.format(table.offset))
        print('\tCount : {}'.format(table.count))
        for record in table.record:
            print('\t\t===== Record =====')
            print('\t\tType  : {}'.format(record.type))
            print('\t\tFlag  : {}'.format(record.flag))
            print('\t\tOffset: {}'.format(record.offset))
        print('\t===== End of ToC =====')

parser = argparse.ArgumentParser(description='Parse bookmark data within plists')
parser.add_argument('plist_path', metavar='plist', type=str, nargs=1, help='specify path to plist file')
args = parser.parse_args()
raw_data = None

with open(args.plist_path[0], 'rb') as plist:
    try:
        pl = plistlib.load(plist)
    except ValueError:
        pl = ccl_bplist.load(plist)

    try:
        for item in pl["RecentDocuments"]["CustomListItems"]:
            raw_data = item['Bookmark']
            # _debug()
            parse()
            print('====================')
    except KeyError:
        pass


"""
Plotly Dash based LIBRA dashboard
"""
from dash import Dash
from dash_bootstrap_components import themes
from src.components.layout import create_layout

def main():
    app = Dash(external_stylesheets=[themes.SPACELAB])
    app.title = "LIBRA Dashboard (based on LIBRA v2.2)"
    app.layout = create_layout(app)
    app.run_server(debug=False, host='127.0.0.1', port=8050)

if __name__=="__main__":
    main()


import logging

LogFile = 'EmployeeLog'
LogFileMode = 'a+'
LoggerName = __name__
LogLevel = logging.DEBUG
LogFormat = '%(asctime)s %(filename)s %(**%(levelname)s** %(message)s'

logger = logging.getLogger(__name__)
logger.setLevel(LogLevel)

formatter = logging.Formatter(LogFormat)

handler = logging.FileHandler(LogFile)
handler.setFormatter(formatter)

logger.addHandler(handler)

class Employee:
    def __init__(self, eid, name):
        self.eid = eid
        self.name = name

        logger.info("Created new Employee : Name : {} Employee Id : {}".format(self.name, self.eid))

def main():
    emp1 = Employee('Nehal', 'IBE1117')
    emp2 = Employee('Kumar', 'IBE1118')

    print(emp1)
    print(emp2)

if __name__ == '__main__':
    main()


# transposition brute forcer

# built-in modules
import math
# 3rd party modules
import pyperclip
# local modules
import transposition_cipher, cipher_main

def transpositionBruteForce(myMessage):
    myKeyMax = int(len(myMessage) / 2)
    # create list of potential decrypted messages
    decrypted = bruteForceMessage(myKeyMax, myMessage)

    # allow user to copy a particular message to clipboard
    copier(decrypted)

def copier(messages):
    # prompt for copying by key
    try:
        copyMessageInput = int(input('Enter key of message to copy: '))
    except ValueError:
        print('Key must be a number.  Please try again.')
        return cipher_main.main()

    copyMessage = messages[copyMessageInput - 2]
    if (copyMessage):
        pyperclip.copy(copyMessage)
        print(f'Your decrypted message at key {copyMessageInput} has '
            'been copied to your clipboard.')
    else:
        print(f'{copyMessageInput} is an invalid key.  Please try again.')
        copier(messages)

def printForcedText(key, text):
    # convert key from int to str
    # add 0 in front of single digits for clarity
    if (key < 10):
        key = '0' + str(key)
    else:
        key = str(key)

    # print with key at beginning and a | at the end
    print(key + ': ' + text + '|')

def bruteForceMessage(keyRange, message):
    messageList = []

    for key in range(2, keyRange):
        newMessage = transposition_cipher.decrypter(key, message)
        printForcedText(key, newMessage)
        messageList.append(newMessage)
    return messageList


from pyspark.sql import *
from pyspark.sql.functions import *
from pyspark.sql.types import *
from etl.utilPrograms.pysparkAssignmentHelpingFunctions import *
import warnings
warnings.simplefilter("ignore")

spark = SparkSession.builder.appName("PySpark-Assignment").config("spark.some.config.option","some-value").getOrCreate()

Schema = StructType([StructField("Product Name",StringType(),True),\
                     StructField("Issue Date",StringType(),True),\
                     StructField("Price",LongType(),True),\
                     StructField("Brand",StringType(),True),\
                     StructField("Country",StringType(),True),\
                     StructField("ProductNumber",StringType(),False)
                     ])

Data = [("Washing Machine","1648770933000",20000,"Samsung","India","0001"),\
        ("Refrigerator","1648770999000",35000," LG ","","0002"),\
        ("Air Cooler","1648770948000",45000," Voltas ","","0003")]

Schema1 = StructType([StructField("SourceId",LongType(),True),\
                     StructField("TransactionNumber",LongType(),True),\
                     StructField("Language",StringType(),True),\
                     StructField("ModelNumber",LongType(),True),\
                     StructField("StartTime",StringType(),True),\
                     StructField("ProductNumber",StringType(),False)
                     ])

Data1 = [(150711,123456,"EN",456789,"2021-12-27T08:20:29.842+0000","0001"),\
        (150439,234567,"UK",345678,"2021-12-27T08:21:14.645+0000","0002"),\
        (150647,345678,"ES",234567,"2021-12-27T08:22:42.445+0000","0003")]

spark.sparkContext.setLogLevel("ERROR")
def createDataframeTable1(Data,Schema):
    df = spark.createDataFrame(data=Data, schema=Schema)
    return df

def createDataframeTable2(Data1,Schema1):
    df1 = spark.createDataFrame(data=Data1, schema=Schema1)
    return df1

# Q1A
def convertDate(createDataframeTable1,convertMiliSecondsToTimeStamp):
    df = createDataframeTable1(Data,Schema)
    df = df.rdd.map(lambda x:(x[0],x[1],convertMiliSecondsToTimeStamp(x[1]),x[2],x[3],x[4],x[5])).\
        toDF(schema = ["ProductName","IssueDate","newTimeStamp","Price","Brand","Country","ProductNumber"])
    df.show(truncate = False)
    return df

# Q1B Convert to date type
def converttoDateType(convertDate,timeStampToDateType):
    df =  convertDate(createDataframeTable1,convertMiliSecondsToTimeStamp)
    df = df.withColumn("newTimeStamp",df.newTimeStamp.cast(TimestampType()))
    df = df.rdd.map(lambda x:(x[0],x[1],timeStampToDateType(x[2]),x[3],x[4],x[5],x[6])).\
        toDF(schema = ["ProductName","IssueDate","DateType","Price","Brand","Country","ProductNumber"])
    df.show()
    return df

# Q1C
def rmWhiteSpaces(createDataframeTable1,rmWhiteSpaceUtils):
    df = createDataframeTable1(Data, Schema)
    df = df.rdd.map(lambda x:(x[0],x[1],x[2],rmWhiteSpaceUtils(x[3]),x[4],x[5])).\
        toDF(schema = ["ProductName","IssueDate","Price","Brand","Country","ProductNumber"])
    df.show()
    return df

# Q1D replace null values with Empty Values
def changeNUllValues(createDataframeTable1):
    df = createDataframeTable1(Data,Schema)
    df = df.select("*",when(df.Country == "","Empty Value").otherwise(df.Country).alias("nullHandlingForCountry")).drop("Country")
    df.show()
    return df

# Q2A Change the camel case columns to snake case
def convertCase(convertCaseUtils,createDataframeTable2):
    df = createDataframeTable2(Data1, Schema1)
    columns = df.columns
    updatedSchema = list(map(convertCaseUtils,columns))
    df = df.rdd.toDF(updatedSchema)
    df.show()
    return df

# Q2B Add another column as start_time_ms and convert the values of StartTime to
# milliseconds.
def convertTimeStampToMiliSeconds(createDataframeTable2,convertSecondstoTimeStamp):

    df = createDataframeTable2(Data1,Schema1)
    dfNew = df.rdd.map(lambda x: (x[0],x[1],x[2],x[3],x[4],convertSecondstoTimeStamp(x[4]),x[5])).\
        toDF(schema=["SourceID","TransactionNumber","Language","ModelNumber","unchangedTime","changedTime", "ProductNumber",])
    dfNew = dfNew.withColumn("changedTime",col("changedTime").cast("long"))
    dfNew.show(truncate = False)
    return dfNew
convertTimeStampToMiliSeconds(createDataframeTable2,convertSecondstoTimeStamp)
# Q3 Combine both the tables based on the Product Number and get all the fields in return.
# And get the country as EN
def combineTheTables(createDataframeTable1, createDataframeTable2):
    df1 = createDataframeTable1(Data,Schema)
    df2 = createDataframeTable2(Data1,Schema1)
    dfJoin = df1.join(df2,df1.ProductNumber == df2.ProductNumber,"inner")
    dfJoin.show(truncate = False)
    return dfJoin

def getCountrybyValue(combineTheTables):
    dfJoin =  combineTheTables(createDataframeTable1, createDataframeTable2)
    dfJoin = dfJoin.filter(dfJoin.Language.contains("EN")).groupBy("Country","Language").count()\
        .select("Country","Language", col("count").alias("countryFound"))
    dfJoin.show()
    return dfJoin


from time import sleep

def loadDataSet():
    return [[1,3,4],[2,3,5],[1,2,3,5],[2,5]]

def createC1(dataSet):
    C1 = []
    for transaction in dataSet:
        for item in transaction:
            if not [item] in C1:
                C1.append([item])
    C1.sort()
    return list(map(frozenset, C1))

def scanD(D, Ck, minSupport):
    ssCnt = {}
    for tid in D:
        for can in Ck:
            if can.issubset(tid):
                if not can in ssCnt:
                    ssCnt[can] = 1
                else:
                    ssCnt[can] += 1
    numItems = float(len(D))
    retList = []
    supportData = {}
    for key in ssCnt:
        support = ssCnt[key] / numItems
        if support >= minSupport:
            retList.insert(0, key)
        supportData[key] = support
    return retList, supportData

def aprioriGen(Lk, k):
    retList = []
    lenLk = len(Lk)
    for i in range(lenLk):
        for j in range(i+1, lenLk):
            L1 = list(Lk[i])[:k-2]
            L2 = list(Lk[j])[:k-2]
            L1.sort()
            L2.sort()
            if L1 == L2:
                retList.append(Lk[i] | Lk[j])
    return retList

'''
    支持度计算，筛选频繁度高的
'''
def apriori(dataSet, minSupport = 0.5):
    C1 = createC1(dataSet)
    D = list(map(set, dataSet))
    L1, supportData = scanD(D, C1, minSupport)
    L = [L1]
    k = 2
    while(len(L[k-2]) > 0):
        Ck = aprioriGen(L[k-2], k)
        Lk, supK = scanD(D, Ck, minSupport)
        supportData.update(supK)
        L.append(Lk)
        k += 1
    return L, supportData

'''
    生成关联规则
'''
def generateRules(L, supportData, minConf = 0.7):
    bigRuleList = []
    for i in range(1, len(L)):
        for freqSet in L[i]:
            H1 = [frozenset([item]) for item in freqSet]
            # print(H1,"---",freqSet)
            if(i > 1):
                rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
            else:
                calcConf(freqSet, H1, supportData, bigRuleList, minConf)
    return  bigRuleList

'''
    计算 freqSet-conseq -> conseq的可信度
    conseq的集合是H
'''
def calcConf(freqSet, H, supportData, brl, minConf = 0.7):
    prunedH = []
    for conseq in H :
        conf = supportData[freqSet] / supportData[freqSet - conseq]
        if conf >= minConf:
            print(freqSet-conseq,"-->",conseq, "conf:",conf)
            brl.append((freqSet-conseq, conseq, conf))
            prunedH.append(conseq)
    return prunedH

def rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
    m = len(H[0])
    # print(freqSet,"===",H)
    if(len(freqSet) > (m+1)):
        Hmp1 = aprioriGen(H, m+1) # 进行组合
        # print(Hmp1)
        Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf) # 计算可信度：如{0，2}->{1,3}可信
        if(len(Hmp1) > 1): # 存在可信的，继续计算其推导的可信度{0}->{1,2,3}的可信的，如果上面不可信，后面不需要进行推导
            rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)

if __name__ == "__main__":
    dataSet = loadDataSet()
    # C1 = createC1(dataSet)
    # print(C1)
    # D = map(set, dataSet)
    # L1, suppData0 = scanD(list(D), C1, 0.5)
    # print(L1)

    # L, suppData = apriori(dataSet)
    # print(L)

    # L, suppData = apriori(dataSet, minSupport=0.5)
    # print(L)
    # rules = generateRules(L, suppData, minConf=0.7)
    # print(rules)

    # 毒蘑菇
    mushDatSet = [line.split() for line in open('mushroom.dat').readlines()]
    L, suppData = apriori(mushDatSet, minSupport=0.3)
    # rules = generateRules(L, suppData, minConf=0.9)
    # print(rules)
    # 查看毒蘑菇
    for item in L[1]:
        if item.intersection('2'):
            print(item)

Machine Learning in Action/Apriori/apriori.py


import logging

import requests
from telegram.ext import run_async, CommandHandler

from commands.yts.utils import get_minimal_movie, prettify_yts_movie
from utils.decorators import send_typing_action, log_time
from keyboards.keyboards import yts_navigator_keyboard

logger = logging.getLogger(__name__)

@log_time
@send_typing_action
@run_async
def yts(bot, update, chat_data):
    try:
        r = requests.get('https://yts.am/api/v2/list_movies.json', params={'limit': 50})
    except requests.exceptions.ConnectionError:
        update.message.reply_text("ðŸ“¡ La api de yts estÃ¡ caida. IntentÃ¡ mÃ¡s tarde")
        return
    if r.status_code != 200:
        logger.info(f"Yts api down. {r.status_code}")
        return None
    try:
        movies = r.json()['data']['movies']
    except KeyError:
        logger.info(
            f'Response has no moives {r.url} {r.status_code} {r.reason} {r.json()}'
        )
        return None

    # Build context based on the imdb_id
    chat_data['context'] = {
        'data': movies,
        'movie_number': 0,
        'movie_count': len(movies),
        'command': 'yts',
        'edit_original_text': True,
    }
    title, synopsis, rating, imdb, yt_trailer, image = get_minimal_movie(movies[0])
    movie_desc = prettify_yts_movie(title, synopsis, rating)
    yts_navigator = yts_navigator_keyboard(imdb_id=imdb, yt_trailer=yt_trailer)
    bot.send_photo(
        chat_id=update.message.chat_id,
        photo=image,
        caption=movie_desc,
        reply_markup=yts_navigator,
    )

yts_handler = CommandHandler('yts', yts, pass_chat_data=True)


from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [

    path('', views.landing, name = 'landing'),
    path('app/', views.scheduler, name = 'scheduler'),
    path('paymentsuccess/', views.paymentsuccess, name = 'paymentsuccess'),
    path('paymentsettings/', views.paymentsettings, name = 'paymentsettings'),
    path('app/project/<slug>', views.projects, name = 'project'),
    path('add-project/', views.add_project, name='add_project'),
    path('add-module/<pk>', views.add_module, name='add_module'),
    path('delete-module/<pk>', views.delete_module, name='delete_module'),
    path('add-task/<pk>', views.add_task, name='add_task'),
    path('delete-task/<pk>', views.delete_task, name='delete_task'),
    path('app/project/edit-task/<pk>', views.edit_task, name='edit_task'),
    path('edit-task/<pk>', views.edit_task, name='edit_task'),
    path('app/project/edit-task/', views.edit_task, name='edit_task'),
    path('try-progress/', views.try_progress, name='try_progress'),
    path('add-email-launch/', views.add_email_launch, name='add_email_launch'),

    path('demo/', views.scheduler_demo, name = 'scheduler_demo'),
    path('demoapp/project/<slug>', views.projects_demo, name = 'project_demo'),
]


from scapy.all import *

# Returns Packet's most important info in a dictionary to be used in the maininterface packettable
def getPacketInfoDict(packet):
	p = {}
	p['srcMac'] = packet[Ether].src
	p['dstMac'] = packet[Ether].dst
	p['time'] = str(packet.time)
	p['len'] = str(len(packet))

	# ARP Support
	if (packet.haslayer(ARP)):
		p['proto'] = 'ARP'
		p['ARPSrc'] = packet[ARP].psrc
		p['ARPDst'] = packet[ARP].pdst
		p['ARPMacDst'] = packet[ARP].hwdst
		p['ARPMacSrc'] = packet[ARP].hwsrc
		print(packet[ARP].op)
		if (packet[ARP].op == 1):
			p['ARPop'] = 'who has'
		elif (packet[ARP].op == 2):
			p['ARPop'] = 'is at'
		try:
			if (p['ARPop'] == 'who has'):
				p['info'] = p['ARPop'] + ' ' + packet[ARP].pdst + '? tell ' + packet[ARP].psrc
			elif (p['ARPop'] == 'is at'):
				p['info'] = packet[ARP].psrc + ' is at ' + p['srcMac']
		except(TypeError):
			p['info'] = ""
		return p
	if (packet.haslayer(IP)):
		p['IPsrc'] = packet[IP].src
		p['IPdst'] = packet[IP].dst
		p['IPVersion'] = str(packet[IP].version)
		p['IPttl'] = str(packet[IP].ttl)
		p['IPcheckSum'] = packet[IP].chksum
		p['IPlen'] = str(packet[IP].len)
	if (packet.haslayer(IPv6)):
		p['IPsrc'] = packet[IPv6].src
		p['IPdst'] = packet[IPv6].dst
		p['IPVersion'] = '6'
		p['IPlen'] = str(packet[IPv6].plen)
	# TCP and UDP
	if (packet.haslayer(UDP) or packet.haslayer(TCP)):
		if (packet.haslayer(UDP)):
			p['proto'] = 'UDP'
			p['srcPort'] = str(packet[UDP].sport)
			p['dstPort'] = str(packet[UDP].dport)
			p['UDPcheckSum'] = packet[UDP].chksum
			p['UDPlen'] = str(packet[UDP].len)
		elif(packet.haslayer(TCP)):
			p['proto'] = 'TCP'
			p['srcPort'] = str(packet[TCP].sport)
			p['dstPort'] = str(packet[TCP].dport)
			p['TCPcheckSum'] = packet[TCP].chksum
		return p
	# ICMP
	if (packet.haslayer(ICMP)):
		p['proto'] = 'ICMP'
		p['IPsrc'] = packet[IP].src
		p['IPdst'] = packet[IP].dst
		p['IPVersion'] = str(packet[IP].version)
		p['ICMPtype'] = str(packet[ICMP].type)
		p['ICMPcode'] = str(packet[ICMP].code)
		p['ICMPcheckSum'] = str(packet[ICMP].chksum)
		return p
	else:
		p['proto'] = packet.lastlayer().name
		return p

def hexdump3(x, dump = False):
	s = ""
	if type(x) is not str and type(x) is not bytes:
		try:
			x = bytes(x)
		except:
			x = str(x)
	l = len(x)
	i = 0
	while i < l:
		s += ("%04x  \t" % i)
		for j in range(16):
			if i+j < l:
				s += ("%02X " % orb(x[i+j]))
			else:
				s += ("  ")
			if j%16 == 7:
				s += (" ")
		s += ("\t\t")
		s +=(sane_color(x[i:i+16]) + '\n')
		i += 16
	return s


from __future__ import annotations
from typing import Any, Optional, TYPE_CHECKING

from bgpy.simulation_engine.announcement import Announcement as Ann
from bgpy.simulation_engine.ann_containers import RecvQueue
from bgpy.enums import Relationships

if TYPE_CHECKING:
    from bgpy.simulation_framework import Scenario

def receive_ann(self, ann: Ann, accept_withdrawals: bool = False):
    """Function for recieving announcements, adds to recv_q"""

    if ann.withdraw and not accept_withdrawals:
        raise NotImplementedError("Policy can't handle withdrawals")
    self._recv_q.add_ann(ann)

def process_incoming_anns(
    self,
    *,
    from_rel: Relationships,
    propagation_round: int,
    scenario: "Scenario",
    reset_q: bool = True,
):
    """Process all announcements that were incoming from a specific rel"""

    # For each prefix, get all anns recieved
    for prefix, ann_list in self._recv_q.prefix_anns():
        # Get announcement currently in local rib
        current_ann: Ann = self._local_rib.get_ann(prefix)
        current_processed: bool = True

        # Seeded Ann will never be overriden, so continue
        if getattr(current_ann, "seed_asn", None) is not None:
            continue
        # For each announcement that was incoming
        for ann in ann_list:
            # Make sure there are no loops
            # In ROV subclass also check roa validity
            if self._valid_ann(ann, from_rel):
                # Determine if the new ann is better
                new_ann_better: bool = self._new_ann_better(
                    current_ann, current_processed, from_rel, ann, False, from_rel
                )
                # If new ann is better, replace the current_ann with it
                if new_ann_better:
                    current_ann = ann
                    current_processed = False

        # This is a new best ann. Process it and add it to the local rib
        if current_processed is False:
            current_ann = self._copy_and_process(current_ann, from_rel)
            # Save to local rib
            self._local_rib.add_ann(current_ann)

    self._reset_q(reset_q)

def _valid_ann(self, ann: Ann, recv_relationship: Relationships) -> bool:
    """Determine if an announcement is valid or should be dropped"""

    # BGP Loop Prevention Check
    return self.asn not in ann.as_path

def _copy_and_process(
    self,
    ann: Ann,
    recv_relationship: Relationships,
    overwrite_default_kwargs: Optional[dict[Any, Any]] = None,
) -> Ann:
    """Deep copies ann and modifies attrs

    Prepends AS to AS Path and sets recv_relationship
    """

    kwargs: dict[str, Any] = {
        "as_path": (self.asn,) + ann.as_path,
        "recv_relationship": recv_relationship,
    }

    if overwrite_default_kwargs:
        kwargs.update(overwrite_default_kwargs)
    # Don't use a dict comp here for speed
    return ann.copy(overwrite_default_kwargs=kwargs)

def _reset_q(self, reset_q: bool):
    """Resets the recieve q"""

    if reset_q:
        self._recv_q = RecvQueue()


#https://colab.research.google.com/drive/1L_2syN8Cqtyywm3MOkzCOXyfw3FuVxOc#scrollTo=zcirEKOgpWGk

import multiprocessing
import math

# funcion fibonacci con la tecnica de la memorizacion para mejorar el tiempo de ejecucion
def fibonacci(n, memo={}):
    if n in memo:
      return memo[n]

    # Cálculo fibo con formula
    memo[n]=math.trunc((pow((1+math.sqrt(5))/2,n) - pow((1-math.sqrt(5))/2,n))/math.sqrt(5))
    return memo[n]

if __name__ == '__main__':
    with multiprocessing.Pool() as pool:
        result = pool.map(fibonacci, range(1000))
    print(result)


import sys
sys.stdin = open('input.txt')

def baek(a, b, c):
    global count2
    if c < b or b < a:
        return
    if a + b + c > 100:
        return
    if a + b + c == 100:
        count2 += 1
        return
    if tensor[a+1][b][c] == 0:
        tensor[a+1][b][c] = 1
        baek(a+1, b, c)
    if tensor[a][b+1][c] == 0:
        tensor[a][b+1][c] = 1
        baek(a, b+1, c)
    if tensor[a][b][c+1] == 0:
        tensor[a][b][c+1] = 1
        baek(a, b, c+1)

count = 0
count2= 0
tensor = [[[0 for _ in range(99)] for _ in range(99)] for _ in range(99)]
for i in range(1, 99):
    for j in range(i, 99):
        for k in range(j, 99):
            if i + j + k == 100:
                count += 1

print(count)

baek(1, 1, 1)

print(count2)


import rasterio
from pathlib import Path
import yaml

# reading in geotiff file as numpy array
def read_tif(file: Path):
    if not file.exists():
        raise FileNotFoundError(f'File {file} not found')

    with rasterio.open(file) as dataset:
        arr = dataset.read()  # (bands X height X width)
        transform = dataset.transform
        crs = dataset.crs

    return arr.transpose((1, 2, 0)), transform, crs

# writing an array to a geo tiff file
def write_tif(file: Path, arr, transform, crs):
    if not file.parent.exists():
        file.parent.mkdir()

    height, width, bands = arr.shape
    with rasterio.open(
            file,
            'w',
            driver='GTiff',
            height=height,
            width=width,
            count=bands,
            dtype=arr.dtype,
            crs=crs,
            transform=transform,
    ) as dst:
        for i in range(bands):
            dst.write(arr[:, :, i], i + 1)


from math import sqrt
import numpy as np
import matplotlib.pyplot as plt

def createList(n):
    numbers = np.random.uniform(0, 1, n)
    return numbers

def expecValue(n):
    M = sum(createList(n)) / n
    return M

def dispersion(list, M):
    sumPow = 0
    for i in range(0, n):
        sumPow += (list[i] - M) ** 2
    D = sumPow / n
    return D

def densityFunc(n, numbers):
    array = []
    for i in range(1, n):
        a = 0
        b = numbers[i]
        c = 1/(b-a)
        if numbers[i] >= a and numbers[i] <= b:
            array.append(c)
        else:
            array.append(0)
    return array

def autocorFunc(n, M, numbers):
    K = []
    for i in range(1, n):
        f = i
        sum1 = 0
        sum2 = 0
        for j in range(1, n - f):
            sum1 += (numbers[j] - M) * (numbers[j + f] - M)
        for g in range(1, n):
            sum2 += (numbers[g] - M) ** 2
        K.append(sum1/sum2)
    return K

n = 10
print("N = ", n)
numbers1 = createList(n)
M = expecValue(n)
D = dispersion(numbers1, M)
S = sqrt(D)
print("Numbers: \n", numbers1)
print("M: ", M)
print("D: ", D)
print("S: ", S)
K1 = autocorFunc(n, M, numbers1)
locs = np.arange(len(K1))
width = 0.75
plt.bar(locs, K1, width=width)
plt.ylabel('K(f)')
plt.xlabel('f')
plt.title('Correlogram, n=10')
plt.savefig('correl1.png')
plt.close()
densityFunc(n, numbers1)
weights = np.ones_like(numbers1) / float(len(numbers1))
plt.hist(numbers1, weights=weights)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.title('density function, n=10')
plt.savefig('denstFunct1.png')
numbers1.sort()
plt.close()
plt.plot(numbers1 / n)
plt.ylabel('F(x)')
plt.xlabel('x')
plt.title('integrate function, n=10')
plt.savefig("integFunct1.png")
plt.close()
print("\n")

n = 100
print("N = ", n)
numbers2 = createList(n)
M = expecValue(n)
D = dispersion(numbers2, M)
S = sqrt(D)
print("Numbers: \n", numbers2)
print("M: ", M)
print("D: ", D)
print("S: ", S)
K2 = autocorFunc(n, M, numbers2)
locs = np.arange(len(K2))
width = 0.75
plt.bar(locs, K2, width=width)
plt.ylabel('K(f)')
plt.xlabel('f')
plt.title('Correlogram, n=100')
plt.savefig('correl2.png')
plt.close()
densityFunc(n, numbers2)
weights = np.ones_like(numbers2) / float(len(numbers2))
plt.hist(numbers2, weights=weights)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.title('density function, n=100')
plt.savefig('denstFunct2.png')
numbers2.sort()
plt.close()
plt.plot(numbers2 / n)
plt.ylabel('F(x)')
plt.xlabel('x')
plt.title('integrate function, n=100')
plt.savefig("integFunct2.png")
plt.close()
print("\n")

n = 1000
print("N = ", n)
numbers3 = createList(n)
M = expecValue(n)
D = dispersion(numbers3, M)
S = sqrt(D)
print("Numbers: \n", numbers3)
print("M: ", M)
print("D: ", D)
print("S: ", S)
K3 = autocorFunc(n, M, numbers3)
locs = np.arange(len(K3))
width = 0.75
plt.bar(locs, K3, width=width)
plt.ylabel('K(f)')
plt.xlabel('f')
plt.title('Correlogram, n=1000')
plt.savefig('correl3.png')
plt.close()
densityFunc(n, numbers3)
weights = np.ones_like(numbers3) / float(len(numbers3))
plt.hist(numbers3, weights=weights)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.title('density function, n=1000')
plt.savefig('denstFunct3.png')
numbers3.sort()
plt.close()
plt.plot(numbers3 / n)
plt.ylabel('F(x)')
plt.xlabel('x')
plt.title('integrate function, n=1000')
plt.savefig("integFunct3.png")
plt.close()
print("\n")

n = 10000
K4 = []
print("N = ", n)
numbers4 = createList(n)
M = expecValue(n)
D = dispersion(numbers4, M)
S = sqrt(D)
print("Numbers: \n", numbers4)
print("M: ", M)
print("D: ", D)
print("S: ", S)
K4 = autocorFunc(n, M, numbers4)
locs = np.arange(len(K4))
width = 0.75

plt.bar(locs, K4, width=width)
plt.ylabel('K(f)')
plt.xlabel('f')
plt.title('Correlogram, n=10000')
plt.savefig('correl4.png')
plt.close()
densityFunc(n, numbers4)
weights = np.ones_like(numbers4) / float(len(numbers4))
plt.hist(numbers4, weights=weights)
plt.ylabel('f(x)')
plt.xlabel('x')
plt.title('density function, n=10000')
plt.savefig('denstFunct4.png')
numbers4.sort()
plt.close()
plt.plot(numbers4 / n)
plt.ylabel('F(x)')
plt.xlabel('x')
plt.title('integrate function, n=10000')
plt.savefig("integFunct4.png")
plt.close()
print("\n")


import networkx as nx
import matplotlib.pyplot as plt

MNDA = nx.MultiGraph()

MNDA.add_nodes_from(["S1","S5"])
MNDA.add_edges_from([("S1","S2"),("S2","S3"),("S2","S4"),("S2","S5"),("S3","S4"),("S3","S4"),("S4","S5"),
                     ("S4","S5"),("S3","S5")])

nx.draw(MNDA, node_size = 1000, node_color = 'y', node_shape = 'o', with_labels=True)
plt.draw()
plt.savefig("MNDA.eps")
plt.show()


import tkinter
import menubar
import toolbar
import statusbar

class fenster(tkinter.Tk):

    #init function für fenster
    def __init__(self):

        #calling die tkinter.Tk init methode
        super().__init__()

        #values für das Fenster
        self.title("Transkriptionseditor")
        self.geometry("500x300")
        self.minsize(700,500)
        self.resizable(True, True)

        #row- and columnconfiguration for the layout
        self.grid_rowconfigure(0,weight=1)
        self.grid_rowconfigure(1,weight=1000)
        self.grid_rowconfigure(2,weight=1)
        self.grid_columnconfigure(0,weight=1)

        #create all objectives in "private" functions
        self.__Main_Frame()
        self.__create_StatusBar()
        self.__create_Menu()
        self.__create_Toolbar()
        self.__create_Scrollbar()
        self.__create_Textfield()

        #calling function to set all bindings
        self.__set_Bindings()

        #setting focus so the Bindings work from the beginning
        self.textfield.focus_set()

        #variable für modifieSearch
        self.mod = 0

    def __Main_Frame(self):
        #create the mainframe, in the mainframe is the textfield and the scrollbar for the textfield
        self.mainFrame = tkinter.Frame(self)
        self.mainFrame.grid(row=1, sticky='news')

    #Private Methode, welche die menubar erzeugt
    def __create_Menu(self):
        #create the menubar
        self.menubar = menubar.menubar(self)
        self.config(menu= self.menubar)

    def __create_Toolbar(self):
        #create the toolbar, from his own class
        self.toolbar = toolbar.toolbar(self)
        self.toolbar.grid(row=0, sticky='news')

    def __create_StatusBar(self):
        #create the status bar as a Frame
        self.statusbar = statusbar.statusbar(self)
        self.statusbar.grid(row=2, sticky='news')

    def __create_Scrollbar(self):
        #packing Scrollbar
        self.scrollbar = tkinter.Scrollbar(self.mainFrame)
        self.scrollbar.pack(side="right",fill="y")

    def __create_Textfield(self):
        #creating the textfield and setting the scrollcommand in the textfield to the scrollbar
        self.textfield = tkinter.Text(self.mainFrame, undo=True,yscrollcommand=self.scrollbar.set, wrap=tkinter.WORD)
        self.textfield.pack(expand=True,fill="both")

        #setting the scrollbar to the textfield viewfield
        self.scrollbar.config(command=self.textfield.yview)

        #wenn das textfeld bearbeitet wird, dann wir dieses event getriggert
        self.textfield.bind('<<Modified>>', lambda event: self.modifieSearch())

    def modifieSearch(self): #wenn das Textfield modifiziert wird, wird diese funktion aufgerufen
        if self.mod == 0: #die variable benutzen wir, damit es nicht zweimal ausgeführt wird, passiert sonst
            self.mod = 1
            if self.menubar.searchmenu.searchwindow: #muss nur gemacht werden, wenn auch das such menü auf ist
                self.menubar.searchmenu.searchwindow.startButton(self) #es wird erneut gesucht, damit wenn weiter gedrückt wird etc nicht die markierungen für die suche ungenau wird
            self.textfield.edit_modified(False) #die Modifie flag vom textfield wird auf false gesetzt, weil sonst weitere modifizierungen nicht erkannt werden
        else:
            self.mod = 0

    def __set_Bindings(self):
        #creating all the bindings for the programm
        #adding bindings for filemenu
        self.bind('<Control -n>', lambda event : self.menubar.filemenu.newFile(self))
        self.bind('<Control -o>', lambda event : self.menubar.filemenu.openFile(self))
        self.bind('<Control -s>', lambda event : self.menubar.filemenu.saveFile(self))
        self.bind('<Control - Alt - s>', lambda event : self.menubar.filemenu.saveFileUnder(self))

        #adding binding for searchmenu
        self.bind('<Control -f>', lambda event : self.menubar.searchmenu.create_searchWindow(self.menubar,self))

        #adding bindings for toolbar
        self.bind('<Control -space>',lambda event : self.toolbar.playSong())
        self.bind('<Control -Left>', lambda event : self.toolbar.skipBack())
        self.bind('<Control -Right>', lambda event : self.toolbar.skipForward())

        """ Der Grund, dass da immer noch event hinter dem Lambda steht ist, das hier ein Event getriggert wird
        und deshalb ein Argument an lambda übergeben wird. Anstatt'event' könnte da auch 'a' stehen. Aber wir müssen sagen,
        dass lambda ein argument erwartet, sonst wird gemeckert."""


# VPN WITH PROXY BY POLAIV | https://github.com/polaiv

import tkinter
import winreg
import customtkinter
from PIL import Image

class ToplevelWindow(customtkinter.CTkToplevel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry('400x300')
        self.label = customtkinter.CTkLabel(self, text='Error')
        self.label.pack(padx=20, pady=20)

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()

        self.geometry('495x595')
        self.title('VPN_WITH_PROXY')
        self.resizable(False, False)
        self.toplevel_window = None
        try:
            self.logo = customtkinter.CTkImage(dark_image=Image.open('vpn_logo.png'), size=(460, 460))
            self.logo_label = customtkinter.CTkLabel(master=self, text='', image=self.logo)
            self.logo_label.place(relx=0.5, rely=0.20, anchor=tkinter.CENTER)
        except:
            self.lbl_error = customtkinter.CTkLabel(self, text='most likely, the logo image \n is not in the same directory')
            self.lbl_error.place(relx=0.5, rely=0.20, anchor=tkinter.CENTER)

        self.lbl_enable = customtkinter.CTkLabel(self, text='VPN was successfully enabled ✅')
        self.lbl_disable = customtkinter.CTkLabel(self, text='VPN was successfully turned off ❌')

        self.btn = customtkinter.CTkButton(self, text="Enable VPN ✅", command=self.toggle_vpn)
        self.btn.place(relx=0.5, rely=0.7, anchor=tkinter.CENTER)

    def toggle_vpn(self):
        if self.btn.cget("text") == "Enable VPN ✅":
            self.btn.configure(text="Turn off VPN ❌")
            self.set_proxy_enabled(True)
            self.lbl_disable.place_forget()
            self.lbl_enable.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER)
        else:
            self.btn.configure(text="Enable VPN ✅")
            self.set_proxy_enabled(False)
            self.lbl_enable.place_forget()
            self.lbl_disable.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER)

    def set_proxy_enabled(self, enabled):
        try:
            registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                          r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
                                          0, winreg.KEY_WRITE)

            if enabled:
                winreg.SetValueEx(registry_key, 'ProxyEnable', 0, winreg.REG_DWORD, 1)
            else:
                winreg.SetValueEx(registry_key, 'ProxyEnable', 0, winreg.REG_DWORD, 0)

            winreg.CloseKey(registry_key)

        except Exception as e:
            self.open_toplevel()

if __name__ == '__main__':
    app = App()
    app.mainloop()


def merge(nums1, n, nums2, m):
    nums3=[0]*(m+n)
    l=0
    r=0
    index=0

    #compare the value and add to new list from both lists
    while l<n and r<m:
        if nums1[l]<=nums2[r]:
            nums3[index]=nums1[l]
            index+=1
            l+=1
        else:
            nums3[index]=nums2[r]
            index+=1
            r+=1

    #add the balence elements to array
    while l<n:
        nums3[index]=nums1[l]
        index+=1
        l+=1

    while r<m:
        nums3[index]=nums2[r]
        index+=1
        r+=1
    #save both array with the values of new array
    for i in range(m+n):
        if i<n:
            nums1[i]=nums3[i]
        else:
            nums2[i-n]=nums3[i]

    print(nums1,nums2)

n = 4
arr1 = [1, 4, 8, 10]
m = 3
arr2 = [2,3,9]
merge(arr1,n,arr2,m)

Merge two Sorted Arrays Without Extra Space.py


import csv
import sys
import numpy as np

attribute_to_vector = {}
attributes = set();
jobs = set();
for fname in ["db_24_0_text/Work Styles.txt", "db_24_0_text/Work Context.txt", "db_24_0_text/Work Activities.txt", "db_24_0_text/Knowledge.txt", "db_24_0_text/Skills.txt","db_24_0_text/Abilities.txt" ]:
	with open(fname, 'r') as csvfile:
		csvreader = csv.reader(csvfile, delimiter='\t', quotechar='"')
		header = next(csvreader);
		hmap = { h:i for i,h in enumerate(header) }

		for row in csvreader:
			attribute = row[ hmap['Element Name'] ].lower();
			job = row[ hmap['O*NET-SOC Code'] ].lower();
			jobs.add(job)
			attributes.add(attribute);

			if row[ hmap['Scale ID'] ] == "IM" or row[ hmap['Scale ID'] ] == "CX":
				if attribute not in attribute_to_vector:
					attribute_to_vector[ attribute ] = {}
				imp = float( row[ hmap['Data Value'] ] );
				attribute_to_vector[ attribute ][ job ] = imp

attributes = sorted( list(attribute_to_vector.keys()) );
for s in attributes:
	if len(attribute_to_vector[s]) != len(jobs):
		for j in jobs:
			if j not in attribute_to_vector[s]:
				attribute_to_vector[s][j] = 0;
jobs = sorted(jobs)

with open("attributes.txt", 'w') as outfile:
	for a in attributes:
		outfile.write(a + "\n");

with open("jobs.txt", 'w') as outfile:
	for j in jobs:
		outfile.write(j + "\n");

with open("job_attribute_matrix.txt", 'w') as outfile:
	csvwriter = csv.writer(outfile, delimiter=" ")
	for j in jobs:
		csvwriter.writerow( [attribute_to_vector[a][j] for a in attributes] )


import time
import scrapy
from autohomebot.items import PcautoItem

class PcautoSpider(scrapy.Spider):
    name = 'pcauto'
    allowed_domains = ['price.pcauto.com.cn']
    start_urls = [
        'https://price.pcauto.com.cn/comment/sg90/'
    ]

    def info(self, message, isPrint=True):
        # 控制台显示消息
        if isPrint == True:
            print('[' + time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time())) + '][INFO]' + message)

        # Log文件输出
        self.logger.info(message)

    def warning(self, message, logOutput=True):
        # 控制台显示消息
        print('[' + time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time())) + '][WARNING]' + message)

        # Log文件输出
        if logOutput == True:
            self.logger.warning(message)

    def error(self, message, logOutput=True):
        # 控制台显示消息
        print('[' + time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time())) + '][ERROR]' + message)

        # Log文件输出
        if logOutput == True:
            self.logger.error(message)

    # 　获取评论详情
    def parse(self, response):

        self.info('太平洋汽车网:[{}]、.状态:[{}]'.format(response.url, response.status))
        title = response.xpath('//h1/text()').extract_first()
        try:
            if response.xpath('//*[@class="next"]'):
                next_page = response.xpath('//*[@class="next"]/@href').extract_first()
                next_url = "https:" + next_page
                yield scrapy.Request(next_url,callback=self.parse)
                # print(next_url)
            for each in response.xpath('//*[@class="litDy clearfix"]'):
                item = PcautoItem()
                username = each.xpath('.//*[@class="txline"]/p/a/text()').extract_first()
                pushtime = each.xpath('.//*[@class="txline"]/span/a/text()').extract_first()
                car_type = each.xpath('.//*[@class="line"][1]/a/text()').extract_first()
                buy_time = each.xpath('.//*[@class="line" and em[contains(text(),"购买时间")]]/text()').extract_first()
                buy_loca = each.xpath('.//*[@class="line" and em[contains(text(),"购买地点")]]/text()').extract_first()
                buy_shop = each.xpath('.//*[@class="line" and em[contains(text(),"购买商家")]]/text()').extract_first()
                buy_cost = each.xpath('.//*[@class="line" and em[contains(text(),"裸车价格")]]/i/text()').extract_first()
                oil_cost = each.xpath('.//*[@class="line" and em[contains(text(),"平均油耗")]]/i/text()').extract_first()
                mileage_ = each.xpath('.//*[@class="line" and em[contains(text(),"行驶里程")]]/text()').extract_first()
                buyimage = each.xpath('.//*[@class="toptit clearfix"]/a/text()').extract()
                cmt_detl = each.xpath('.//*[@class="dianPing clearfix"]')
                comment_detail = {}
                if cmt_detl:
                    comment_detail["优点"] = cmt_detl.xpath('./div[b[contains(text(),"优点")]]/span/text()').extract_first()
                    comment_detail["缺点"] = cmt_detl.xpath('./div[b[contains(text(),"缺点")]]/span/text()').extract_first()
                    comment_detail["外观"] = cmt_detl.xpath('./div[b[contains(text(),"外观")]]/span/text()').extract_first()
                    comment_detail["内饰"] = cmt_detl.xpath('./div[b[contains(text(),"内饰")]]/span/text()').extract_first()
                    comment_detail["空间"] = cmt_detl.xpath('./div[b[contains(text(),"空间")]]/span/text()').extract_first()
                    comment_detail["配置"] = cmt_detl.xpath('./div[b[contains(text(),"配置")]]/span/text()').extract_first()
                    comment_detail["动力"] = cmt_detl.xpath('./div[b[contains(text(),"动力")]]/span/text()').extract_first()
                    comment_detail["操控"] = cmt_detl.xpath('./div[b[contains(text(),"操控")]]/span/text()').extract_first()
                    comment_detail["油耗"] = cmt_detl.xpath('./div[b[contains(text(),"油耗")]]/span/text()').extract_first()
                    comment_detail["舒适"] = cmt_detl.xpath('./div[b[contains(text(),"舒适")]]/span/text()').extract_first()

                # print(username, pushtime, car_type, buy_time, buy_loca, buy_shop, buy_cost, oil_cost, mileage_, zh_Score,
                #       buyimage, cmt_detl)
                item['username'] = username
                item['pushtiem'] = pushtime
                item['car_type'] = car_type
                item['buy_time'] = buy_time
                item['buy_loca'] = buy_loca
                if buy_shop:
                    item['buy_shop'] = buy_shop.strip()
                else:
                    item['buy_shop'] = None
                if buy_cost:
                    item['buy_cost'] = buy_cost + '万元'
                else:
                    item['buy_cost'] = None
                if oil_cost:
                    item['oil_cost'] = oil_cost + 'L/100km'
                else:
                    item['oil_cost'] = None
                item['mileage_'] = mileage_
                item['carimage'] = buyimage
                item['cmt_detl'] = comment_detail
                item['update_datetime'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                item['collection'] = title
                yield item
        except Exception as e:
            self.error('【parse_detail出错】{},{}'.format(response.url, e))


import os
import sys
import copy

broc_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, broc_dir)

from dependency import SyntaxTag
from dependency import Builder

class SourceType(object):
    """
    Source Type
    """
    SOURCE = 0
    C = 1
    CXX = 2

class Source(object):
    """
    base class
    """
    TYPE = SourceType.SOURCE
    EXTS = ()
    def __deepcopy__(self, memo):
        """
        """
        cls = self.__class__
        result = cls.__new__(cls)
        memo[id(self)] = result
        for k, v in self.__dict__.items():
            setattr(result, k, copy.deepcopy(v, memo))
        return result

    def __str__(self):
        """
        return infile, outfile, compiler, compile options infos
        """
        if self.builder:
            return self.builder.GetBuildCmd()
        else:
            return self.infile

    def __init__(self, infile, env, args):
        """
        Args:
            infile : the cvs path of source file
            env : Environment object
            args : the compile option args
        """
        self.infile = infile                     # the cvs path of source file
        self.outfile = ""                        # the cvs path of object file, ie .o
        self.args = args                         # compile option args
        self.env = env
        self.target = None                       # Target object that Source belongs to

        # compile options
        self.includes = ['.', 'broc_out']
        self.cppflags = []
        self.cflags = []
        self.cxxflags = []

        # builder
        self.builder = None
        self.headers = set()                      # the head files

    def __eq__(self, v):
        """
        call when compare two Source objects
        """
        return self.infile == v._infile

    def GetBuildCmd(self):
        """
        return build cmd
        """
        return self.builder.GetBuildCmd()

    def GetHeaderCmd(self):
        """
        return cmd for caulating head files
        """
        return self.builder.GetHeaderCmd()

    def GetHeaderFiles(self):
        """
        return the list of head files
        """
        return self.headers

    def SetHeaderFiles(self, headers):
        """
        set headers files
        """
        self.headers = headers

    def Compiler(self):
        """
        return the compiler cmd
        """
        pass

    def InFile(self):
        """
        return source file
        """
        return self.infile

    def Target(self):
        """
        return target object that source object belongs to
        """
        return self.target

    def SetTarget(self, target):
        """
        set target that source object belongs to
        """
        self.target = target

    def Env(self):
        """
        return the Envrionment object that source object belongs to
        """
        return self.env

    def OutFile(self):
        """
        return the cvs path of result file
        """
        return self.outfile

    def CalcObjectName(self):
        """
        caculate the cvs path of result file
        cvs path = 'broc_out' + '/' + cvs path of infile + '/' + '%s_%s_%s.o' % (self.target.TYPE, self.target.name, file name)
        """
        cvs_dir = os.path.dirname(self.infile)
        root, _ = os.path.splitext(os.path.basename(self.infile))
        obj_file = os.path.join(cvs_dir,
                                "%s_%s_%s.o" % (self.target.TYPE, self.target.Name(), root))
        if not obj_file.startswith('broc_out'):
            self.outfile = os.path.join("broc_out", obj_file)
        else:
            self.outfile = obj_file

    def Action(self):
        """
        parser compile flags including include path, preprocess flags,
        c compile flags and cxx compile flags
        """
        incpaths_flag = False
        cppflags_flag = False
        cflags_flag = False
        cxxflags_flag = False
        # parse all args and take arg as local flag
        for args in self.args:
            for arg in args:
                if isinstance(arg, SyntaxTag.TagInclude):
                    incpaths_flag = True
                    self.includes.extend(arg.V())
                elif isinstance(arg, SyntaxTag.TagCppFlags):
                    cppflags_flag = True
                    self.cppflags.extend(arg.V())
                elif isinstance(arg, SyntaxTag.TagCFlags):
                    cflags_flag = True
                    self.cflags.extend(arg.V())
                elif isinstance(arg, SyntaxTag.TagCxxFlags):
                    cxxflags_flag = True
                    self.cxxflags.extend(arg.V())
                else:
                    continue

        # if local flag is empty, use module global flag
        if not incpaths_flag:
            self.includes = self.env.IncludePaths().V()
        if not cxxflags_flag:
            self.cxxflags = self.env.CxxFlags().V()
        if not cppflags_flag:
            self.cppflags = self.env.CppFlags().V()
        if not cflags_flag:
            self.cflags = self.env.CFlags().V()

    def CalcHeaderFiles(self):
        """
        calculate head file
        Returns:
            True if caculate successfully
            False if failed to caculate
        """
        ret = True
        res = self.builder.CalcHeaderFiles()
        if not res['ret']:
            ret = False
        else:
            self.headers = res['headers']

        return ret

class CSource(Source):
    """
    C Source Code
    """
    TYPE = SourceType.C
    EXTS = ('.c',)
    def __init__(self, infile, env, args):
        """
        """
        Source.__init__(self, infile, env, args)

    def Compiler(self):
        """
        return the path of compiler
        """
        return self.env.CC()

    def Action(self):
        """
        parse compile options, and join all options as a string object
        """
        Source.Action(self)
        self.CalcObjectName()
        options = ['-DBROC']
        options.extend(self.cppflags + self.cflags)
        self.builder = Builder.ObjBuilder(self.outfile, self.infile, self.includes,
                                          options, self.env.CC(), self.env.Workspace())

class CXXSource(Source):
    """
    C++ Source Code
    """
    TYPE = SourceType.CXX
    EXTS = ('.cpp', '.cc', '.cxx')
    def __init__(self, infile, env, args):
        """
        """
        Source.__init__(self, infile, env, args)

    def Compiler(self):
        """
        return the path of Compiler
        """
        return self.env.CXX()

    def Action(self):
        """
        init builder
        """
        Source.Action(self)
        self.CalcObjectName()
        options = ['-DBROC']
        options.extend(self.cppflags + self.cxxflags)
        self.builder = Builder.ObjBuilder(self.outfile, self.infile, self.includes,
                                          options, self.env.CXX(), self.env.Workspace())


import os
import numpy as np
import pandas as pd

def compute_p_r(f_pred, threshold_start, threshold_end, threshold_step_len):
	pred_lines = f_pred.readlines()
	pred_lines = np.array(pred_lines)

	label_list = []
	preds_res_list = []
	for line in pred_lines:
		line_sp = line.split('\t')
		label_list.append(line_sp[0])
		pred = line_sp[1]
		pred = pred.split('_')
		preds_res_list.append([pred[0], float(pred[1])])

	all_num = len(label_list)

	threshold_tmp = threshold_start

	df = pd.DataFrame(columns=['threshold', 'P', 'R', 'F1'])

	while threshold_tmp <= threshold_end:
		pred_correct = 0
		pred_bigthanthreshold = 0

		# print(len(label_list))
		# print(len(preds_res_list))
		if len(label_list) == len(preds_res_list):
			for i in range(len(preds_res_list)):
				# print(preds_res_list[i][1], threshold_tmp)
				if preds_res_list[i][1] > threshold_tmp:
					pred_bigthanthreshold += 1
					# print(label_list[i], preds_res_list[i][0])
					if label_list[i] == preds_res_list[i][0]:
						pred_correct += 1
		Precision = pred_correct / pred_bigthanthreshold if pred_bigthanthreshold != 0 else 0
		Recall = pred_correct / all_num
		F1_Score = (2 * Precision * Recall) / (Precision + Recall) if Precision + Recall != 0 else 0
		data_row = {'threshold': threshold_tmp, 'P': Precision, 'R': Recall, 'F1': F1_Score}
		df = df.append(data_row, ignore_index=True)
		# print('t:', threshold_tmp)
		# print('Precision:', Precision)
		# print('Recall:', Recall)
		# print('F1:', F1_Score)
		threshold_tmp = threshold_tmp + threshold_step_len

	return df

def compute_p_r_one(f_pred, threshold):
	return compute_p_r(f_pred, threshold, threshold, 1)

if __name__ == '__main__':
	# 参数
	version = 'v1_0'
	date = '20210408-20210414'
	dataset = 'all'

	# 文件路径
	PRED_BASE_PATH = '/Users/sunhaowen/Documents/data/3.ivr_log/final_data/{}/pred_result'.format(version)
	OUT_BASE_PATH = '/Users/sunhaowen/Documents/data/3.ivr_log/final_data/{}/eval_result'.format(version)
	PRED_FILE_NAME = 'pred_{}_{}_py.txt'.format(date, dataset)
	OUT_FILE_NAME = 'eval_result_{}_{}_py.xlsx'.format(date, dataset)

	my_f_pred = open(os.path.join(PRED_BASE_PATH, PRED_FILE_NAME), 'r')

	# 修改函数参数
	res_df = compute_p_r(my_f_pred, threshold_start=0.0, threshold_end=1.0, threshold_step_len=0.01)
	# res_df = compute_p_r_one(my_f_pred, threshold=0.77)

	# 输出文件
	res_df.to_excel(os.path.join(OUT_BASE_PATH, OUT_FILE_NAME), index=False)


# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import xlrd

print("Iniciando nosso robô... \n")

arq = open("resultados.txt", "w")

dominios = []

#Lendo do Excel
workbook = xlrd.open_workbook('dominio.xlsx')
sheet = workbook.sheet_by_index(0)
for linha in range(0,8):
    dominios.append(sheet.cell_value(linha,0))

driver = webdriver.Chrome('/home/marcos/Projetos/robos/RobosAutomatico/chromedriver')
driver.get("https://registro.br/")

for dominio in dominios:
    pesquisa = driver.find_element_by_id("is-avail-field")
    pesquisa.clear() # Limpando Input de Pesquisa
    pesquisa.send_keys(dominio)
    pesquisa.send_keys(Keys.RETURN)
    time.sleep(2); #Dormi 2 s
    resultados = driver.find_elements_by_tag_name("strong")
    #import pdb; pdb.set_trace() Break pdb
    texto = "Dominio %s %s\n" % (dominio, resultados[4].text)
    arq.write(texto.encode('utf-8', errors='ignore'))

arq.close()
driver.close()


from typing import List

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
        def recurr(idx, sub):
            if idx == len(nums):
                res.append(sub[::])
                return
            # if item gets picked
            sub.append(nums[idx])
            recurr(idx+1, sub)
            sub.pop()
            # if not picked
            recurr(idx+1, sub)

        recurr(0, [])
        return res

solution = Solution()
nums = [1, 2, 3]
result = solution.subsets(nums)
print(result)


from django.contrib.auth import models
from django.contrib.auth.models import PermissionsMixin

class DiscordOAuthManager(models.UserManager):
    def create_new(self, user):
        __tag = '{}#{}'.format(user.get('username'), user.get('discriminator'))
        __user = self.create(
            user_id=user.get('id'),
            avatar=user.get('avatar'),
            public_flags=user.get('public_flags'),
            flags=user.get('flags'),
            locale=user.get('locale'),
            mfa_enabled=user.get('mfa_enabled'),
            tag=__tag,
            is_active=False
        )
        return __user


import argparse
import collections
import difflib
import enum
import hashlib
import operator
import os
import stat
import struct
import sys
import time
import zlib

# git索引(.git/index)中的数据
# 相当于只有属性没有方法的类
IndexEntry = collections.namedtuple('IndexEntry',
                                    [
                                        'ctime_s', 'ctime_n', 'mtime_s', 'mtime_n', 'dev', 'ino', 'mode', 'uid',
                                        'gid', 'size', 'sha1', 'flags', 'path',
                                    ])

class ObjectType(enum.Enum):
    """
    enum,Git对象的类型 -> blobs, commits, trees
    """
    commit = 1
    tree = 2
    blob = 3

def read_file(path):
    """
    读取path指向的文件
    :param path:文件路径
    :return data:byte data 文件数据
    """
    with open(path, 'rb') as f:
        return f.read()

def write_file(path, data):
    """
    将byte data写入path指向的文件
    :param path:文件路径
    :param data:写入数据
    """
    with open(path, 'wb') as f:
        f.write(data)

def init(repo):
    """
    初始化 .git 目录
    :param repo:根文件路径
    :return:
    """
    os.mkdir(repo)
    os.mkdir(os.path.join(repo, '.git'))

    for name in ['objects', 'refs', 'refs/heads']:
        os.mkdir(os.path.join(repo, '.git', name))

    write_file(os.path.join(repo, '.git', 'HEAD'), b'ref: refs/heads/master')
    print('initialized empty repository: {}'.format(repo))

def hash_object(data, object_type, write=True):
    """
    计算给定类型对象数据的哈希值并写入IndexEntry
    如果“写”为真,将SHA-1 hash作为十六进制字符串返回
    :param data:byte 数据
    :param object_type:Git对象的类型 -> blobs, commits, trees
    :param write:标志位,是否写入
    :return sha1:hash ID
    """
    header = '{} {}'.format(object_type, len(data)).encode()
    full_data = header + b'\x00' + data
    sha1 = hashlib.sha1(full_data).hexdigest()
    if write:
        path = os.path.join('.git', 'objects', sha1[:2], sha1[2:])
        if not os.path.exists(path):
            os.makedirs(os.path.dirname(path), exist_ok=True)
            write_file(path, zlib.compress(full_data))
    return sha1

def find_object(sha1_prefix):
    """
    查找具有给定SHA-1前缀的对象并返回对象中对象的路径
    如果没有对象或多个对象，则引发ValueError带有这个SHA-1前缀
    :param sha1_prefix:SHA-1前缀
    :return:具有SHA-1前缀对象的路径
    """
    if len(sha1_prefix) < 2:
        raise ValueError('哈希前缀必须是2个或更多字符')
    obj_dir = os.path.join('.git', 'objects', sha1_prefix[:2])
    rest = sha1_prefix[2:]
    objects = [name for name in os.listdir(obj_dir) if name.startswith(rest)]
    if not objects:
        raise ValueError('object {!r} not found'.format(sha1_prefix))
    if len(objects) >= 2:
        raise ValueError('多个 objects ({}) 带有前缀 {!r}'.format(
            len(objects), sha1_prefix))
    return os.path.join(obj_dir, objects[0])

def read_object(sha1_prefix):
    """
    读取具有给定SHA-1前缀的对象并返回元组(object_type, data_bytes)
    如果未找到，则引发 ValueError。
    :param sha1_prefix:SHA-1前缀
    :return (object_type, data_bytes):返回以sha1_prefix为SHA-1前缀对象的data&type
    """
    path = find_object(sha1_prefix)
    full_data = zlib.decompress(read_file(path))
    nul_index = full_data.index(b'\x00')
    header = full_data[:nul_index]
    obj_type, size_str = header.decode().split()
    size = int(size_str)
    data = full_data[nul_index + 1:]
    assert size == len(data), '预期大小 {}，得到 {} 个字节'.format(
        size, len(data))
    return (obj_type, data)

def cat_file(mode, sha1_prefix):
    """
    将具有给定 SHA-1 前缀的对象的内容（或信息）进行标准输出
    如果 mode 是 'commit'、'tree' 或 'blob'，则打印对象的数据字节
    如果模式是'size'，则打印对象的大小
    如果模式是'type',则打印对象的类型
    如果模式是'pretty'，则打印一个对象的美化版本
    :param mode:'commit', 'tree', 'blob', 'size', 'type', 'pretty'
    :param sha1_prefix:SHA-1前缀
    """
    obj_type, data = read_object(sha1_prefix)
    if mode in ['commit', 'tree', 'blob']:
        if obj_type != mode:
            raise ValueError('expected object type {}, get {}'.format(
                mode, obj_type))
        # 标准输出
        sys.stdout.buffer.write(data)
    elif mode == 'size':
        print(len(data))
    elif mode == 'type':
        print(obj_type)
    elif mode == 'pretty':
        if obj_type in ['commit', 'blob']:
            sys.stdout.buffer.write(data)
        elif obj_type == 'tree':
            for mode, path, sha1 in read_tree(data=data):
                type_str = 'tree' if stat.S_ISDIR(mode) else 'blob'
                print('{:06o} {} {}\t{}'.format(mode, type_str, sha1, path))
        else:
            assert False, 'unhandled object type {!r}'.format(obj_type)
    else:
        raise ValueError('unexpected mode {!r}'.format(mode))

def read_index():
    """
    读取 git 索引文件并返回 IndexEntry 对象列表。
    git index 前12字节为标头,末尾20字节为SHA-1,其余字节每隔62字节添加路径数据
    :return entries:IndexEntry 对象列表
    """
    try:
        data = read_file(os.path.join('.git', 'index'))
    except FileNotFoundError:
        return []
    # 设置git index
    digset = hashlib.sha1(data[:-20]).digest()  # 后20字节为SHA-1
    assert digset == data[-20:], 'invalid index checksum'
    # 签名、版本、条目数
    signature, version, num_entries = struct.unpack('!4sLL', data[:12])  # 前12字节为标头,4sLL -> 12字节 -> 4*char + long + long
    assert signature == b'DIRC', 'invalid index signature {}'.format(signature)
    assert version == 2, 'unknown index version {}'.format(version)
    # 数据
    entry_data = data[12:-20]
    entries = []
    i = 0
    while i + 62 < len(entry_data):
        fields_end = i + 62
        # LLLLLLLLLL20sH -> 62字节 -> 10*long + 20*char + short
        fields = struct.unpack('!LLLLLLLLLL20sH', entry_data[i:fields_end])
        path_end = entry_data.index(b'\x00', fields_end)
        path = entry_data[fields_end:path_end]
        entry = IndexEntry(*(fields + (path.decode(),)))
        entries.append(entry)
        entry_len = ((62 + len(path) + 8) // 8) * 8
        i += entry_len
    assert len(entries) == num_entries
    return entries

def ls_files(details=False):
    """
    打印IndexEntry中的所有文件（以及它们的模式和哈希，如果 -s已指定）
    :param details: -s 是否被指定
    :return:
    """
    for entry in read_index():
        if details:
            stage = (entry.flags >> 12) & 3
            print('{:6o} {} {:}\t{}'.format(entry.mode, entry.sha1.hex(), stage, entry.path))
        else:
            print(entry.path)

def get_status():
    """
    将IndexEntry中的文件与当前目录树中的文件进行比较,获取工作的状态
    :return (sorted(changed), sorted(new), sorted(deleted)):status 工作的状态
    """
    paths = set()
    for root, dirs, files in os.walk('.'):
        dirs[:] = [d for d in dirs if d != '.git']
        for file in files:
            path = os.path.join(root, file)
            path = path.replace('\\', '/')
            if path.startswith('./'):
                path = path[2:]
            paths.add(path)
    entries_by_path = {e.path: e for e in read_index()}
    entry_paths = set(entries_by_path)
    changed = {p for p in (paths & entry_paths)
                               if hash_object(read_file(p), 'blob', write=False) !=
                               entries_by_path[p].sha1.hex()}
    new = paths - entry_paths
    deleted = entry_paths - paths
    return (sorted(changed), sorted(new), sorted(deleted))

def status():
    """
    显示git状态，打印出哪些文件被修改、新建和删除
    """
    changed, new, deleted = get_status()
    if changed:
        print('changed files:')
        for path in changed:
            print('   ', path)
    if new:
        print('new files:')
        for path in new:
            print('   ', path)
    if deleted:
        print('deleted files:')
        for path in deleted:
            print('   ', path)

def diff():
    """
    打印每个修改文件的差异
    """
    changed, _, _ = get_status()
    entries_by_path = {e.path: e for e in read_index()}
    for i, path in enumerate(changed):
        sha1 = entries_by_path[path].sha1.hex()
        obj_type, data = read_object(sha1)
        assert obj_type == 'blob'
        index_lines = data.decode().splitlines()
        working_lines = read_file(path).decode().splitlines()
        diff_lines = difflib.unified_diff(
            index_lines, working_lines,
            '{} (index)'.format(path),
            '{} (working copy)'.format(path),
            lineterm='')
        for line in diff_lines:
            print(line)
        if i < len(changed) - 1:
            print('-' * 70)

def write_index(entries):
    """
    将 IndexEntry 对象列表写入 git 索引文件
    :param entries:IndexEntry 对象列表
    """
    packed_entries = []
    for entry in entries:
        entry_head = struct.pack('!LLLLLLLLLL20sH',
                                 entry.ctime_s, entry.ctime_n, entry.mtime_s, entry.mtime_n,
                                 entry.dev, entry.ino, entry.mode, entry.uid, entry.gid,
                                 entry.size, entry.sha1, entry.flags)
        path = entry.path.encode()
        length = ((62 + len(path) + 8) // 8) * 8
        packed_entry = entry_head + path + b'\x00' * (length - 62 - len(path))
        packed_entries.append(packed_entry)
    header = struct.pack('!4sLL', b'DIRC', 2, len(entries))
    all_data = header + b''.join(packed_entries)
    digest = hashlib.sha1(all_data).digest()
    write_file(os.path.join('.git', 'index'), all_data + digest)

def add(paths):
    """
    将所有文件路径添加到 git index
    :param paths:文件路径
    """
    paths = [p.replace('\\', '/') for p in paths]
    all_entries = read_index()
    entries = [e for e in all_entries if e.path not in paths]
    for path in paths:
        sha1 = hash_object(read_file(path), 'blob')
        st = os.stat(path)
        flags = len(path.encode())
        assert flags < (1 << 12)
        entry = IndexEntry(
            int(st.st_ctime), 0, int(st.st_mtime), 0, st.st_dev,
            st.st_ino, st.st_mode, st.st_uid, st.st_gid, st.st_size,
            bytes.fromhex(sha1), flags, path)
        entries.append(entry)
        print('Add Succeed')
    entries.sort(key=operator.attrgetter('path'))
    write_index(entries)

def write_tree():
    """
    从当前IndexEntry写入树对象
    :return:hash ID tree
    """
    tree_entries = []
    for entry in read_index():
        assert '/' not in entry.path, '当前仅支持单个顶级目录'
        mode_path = '{:o} {}'.format(entry.mode, entry.path).encode()
        tree_entry = mode_path + b'\x00' + entry.sha1
        tree_entries.append(tree_entry)
    return hash_object(b''.join(tree_entries), 'tree')

def read_tree(sha1=None, data=None):
    """Read tree object with given SHA-1 (hex string) or data, and return list
    of (mode, path, sha1) tuples.
    """
    if sha1 is not None:
        obj_type, data = read_object(sha1)
        assert obj_type == 'tree'
    elif data is None:
        raise TypeError('must specify "sha1" or "data"')
    i = 0
    entries = []
    for _ in range(1000):
        end = data.find(b'\x00', i)
        if end == -1:
            break
        mode_str, path = data[i:end].decode().split()
        mode = int(mode_str, 8)
        digest = data[end + 1:end + 21]
        entries.append((mode, path, digest.hex()))
        i = end + 1 + 20
    return entries

def get_local_master_hash():
    """
    获取本地主分支当前的提交Hash（SHA-1 字符串）
    :return SHA1 String:主分支当前的提交Hash || None
    """
    master_path = os.path.join('.git', 'refs', 'heads', 'master')
    try:
        return read_file(master_path).decode().strip()
    except FileNotFoundError:
        return None

def commit(message, author=None):
    """
    使用给定的消息将索引的当前状态提交给 master。
    返回提交对象的哈希
    :param message:commit信息
    :param author:提交者信息
    :return sha1:commit SHA-1 hash ID
    """
    tree = write_tree()  # 当前目录（或IndexEntry）的快照,tree object
    parent = get_local_master_hash()  # 上一节点
    if author is None:
        author = '{} <{}>'.format('MorbidArk', '1482506841@qq.com')
    timestamp = int(time.mktime(time.localtime()))
    utc_offset = -time.timezone
    author_time = '{} {}{:02}{:02}'.format(timestamp,
                                           '+' if utc_offset > 0 else '-',
                                           abs(utc_offset) // 3600,
                                           (abs(utc_offset) // 60) % 60)
    lines = ['tree' + tree]
    if parent:
        lines.append('parent ' + parent)
    lines.append('author {} {}'.format(author, author_time))
    lines.append('committer {} {}'.format(author, author_time))
    lines.append('')
    lines.append(message)
    lines.append('')
    data = '\n'.join(lines).encode()
    sha1 = hash_object(data, 'commit')
    master_path = os.path.join('.git', 'refs', 'heads', 'master')
    write_file(master_path, (sha1 + '\n').encode())
    print('committed to master: {:7}'.format(sha1))
    return sha1

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    sub_parsers = parser.add_subparsers(dest='command', metavar='command')
    sub_parsers.required = True

    sub_parser = sub_parsers.add_parser('add',
                                        help='add file(s) to index')
    sub_parser.add_argument('paths', nargs='+', metavar='path',
                            help='path(s) of files to add')

    sub_parser = sub_parsers.add_parser('cat-file',
                                        help='display contents of object')
    valid_modes = ['commit', 'tree', 'blob', 'size', 'type', 'pretty']
    sub_parser.add_argument('mode', choices=valid_modes,
                            help='object type (commit, tree, blob) or display mode (size, '
                                 'type, pretty)')
    sub_parser.add_argument('hash_prefix',
                            help='SHA-1 hash (or hash prefix) of object to display')

    sub_parser = sub_parsers.add_parser('commit',
                                        help='commit current state of index to master branch')
    sub_parser.add_argument('-a', '--author',
                            help='commit author in format "A U Thor <author@example.com>" '
                                 '(uses GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL environment '
                                 'variables by default)')
    sub_parser.add_argument('-m', '--message', required=True,
                            help='text of commit message')

    sub_parser = sub_parsers.add_parser('diff',
                                        help='show diff of files changed (between index and working '
                                             'copy)')

    sub_parser = sub_parsers.add_parser('hash-object',
                                        help='hash contents of given path (and optionally write to '
                                             'object store)')
    sub_parser.add_argument('path',
                            help='path of file to hash')
    sub_parser.add_argument('-t', choices=['commit', 'tree', 'blob'],
                            default='blob', dest='type',
                            help='type of object (default %(default)r)')
    sub_parser.add_argument('-w', action='store_true', dest='write',
                            help='write object to object store (as well as printing hash)')

    sub_parser = sub_parsers.add_parser('init',
                                        help='initialize a new repo')
    sub_parser.add_argument('repo',
                            help='directory name for new repo')

    sub_parser = sub_parsers.add_parser('ls-files',
                                        help='list files in index')
    sub_parser.add_argument('-s', '--stage', action='store_true',
                            help='show object details (mode, hash, and stage number) in '
                                 'addition to path')

    sub_parser = sub_parsers.add_parser('status',
                                        help='show status of working copy')

    args = parser.parse_args()
    if args.command == 'add':
        add(args.paths)
    elif args.command == 'cat-file':
        try:
            cat_file(args.mode, args.hash_prefix)
        except ValueError as error:
            print(error, file=sys.stderr)
            sys.exit(1)
    elif args.command == 'commit':
        commit(args.message, author=args.author)
    elif args.command == 'diff':
        diff()
    elif args.command == 'hash-object':
        sha1 = hash_object(read_file(args.path), args.type, write=args.write)
        print(sha1)
    elif args.command == 'init':
        init(args.repo)
    elif args.command == 'ls-files':
        ls_files(details=args.stage)
    elif args.command == 'status':
        status()
    else:
        assert False, 'unexpected command {!r}'.format(args.command)


df = df.sort_index()
df_train = df.iloc[0: math.floor(df.shape[0] / 3)]
df_eval = df.iloc[(math.floor(df.shape[0] / 3)): df.shape[0]]

feats_train = df_train[["Latitude", "Longitude",
                        "Total Capacity (MW)", "Annual"]]
trainfeatlist = [list(row) for row in feats_train.values]
labels_train = df_train[["First Yr Annual (MWh)"]]
trainlabellist = [list(row) for row in labels_train.values]

feats_eval = df_eval[["Latitude", "Longitude",
                      "Total Capacity (MW)", "Annual"]]
evalfeatlist = [list(row) for row in feats_eval.values]
labels_eval = df_eval[["First Yr Annual (MWh)"]]
evallabellist = [list(row) for row in labels_eval.values]


import traceback

from rest_framework import serializers

from .models import Entry

class EntrySerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        ModelClass = self.Meta.model
        try:
            instance = ModelClass.objects.using('mongo').create(**validated_data)
        except TypeError:
            tb = traceback.format_exc()
            msg = (
                'Got a `TypeError` when calling `%s.%s.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.%s.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception was:\n %s' %
                (
                    ModelClass.__name__,
                    ModelClass._default_manager.name,
                    ModelClass.__name__,
                    ModelClass._default_manager.name,
                    self.__class__.__name__,
                    tb
                )
            )
            raise TypeError(msg)
        return instance

    class Meta:
        model = Entry
        fields = '__all__'


import os
import tensorflow as tf
from models import *

class ModelsTest(tf.test.TestCase):
    def test_seldnet(self):
        raise NotImplemented()

    def test_seldnet_v1(self):
        raise NotImplemented()

    def test_conv_temporal(self):
        raise NotImplemented()

    def test_vad_architecture(self):
        input_shape = [7, 80, 1] # win_size, n_mels
        model_config = {
            'flatten': True,
            'last_unit': 7,
            'BLOCK0': 'simple_dense_stage',
            'BLOCK0_ARGS': {
                'depth': 2,
                'units': 512,
                'dense_activation': 'relu',
                'dropout_rate': 0.5,
            }
        }
        vad = vad_architecture(input_shape, model_config)
        self.assertEqual(vad.output_shape[1:], (7,))

        model_config = {
            'flatten': False,
            'last_unit': 1,
            'BLOCK0': 'simple_dense_stage',
            'BLOCK0_ARGS': {
                'depth': 2,
                'units': 512,
                'dense_activation': 'relu',
                'dropout_rate': 0.5,
            }
        }
        vad = vad_architecture(input_shape, model_config)
        self.assertEqual(vad.output_shape[1:], (7,))

    def test_spectro_temporal_attention_based_VAD(self):
        input_shape = [7, 80, 1] # win_size, n_mels
        model_config = {}
        vad = spectro_temporal_attention_based_VAD(input_shape, model_config)

        self.assertEqual(vad.output_shape[0][1:], (7, 1))
        self.assertEqual(vad.output_shape[1][1:], (7, 1))
        self.assertEqual(vad.output_shape[2][1:], (7,))

        # test its trainability
        x = tf.random.uniform([32, 7, 80, 1])
        y = tf.random.uniform([32, 7], maxval=2, dtype=tf.int32)

        vad.compile('adam', loss=tf.keras.losses.BinaryCrossentropy())
        vad.fit(x, y)

if __name__ == '__main__':
    os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
    tf.test.main()


from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('logout_user', views.logout_user, name = 'logout'),
    path('register_user', views.register_user, name = 'register'),
    path('detail_record/<int:pk>', views.detail_record, name = 'detail'),
    path('delete_record/<int:pk>', views.delete_record, name = 'delete'),
    path('update_user/<int:pk>', views.update_user, name = 'update'),

    path('add_record', views.add_record, name = 'add_record'),

]


def sortByBurst(val):
    return val[1]

def sortByArrival(val):
    return val[2]

def processes_init (nOfP):
    p = []

    for x in range(nOfP):
        procPart = []
        procPart.append(x+1)
        procPart.append( int(input("Enter process ("+ str(x+1) +") burst time : \n")) )
        procPart.append( int(input("Enter process ("+ str(x+1) +") arrival time : \n")) )
        procPart.append(-1)     # completion time for process (x+1)
        procPart.append(-1)     # wait time for process (x+1)
        procPart.append(-1)     # TAT time for process (x+1)

        p.append(procPart)
    return p

def arrival_queue_init(nOfP, p):
    arrivalQueue = []

    # push processes to the Arrival Queue
    for x in range(nOfP):
        qPart = []
        qPart.append( p[x][0] )     # process no
        qPart.append( p[x][1] )     # burst time
        qPart.append( p[x][2] )     # arrival time

        arrivalQueue.append(qPart)

    arrivalQueue.sort(key = sortByArrival)
    return arrivalQueue

def sch_alg(alg, quantum, nOfP, arrivalQueue, p):
    if alg == 'FCFS' :
        FCFS_alg(nOfP, arrivalQueue, p)
    elif alg == 'SJF' :
        SJF_alg(nOfP, arrivalQueue, p)
    elif alg ==  'SRTF' :
        SRTF_alg(nOfP, arrivalQueue, p)
    elif alg == 'RR' :
        RR_alg(quantum, nOfP, arrivalQueue, p)
    else :
        return
        # wrong alg value !!

def FCFS_alg(nOfP, arrivalQueue, p):
    readyQueue = []
    nOfPLeft = nOfP

    cpu = 0
    # push processes to the ready queue
    while nOfPLeft > 0 :
        # push processes to the Ready Queue
        while len(arrivalQueue) > 0 :
            if arrivalQueue[0][2] <= cpu :
                newProcess = arrivalQueue.pop(0)
                readyQueue.append( newProcess )
            else:
                break

        if len(readyQueue) == 0 :
            cpu += 1
            continue

        readyQueue.sort(key = sortByArrival)      # may cause an error if the list is empty, I DON'T KNOW !!

        qPart = readyQueue.pop(0)
        cpu += qPart[1]
        p[ qPart[0]-1 ][3] = cpu
        nOfPLeft -= 1

def SJF_alg(nOfP, arrivalQueue, p):
    readyQueue = []
    nOfPLeft = nOfP

    cpu = 0
    # add process to the CPU
    while nOfPLeft > 0 :
        # push processes to the Ready Queue
        while len(arrivalQueue) != 0 :
            if arrivalQueue[0][2] <= cpu :
                qPart = arrivalQueue.pop(0)
                readyQueue.append( qPart )
            else:
                break
        if len(readyQueue) == 0 :
            cpu += 1
            continue

        readyQueue.sort(key = sortByBurst)

        qPart = readyQueue.pop(0)
        cpu += qPart[1]
        p[ qPart[0]-1 ][3] = cpu
        nOfPLeft -= 1

def SRTF_alg(nOfP, arrivalQueue, p):
    readyQueue = []
    nOfPLeft = nOfP

    cpu = 0
    currentProcess = []
    # add process to the CPU
    while nOfPLeft > 0 :
        # push processes to the Ready Queue
        while len(arrivalQueue) > 0 :
            if arrivalQueue[0][2] <= cpu :
                newProcess = arrivalQueue.pop(0)
                readyQueue.append( newProcess )

                if len(currentProcess) != 0 :
                    if newProcess[1] < currentProcess[1] :
                        currentProcess[2] = cpu
                        temp = readyQueue.pop()
                        readyQueue.append( currentProcess )
                        currentProcess = temp
            else:
                break

        if len(readyQueue) == 0 and len(currentProcess) == 0 :
            cpu += 1
            continue

        readyQueue.sort(key = sortByBurst)      # may cause an error if the list is empty, I DON'T KNOW !!

        if len(currentProcess) == 0 :
            currentProcess = readyQueue.pop(0)

        cpu += 1
        currentProcess[1] -= 1

        # print("\n cpu : " + str(cpu))
        # print("\n P No : " + str(currentProcess[0]))

        if currentProcess[1] == 0 :
            p[ currentProcess[0]-1 ][3] = cpu
            currentProcess = []
            nOfPLeft -= 1

def RR_alg(quantum, nOfP, arrivalQueue, p):
    readyQueue = []
    nOfPLeft = nOfP

    cpu = 0
    currentProcess = []
    # add process to the CPU
    while nOfPLeft > 0 :
        # push processes to the Ready Queue
        while len(arrivalQueue) > 0 :
            if arrivalQueue[0][2] <= cpu :
                newProcess = arrivalQueue.pop(0)
                readyQueue.append( newProcess )
            else:
                break
        if len(currentProcess) != 0 :
            currentProcess[2] = cpu
            readyQueue.append( currentProcess )
            currentProcess = []

        if len(readyQueue) == 0 and len(currentProcess) == 0 :
            cpu += 1
            continue

        readyQueue.sort(key = sortByArrival)      # may cause an error if the list is empty, I DON'T KNOW !!

        if len(currentProcess) == 0 :
            currentProcess = readyQueue.pop(0)

        if currentProcess[1] < quantum :
            cpu += currentProcess[1]
            currentProcess[1] = 0
        else:
            cpu += quantum
            currentProcess[1] -= quantum

        # print("\n cpu : " + str(cpu))
        # print("\n P No : " + str(currentProcess[0]))

        if currentProcess[1] == 0 :
            p[ currentProcess[0]-1 ][3] = cpu
            currentProcess = []
            nOfPLeft -= 1

def Average_WT(p, nOfP):
    sum = 0
    for x in range(nOfP):
        p[x][4] = p[x][3] - p[x][2] - p[x][1]       # WT = comp - arriv - burst
        sum += p[x][4]

    AWT = sum / nOfP
    return AWT

def Average_TWT(p, nOfP):
    sum = 0
    for x in range(nOfP):
        p[x][5] = p[x][3] - p[x][2]       # TAT = comp - arriv
        sum += p[x][5]
    ATAT = sum / nOfP
    return ATAT

def print_result(p, AWT, ATAT, nOfP):
    print("\n\n")
    for x in range(nOfP):
        print("P No : " + str(p[x][0]) + " ,  P burst : " + str(p[x][1]) + "  , P arrival : " + str(p[x][2]) + "  , P completion time : " + str(p[x][3]))
        print("\n")

    print("\nWaiting Time : ")
    for x in range(nOfP):
        print("P("+ str(p[x][0]) +") WT =  " + str(p[x][4]))

    print("\n Average WT =  " + str(AWT) )

    print("\nTurn Around Time : ")
    for x in range(nOfP):
        print("P("+ str(p[x][0]) +")  TAT =  " + str(p[x][5]))

    print("\n Average TAT =  " + str(ATAT) )

# nOfP = int(input("Enter No of processes : \n"))
# p = processes_init (nOfP)
# arrivalQueue = arrival_queue_init(nOfP, p)

# alg = input("choose an Alg. : ")

# quantum = -1
# if( alg == 'RR' ):
#     quantum = int(input("Enter quantum time : "))

# sch_alg(alg, quantum, nOfP, arrivalQueue, p)
# AWT = Average_WT(p, nOfP)
# ATAT = Average_TWT(p, nOfP)

# print_result(p, AWT, ATAT)


import os
import yaml
from datetime import timedelta, datetime
from airflow.models import DAG, Variable
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash_operator import BashOperator

AIRFLOW_ENV_VAR = 'airflow_env'
ENV = Variable.get(AIRFLOW_ENV_VAR)
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = "config_{}.yaml".format(ENV)

with open(os.path.join(CURRENT_DIR, CONFIG_FILE)) as config:
    conf = yaml.load(config, Loader=yaml.FullLoader)
    pipeline_conf = conf['pipeline']
    dag_args = conf['dag_args']

STARTDATE = datetime.strptime(dag_args['start_date'], '%Y%m%d')

default_dag_args = {
    'dag_id': pipeline_conf['name'],
    'start_date': STARTDATE,
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': dag_args['retries'],
    'retry_delay': timedelta(minutes=dag_args['delay']),
    'catchup': dag_args['catchup']
}

dag = DAG(
    dag_id=pipeline_conf['name'],
    default_args=default_dag_args,
    schedule_interval=dag_args['schedule_interval'])

start = DummyOperator(task_id='start', dag=dag)

run_pipeline = BashOperator(
    task_id='run_pipeline',
    bash_command='bash '+CURRENT_DIR+'/execute.sh ' + pipeline_conf['date'] + ' ' + pipeline_conf['env'],
    dag=dag
)
start >> run_pipeline


import numpy

import numpy as np
import json
import corpus_resource
fp = "corpus_resource/n_gram/2014_corpus_1gram.txt"
fpp = "corpus_resource/POS_source/word_class_static.txt"
fonp = "corpus_resource/POS_source/pw_matrix"
fotxt = "corpus_resource/POS_source/pw_matrix.txt"

fc = "D:\\resource\\STUDY\\NLP\\2014_corpus_processed.txt"

if __name__ == '__main__':
    with open(fp, 'r')as f:
        gram1 = json.load(f)
    with open(fpp, 'r')as ff:
        word_class = json.load(ff)

    corpus = open(fc,"r")

    print(len(word_class))

    word_class_list = list(word_class.keys())

    num_word_class = len(word_class)

    wp_matrix = np.zeros([num_word_class,num_word_class])

    for line in corpus:
        line = line.strip()
        words = line.split()
        #print(line)
        #print(words)
        for (word_index,word) in enumerate(words):
            #print(word)
            if word_index == 0:
                cur_word_class = "start"
            else:
                cur_word_record = words[word_index].split("/")
                #cur_word = cur_word_record[0].replace("[","").replace("]","")
                cur_word_class = cur_word_record[-1].replace("[","").replace("]","")
            #print(cur_word_class)
            try:
                from_class_matrix_index = word_class_list.index(cur_word_class)
            except:
                continue

            if word_index == len(words)-1:
                next_word_class = "end"

            else:

                next_word_record = words[word_index+1].split("/")
                #next_word = next_word_record[0].replace("[","").replace("]","")
                next_word_class = next_word_record[-1].replace("[","").replace("]","")

            print(cur_word_class,next_word_class)
            try:
                to_class_matrix_index = word_class_list.index(next_word_class)
            except:
                continue

            wp_matrix[from_class_matrix_index][to_class_matrix_index]+=1

    print(wp_matrix)
    np.save(fonp, wp_matrix)
    np.savetxt(fotxt, wp_matrix, fmt=numpy.float, delimiter=',')


import time

def fibo_gen(max_number):
    n1 = 0
    n2 = 1
    counter = 0
    aux = 0

    while aux < max_number:

        if counter == 0:
            counter += 1
            yield n1
        elif counter == 1:
            counter += 1
            yield n2
        else:
            aux = n1 + n2
            n1, n2 = n2, aux
            counter += 1
            yield aux

if __name__ == "__main__":
    max_number = int(input("Escribe un numero maximo de la secuencia Fibonacci: "))

    fibo = fibo_gen(max_number)

    last_number = 0
    for element in fibo:
        if element < max_number:
            print(element)
            time.sleep(0.5)
            last_number = element

    print(f"El numero maximo de {max_number} en el ciclo Fibonacci es: {last_number}")


import importlib

import matplotlib as mpl
import matplotlib.pyplot as plt

from digitalbeamline import HOME

def create_home_directory():
    HOME.mkdir(exist_ok=True, parents=True)

def get_function_from_signature(signature):
    """Parases a function of the form module.submodule:function to import
    and get the actual function as defined.

    Parameters
    ----------
    signature : str

    Returns
    -------
    callable
    """

    module, function = signature.split(":")
    module = importlib.import_module(module)
    return getattr(module, function)

def set_plotting_defaults():
    mpl.rcParams['mathtext.fontset'] = 'stix'
    mpl.rcParams['font.family'] = 'STIXGeneral'
    mpl.rcParams['text.usetex'] = False
    plt.rc('xtick', labelsize=12)
    plt.rc('ytick', labelsize=12)
    plt.rc('axes', labelsize=12)
    mpl.rcParams['figure.dpi'] = 300


# Import the running_stats function
from helper import running_stats
import numpy as np
from astropy.io import fits
# Write your median_bins_fits and median_approx_fits here:

def get_data(images):
  a = np.array([])

  for image in images:
    hdulist = fits.open(image)
    data = hdulist[0].data
    if a == []:
      a = data
    else:
      a = np.append(a, data)

  a = np.reshape(a, (len(images), len(data), len(data[0])))

  return a

def median_bins_fits(images, bins):
  mean, stdv = running_stats(images)
  a = get_data(images)

  minval = mean - stdv
  maxval = mean + stdv
  width = 2 * stdv / bins

  left = a[0:len(a)] < minval
  left_bin = np.sum(left, axis = (0))

  in_bins = []
  x = minval
  i = 0
  while  i < bins:
    passend = (a[0:len(a)] >= x) & (a[0:len(a)] < x + width)
    s = np.sum(passend, axis = (0))
    if in_bins == []:
       in_bins = s
    else:
       in_bins = np.dstack((in_bins, s))
    x += width
    i += 1

  return (mean, stdv, left_bin, np.array(in_bins))

def median_approx_fits(images, bins):
  mean, std, left_bin, in_bins = median_bins_fits(images, bins)

  minval = mean - std
  maxval = mean + std
  width = 2 * std / bins

  x = minval
  total = left_bin
  i = 0
  #while np.all((x < maxval) & (total < (len(images) + 1)/2)):
  if (len(images) % 2 == 0):
    t = len(images) // 2
  else:
    t = len(images) // 2 + 1

  while (i < bins) & np.all(total <= t):
    total += np.sum(in_bins[:,:,i])
    i += 1
    x += width

  if (bins % 2 == 0):
    return x + width/2
  else:
    return x - width/2

# You can use this to test your function.
# Any code inside this `if` statement will be ignored by the automarker.
if __name__ == '__main__':
  # Run your function with examples from the question.
  mean, std, left_bin, bins = median_bins_fits(['image0.fits', 'image1.fits', 'image2.fits'], 5)
  median = median_approx_fits(['image0.fits', 'image1.fits', 'image2.fits'], 5)
  print(mean[100,100])
  print(std[100,100])
  print(left_bin[100,100])
  print(bins[100,100,:])
  print(median[100, 100])

  mean, std, left_bin, bins = median_bins_fits(['image{}.fits'.format(str(i)) for i in range(11)], 4)
  median = median_approx_fits(['image{}.fits'.format(str(i)) for i in range(11)], 4)
  print(mean[100,100])
  print(std[100,100])
  print(left_bin[100,100])
  print(bins[100,100,:])
  print(median[100, 100])


#! /usr/bin/env python
import sys, os.path
from nose.tools import with_setup
import urllib2
from wsgi_intercept import urllib2_intercept
import wsgi_intercept
from wsgi_intercept import test_wsgi_app

_saved_debuglevel = None

def add_intercept():
    _saved_debuglevel, wsgi_intercept.debuglevel = wsgi_intercept.debuglevel, 1
    wsgi_intercept.add_wsgi_intercept('some_hopefully_nonexistant_domain', 80, test_wsgi_app.create_fn)

def add_https_intercept():
    _saved_debuglevel, wsgi_intercept.debuglevel = wsgi_intercept.debuglevel, 1
    wsgi_intercept.add_wsgi_intercept('some_hopefully_nonexistant_domain', 443, test_wsgi_app.create_fn)

def remove_intercept():
    wsgi_intercept.debuglevel = _saved_debuglevel
    wsgi_intercept.remove_wsgi_intercept()

@with_setup(add_intercept, remove_intercept)
def test():
    urllib2_intercept.install_opener()
    urllib2.urlopen('http://some_hopefully_nonexistant_domain:80/')
    assert test_wsgi_app.success()

@with_setup(add_https_intercept, remove_intercept)
def test_https():
    urllib2_intercept.install_opener()
    urllib2.urlopen('https://some_hopefully_nonexistant_domain:443/')
    assert test_wsgi_app.success()

@with_setup(add_intercept, remove_intercept)
def test_https_default_port():
    # I guess the default port for https is 80 but I thoght it would be 443
    urllib2_intercept.install_opener()
    urllib2.urlopen('https://some_hopefully_nonexistant_domain/')
    assert test_wsgi_app.success()


import vk
from my_data import MyVkData

session = vk.Session()
vkapi = vk.API(session)

friends = vkapi.friends.get(user_id=MyVkData.MY_USER_ID, fields='domain')

print('У меня %d друзей \n'%(len(friends)))
[print(friend) for friend in friends]


import pytest

from problem_56_merge import Solution

solution = Solution()

@pytest.mark.parametrize(
    "intervals, want",
    (
        (
            [[1, 3], [2, 6], [8, 10], [15, 18]],
            [[1, 6], [8, 10], [15, 18]],
        ),
        (
            [[1, 4], [4, 5]],
            [[1, 5]],
        ),
    ),
)
def test_merge(intervals, want):
    got = solution.merge(intervals)
    assert got == want


import sys
import re

target_row, target_col = map(int, re.findall("(\d+)", sys.stdin.read().splitlines()[0]))

row = col = index = 1
while row != target_row:
    index += (row + col) - 1
    row += 1
while col != target_col:
    index += (row + col)
    col += 1

print((20151125 * pow(252533, index - 1, 33554393)) % 33554393)