blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
133
| path
stringlengths 2
333
| src_encoding
stringclasses 30
values | length_bytes
int64 18
5.47M
| score
float64 2.52
5.81
| int_score
int64 3
5
| detected_licenses
listlengths 0
67
| license_type
stringclasses 2
values | text
stringlengths 12
5.47M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
f980dfbc632b7e60f97ff731f198bf443b075311
|
Python
|
MelHiour/pyneng
|
/exercises/17_serialization/task_17_1.py
|
UTF-8
| 4,129 | 3.375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
'''
Задание 17.1
В этом задании нужно:
* взять содержимое нескольких файлов с выводом команды sh version
* распарсить вывод команды с помощью регулярных выражений и получить информацию об устройстве
* записать полученную информацию в файл в CSV формате
Для выполнения задания нужно создать две функции.
Функция parse_sh_version:
* ожидает аргумент output в котором находится вывод команды sh version (не имя файла)
* обрабатывает вывод, с помощью регулярных выражений
* возвращает кортеж из трёх элементов:
* ios - в формате "12.4(5)T"
* image - в формате "flash:c2800-advipservicesk9-mz.124-5.T.bin"
* uptime - в формате "5 days, 3 hours, 3 minutes"
Функция write_to_csv:
* ожидает два аргумента:
* имя файла, в который будет записана информация в формате CSV
* данные в виде списка списков, где:
* первый список - заголовки столбцов,
* остальные списки - содержимое
* функция записывает содержимое в файл, в формате CSV и ничего не возвращает
Остальное содержимое скрипта может быть в скрипте, а может быть в ещё одной функции.
Скрипт должен:
* обработать информацию из каждого файла с выводом sh version:
* sh_version_r1.txt, sh_version_r2.txt, sh_version_r3.txt
* с помощью функции parse_sh_version, из каждого вывода должна быть получена информация ios, image, uptime
* из имени файла нужно получить имя хоста
* после этого вся информация должна быть записана в файл routers_inventory.csv
В файле routers_inventory.csv должны быть такие столбцы:
* hostname, ios, image, uptime
В скрипте, с помощью модуля glob, создан список файлов, имя которых начинается на sh_vers.
Вы можете раскомментировать строку print(sh_version_files), чтобы посмотреть содержимое списка.
Кроме того, создан список заголовков (headers), который должен быть записан в CSV.
'''
import glob
import csv
import re
sh_version_files = glob.glob('sh_vers*')
# print(sh_version_files)
headers = ['hostname', 'ios', 'image', 'uptime']
def parse_sh_version(output):
'''Parse "sh ver" and return tuple (software version, image, uptime)'''
regex = re.compile('Cisco IOS Software.+ Version (?P<ios>[\w.()]+)|file is "(?P<image>.+)"|uptime is (?P<uptime>.+)s')
iterator = regex.finditer(output)
result = tuple(item.group(item.lastgroup) for item in iterator)
result = tuple([result[0], result[2], result[1]]) # agly shit... please ignore...
return result
def write_to_csv(to, what):
'''Write list of lists to .csv file'''
with open(to, 'w') as file:
writer = csv.writer(file)
writer.writerows(what)
##########################################################
what = []
what.append(headers)
for file in sh_version_files:
hostname = re.search('\D\d', file).group()
with open(file) as sh_ver:
info = list(parse_sh_version(sh_ver.read())) # Parse file and create a list from tuple
info.insert(0, hostname) # Insert hostname
what.append(info) # Append list to list of lists
write_to_csv('test.csv', what)
| true |
01e92656dd29da492a0dfbc774b4acf61e7203dd
|
Python
|
queirozfcom/statistical-learning
|
/dynamic-programming/src/plot.py
|
UTF-8
| 615 | 3.359375 | 3 |
[] |
no_license
|
import numpy as np
def plotv(v):
float_formatter = lambda x: " %06.3f "%x
np.set_printoptions(formatter={'float_kind':float_formatter})
v = v.reshape((5,5))
print(v)
def plotpi(pi):
copy = np.copy(pi).ravel()
moves = np.array(list(map(_index_to_move,copy)))
moves = moves.reshape((5,5))
print(moves)
def _index_to_move(index):
if(index == 1):
return(" up ")
elif index == 2:
return("right ")
elif index == 3:
return(" down ")
elif index == 4:
return(" left ")
else:
raise ValueError("Unknown move: {0}".format(index))
| true |
776ff0c5c9089c979723db4aecbd6a4936ef614a
|
Python
|
trychiOO/python_all
|
/learn/python_all/Demo_ut/exe/re_exe.py
|
UTF-8
| 590 | 2.609375 | 3 |
[] |
no_license
|
#-*- coding:utf8 -*-
import requests#导入request模块
import json
url = 'http://apis.juhe.cn/simpleWeather/query?key= 1b43db481985a3748772c8a336ecf5a2&city=北京'
# url = 'https://azero.soundai.cn/v20190530/directives'
headers = {"Connection":'keep-alive',"Host":"httpbin.org"}#值以字典的形式传入
response = requests.post(url=url,headers=headers)#用关键字headers传入
print(response.headers)#打印出响应头
print(response.headers['Connection'])#取得部分响应头以做判断:
print(response.headers.get('Connection'))#或者这样也可以
print(response.text)
| true |
72f1600638e03eaf7e8420eefa4d7b0bdcb68ff2
|
Python
|
jsh2333/pyml
|
/day1_python/01_python200_src/014.py
|
UTF-8
| 104 | 3.296875 | 3 |
[] |
no_license
|
x = 0
while x < 10:
x = x+1
if x < 3:
continue
print(x)
if x > 7:
break
| true |
7682fa60f22d3fd0fe5c191f308a2165f7dac745
|
Python
|
Suyash906/DataStructures
|
/Python3/DynamicProgramming/02_Longest_Common_Subsequence.py
|
UTF-8
| 1,200 | 3.25 | 3 |
[] |
no_license
|
class Solution:
def longestCommonSubsequenceDP(self, s1, s2):
l1 = len(s1)+1
l2 = len(s2)+1
dp = [[0 for _ in range(l2)] for _ in range(l1)]
for i in range(1, l1):
for j in range(1,l2):
if s1[i-1] == s2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[l1-1][l2-1]
def longestCommonSubsequenceRecursive(self, s1, s2, i, j):
## base
if i >= len(s1) or j >= len(s2):
return 0
## body
if s1[i] == s2[j]:
return 1 + self.longestCommonSubsequenceRecursive(s1,s2,i+1,j+1)
case_1 = self.longestCommonSubsequenceRecursive(s1,s2,i,j+1)
case_2 = self.longestCommonSubsequenceRecursive(s1,s2,i+1,j)
case_3 = self.longestCommonSubsequenceRecursive(s1,s2,i+1,j+1)
return max(case_1, case_2, case_3)
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# return self.longestCommonSubsequenceRecursive(text1, text2, 0, 0)
return self.longestCommonSubsequenceDP(text1, text2)
| true |
c6dd47bd8e5743f9088b1794b11ab07d8d5fdcec
|
Python
|
geetha79/pythonprograms
|
/dicefun.py
|
UTF-8
| 215 | 3.71875 | 4 |
[] |
no_license
|
#!/usr/bin/python3
import random
i=0
def myroll():
return random.randint(1,6)
while(i<=100):
n=input("press r ro roll the dice")
if(n=='r'):
r=myroll()
i=i+r
print("u got ",r)
print("new position is",i)
| true |
46cf97ebe2fe16a207569d1aa6d0685e7eae6e46
|
Python
|
EBone/py_littools
|
/py_lit/cppaddf.py
|
UTF-8
| 395 | 2.59375 | 3 |
[] |
no_license
|
import os
filedirs=os.listdir(os.getcwd())
for wafile in filedirs:
with open(wafile,"r") as wahfile:
contentlist=wahfile.readlines()
for x,line in enumerate(contentlist):
if "." not in line:
line=line.strip()+".0"
contentlist[x]=line.strip()+"f;\n"
with open(wafile,"w") as wahfile:
wahfile.writelines(contentlist)
print(contentlist)
| true |
894df06d09873db695c8410421ad30b053c4a678
|
Python
|
BethanyG/pystudy
|
/blackjack/blackjack.py
|
UTF-8
| 1,534 | 4.1875 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
class Player:
def __init__(self, name):
self.hand = []
self.name = name
def take(self, card):
"""Take a card and place it in the hand"""
self.hand.append(card)
def show_hand(self):
"""Returns a string representing the player's hand"""
result = ""
for card in self.hand:
result = result + card + " "
return result
class Dealer:
def __init__(self):
self.hand = []
self.deck = None
self.reset()
def reset(self):
"""Reset the deck."""
self.deck = ["2S", "5H", "KD", "3S", "JH", "6C"]
def deal(self, player):
"""Deals a card to the player"""
card = self.deck.pop()
player.take(card)
class Board:
def __init__(self):
self.jack = Dealer()
self.players = []
def add_player(self, player):
self.players.append(player)
def display(self):
"""Display the status of the Board"""
print("List of player's hand")
for player in self.players:
# hand_representation = player.show_hand()
# print("{} hand: {}".format(player.name, hand_representation))
print(f"{player.name}'s hand: {player.show_hand()}")
if __name__ == '__main__':
board = Board()
scott = Player("Scott")
bethany = Player("Bethany")
board.add_player(scott)
board.add_player(bethany)
jack = board.jack
jack.deal(scott)
jack.deal(bethany)
board.display()
| true |
c703d5d4c309a6d4db423068fce4f074533bb5da
|
Python
|
yuichimukai/python-procon
|
/algorism-practice/chapter3-3.py
|
UTF-8
| 298 | 3.125 | 3 |
[] |
no_license
|
#バブルソート
n = int(input())
A = list(map(int, input().split()))
cnt = 0
flg = 1
while flg:
flg = 0
for i in range(n - 1, 0, -1):
if A[i] < A[i - 1]:
A[i], A[i - 1] = A[i - 1], A[i]
cnt += 1
flg = 1
print(' '.join(map(str, A)))
print(cnt)
| true |
8153036b51b833aaacb317b4693a6acebf79e450
|
Python
|
Eric-Wonbin-Sang/CS110Manager
|
/2020F_hw5_submissions/rouxjake/JakeRouxP2.py
|
UTF-8
| 289 | 3.78125 | 4 |
[] |
no_license
|
#I pledge my honor that I have abided by the Stevens Honor System. Jake Roux
def main():
print("This program will return the sum of numbers you enter")
num=eval(input("Separated by commas, enter your numbers:"))
sum=0
for i in num:
sum+= int(i)
print(sum)
main()
| true |
c7311c287ace04d3f7dab951e5fd85bef4a577f9
|
Python
|
FrancoGBenedetti/KingFish
|
/DQ-Backend/pyScripts/table_comparation.py
|
UTF-8
| 2,505 | 2.84375 | 3 |
[] |
no_license
|
import dash
import dash_core_components as dcc
import dash_admin_components as dac
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
import numpy as np
def reconciliation(df,df1):
# Retorna 2 DataFrames en donde se encontró diferencias
dfs_dictionary = {'DF':df,'DF1':df1}
dff=pd.concat(dfs_dictionary)
dff=dff.drop_duplicates(keep=False)
if len(dff)==0:
return dff, dff
else:
DF1=dff.loc[dff.index.levels[0][0]]
DF2=dff.loc[dff.index.levels[0][1]]
if len(DF1)>len(DF2):
DF1=DF1.iloc[:len(DF2)]
else: DF2=DF2.iloc[:len(DF1)]
return DF1,DF2
def indicator(df,df1):
# Retorna una lista con las columnas inválidas y otra con las filas inválidas
if len(df)>len(df1):
df=df.iloc[:len(df1)]
else: df1=df1.iloc[:len(df)]
invalid_col=[]
invalid_row=[]
for x in df.index:
for i in sorted(df.columns):
if df[i][x] != df1[i][x]:
if pd.isnull(df[i][x])==False:
invalid_col.append(i)
invalid_row.append(x)
return invalid_col, invalid_row
def compare_result(col_list, row_list, DF1, DF2):
#Retorna tabla con los datos encontrados que son distintos
compare = pd.DataFrame()
for i in range(0,len(col_list)):
df = pd.DataFrame(({'fila':row_list[i],'columna':col_list[i],'fuente_1':[DF1.loc[row_list[i],col_list[i]]],'fuente_2':[DF2.loc[row_list[i],col_list[i]]]}))
compare = compare.append(df)
compare.reset_index(inplace=True, drop =True)
return compare
def cell_style(value, value1):
#Retorna style de celda de la tabla en donde los valores no coincidan
style = {}
if (pd.isnull(value) & pd.isnull(value1)) == False:
if value != value1:
style = {
'backgroundColor': '#d7301f',
'color': 'white'
}
return style
def generate_table(DF, DF1):
# Retorna el header y el body de la tabla
rows = []
for i in range(len(DF)):
row = []
for col in DF.columns:
value = DF.iloc[i][col]
value1 = DF1.iloc[i][col]
style = cell_style(value, value1)
row.append(html.Td(value, style=style))
rows.append(html.Tr(row))
table_header = [html.Thead(html.Tr([html.Th(col) for col in DF.columns]), className='thead-dark')]
table_body = [html.Tbody(rows)]
return table_header, table_body
| true |
8888d46889946f988eb20fc501f535f5c8b0bd90
|
Python
|
brandonartner/algorithms-python
|
/mcs-tree/kruskal.py
|
UTF-8
| 2,178 | 3.34375 | 3 |
[] |
no_license
|
import pprint
import re
import sys
import math
def has_edge(edges,start,end):
contains_edge = 0
for edge in edges:
if edge[0] == start and edge[1] == end:
contains_edge = 1
break
return contains_edge
def display(T, n):
for i in range(n):
if i > 0:
for j in range(n):
if j > 0:
sys.stdout.write(' ')
if has_edge(T,n*(i-1)+j+1, n*i+j+1):
sys.stdout.write(' | ')
else:
sys.stdout.write(' ')
print()
for j in range(n):
if j > 0:
if has_edge(T,n*i+j,n*i+j+1):
sys.stdout.write(' - ')
else:
sys.stdout.write(' ')
sys.stdout.write(' * ')
print()
filename = input("Select your item: ")
with open(filename) as inputFile:
#reading in the graph.txt file that will split the first character to see how many nodes the graph will have
listGraph2 = [tuple(re.split(':',inputFile.readline()))]
#passing in the rest of the list (1,2;9)..etc
s= listGraph2[0][1]
#s=s[1:-1]
pattern = '([0-9]+),'
sub = r'\1;'
Graph = re.sub(pattern,sub,s)
Graph = Graph.split(',')
edges=[]
for i in range(len(Graph)):
edges.append(eval(Graph[i].replace(';',',')))
for i in range(len(edges)):
for j in range(i+1, len(edges)):
if edges[i][2] > edges[j][2]:
edges[i],edges[j] = edges[j],edges[i]
#just getting num of nodes which is n^2 n indicating the # of nodes
n = int(listGraph2[0][0])
numOfNodes = n**2
for x in edges:
if x[0] > numOfNodes or x[1] > numOfNodes or abs(math.floor((x[1]-1)/n)-math.floor((x[0]-1)/n)) > 1 or abs((x[1]-1)%n-(x[0]-1)%n) > 1:
print ("Error not a Graph")
sys.exit(0)
D = [i for i in range(1,numOfNodes+1)]
T = []
for edge in edges:
T.append(edge)
if D[edge[0]-1] == D[edge[1]-1]:
T.remove(edge)
else:
k = D[edge[0]-1]
l = D[edge[1]-1]
for j in range(numOfNodes):
if D[j] == l:
D[j] = k
print(edges)
display(edges,n)
print(T)
display(T,n)
| true |