blob_id
large_string
repo_name
large_string
path
large_string
src_encoding
large_string
length_bytes
int64
score
float64
int_score
int64
detected_licenses
large list
license_type
large_string
text
string
download_success
bool
765e703ab2ef9934d2d308304afbae478f28f136
yokubol/python-mini-projects
/ex16.py
UTF-8
1,191
4.125
4
[]
no_license
# import argument variable from sys module from sys import argv # unpack the argument variable script, filename = argv # tell user that the program is going erase all content from file print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN."...
true
b1dce852c3f8a48520733341fc6ff2a001bf7539
bdcovington/PigLatinGen
/plg_GUI.py
UTF-8
1,634
3.171875
3
[]
no_license
# plg_GUI.py from tkinter import * from plg_functions import PigLatin window = Tk() # LABEL w = '600' h = '275' window.geometry('{}x{}'.format(w, h)) window.title('Pig Latin Generator') class PigLatinGUI: def __init__(self): self.plg = PigLatin() def run_program(self): s...
true
833c701b519d026695215f88643848a012cb5fec
BranislavL308/Diplomski
/communicationThread.py
UTF-8
1,054
2.5625
3
[]
no_license
from PyQt5.QtCore import QThread, pyqtSignal from serial import Serial class MyThread(QThread): change_value = pyqtSignal(list) error = pyqtSignal() def __init__(self, com_data): super().__init__() def init_com(self, com_data): self.data = com_data ...
true
fd39f6bc2cc63953c5adfa14ba39275bf98a11cc
uk-gov-mirror/ministryofjustice.opg-cotton
/cotton/provider/driver.py
UTF-8
1,610
2.84375
3
[]
no_license
from __future__ import print_function import importlib from exceptions import NotImplementedError class Provider(object): def __init__(self, **kwargs): """ initializes connection object """ raise NotImplementedError() def status(self): raise NotImplementedError() ...
true
b3132b93d1954d234783adc00c033bf50add95a1
eirikhoe/advent-of-code
/2019/01/sol_2.py
UTF-8
398
2.859375
3
[]
no_license
import numpy as np current_masses = [] with open("input.txt", "r") as file: current_masses = np.array([int(line.rstrip()) for line in file]) fuel_required = np.zeros(current_masses.shape, dtype=int) while np.max(current_masses) > 8: current_masses = np.where(current_masses > 8, current_masses // 3 - 2, 0) ...
true
e7159f191bf90ae9245b7dedc055acdd6f80866d
qq841483350/zhanzhang_url_tuisong
/zhanzhang_url_tuisong.py
UTF-8
588
2.71875
3
[]
no_license
#coding:utf8 #百度url主动实时推送百度索引,urls里一行一个URL import requests,time def tuisong(): url = "http://data.zz.baidu.com/urls?site=domain&token=token"%(domain,token) #接口调用地址 在站长平台获取 filecontents = {'file': open('urls.txt', 'r')} #urls.txt为需要推送的URL文件,每行一个 r=requests.post(url, files=filecontents) ...
true
6d28e81caf3b08078fabd6876f065ca66849ec8a
FieryDruid/Machine_logs
/Anomaly_vector.py
UTF-8
2,035
3.328125
3
[]
no_license
import csv from tkinter import Tk from tkinter.filedialog import askopenfilename import re import numpy as np import sys anomalies_file = 1 if len(sys.argv)> 1: anomalies_file = int(sys.argv[1]) print(f"Выбран файл с аномалиями: {anomalies_file}") #Диалоговое окно для открытия файла с закодированными результа...
true
8e05b61482b3ab9c1a1652c7861e0a5871ec0abb
amusecode/amuse
/src/amuse/units/generic_unit_converter.py
UTF-8
11,583
3
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
import numpy from amuse.units.quantities import new_quantity from amuse.units.quantities import is_unit from amuse.units.quantities import is_quantity from amuse.units.generic_unit_system import * from amuse.support import exceptions from amuse.support.core import late class UnitsNotOrtogonalException(exceptions.Amus...
true
dc174f39ffb15958d49d2624f7fdd0ee46282e81
jasontressler/FileBrowser
/Main.py
UTF-8
4,895
2.828125
3
[]
no_license
import tkinter as tk from tkinter import ttk from LazyTree import LazyTree from FileViewList import FileViewList as FL from PIL import ImageTk, Image import pymsgbox import shutil import os ### Global vars ### currentDir = '' selectedDir = '' copyDir = '' cut = False ### Global funcs ### def doNothing(): pass ...
true
2a3a885ecc50f2527519fff82dd0c9b2145e3c6c
SDB016/Baekjoon-Solution
/Greedy/11047.py
UTF-8
202
2.953125
3
[]
no_license
n, k = map(int, input().split()) coin = [] count = 0 for _ in range(n): coin.append(int(input())) for i in reversed(coin): count += k // i k %= i if k == 0: break print(count)
true
0ca2872690f36f67d1d601c58c9f96dc02592a66
Anirudh-Muthukumar/Python-Code
/BFS application I.py
UTF-8
3,155
3.171875
3
[]
no_license
graph = {} queue = [] visited = [] m, n = None, None def toStr(node): string = "" for i in range(len(node)): for j in range(len(node[0])): string += str(node[i][j]) return string def toMatrix(string): matrix = [ [0 for _ in range(n)] for _ in range(m)] for ind, ch in enumerate(...
true
40ad69cd0e210fa7bd0ed3b1dfcc74e57ffa2dbf
segloff23/Advent-Of-Code-2015
/01/solution.py
UTF-8
770
4.125
4
[]
no_license
def loadProblem(): with open("problem.txt") as problemFile: problem = problemFile.read().strip(); return problem; def partOne(problem): up = problem.count("("); down = len(problem) - up; finalFloor = up - down; print("Part 1: {:d}".format(finalFloor)); def partTwo(problem): f...
true
b24ed33a5ad2befab03e9d854d2b3d0521011b84
denglert/python-sandbox
/corey_schafer/renaming_multiple_files/renaming.py
UTF-8
646
3.28125
3
[]
no_license
import os os.chdir('files-to-be-renamed') for f in os.listdir(): f_basename, f_ext = os.path.splitext(f) print( "\nBasename and extension split." ) print( f_basename ) print( f_ext ) print( "\nSplitting at -" ) f_title, f_course, f_num = f_basename.split('-') print( f_title ) print( f...
true
50b62da08696e0dcd69fbed6945193abdbefc35d
tapetop18135/project2DeplyBackend
/app/lib/linearRegressGen.py
UTF-8
701
3.25
3
[]
no_license
import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score class Linear_regression(): def __init__(self,data): self.dataAxisY = data self.__genAxisX() def __genAxisX(self): tempX = [] for i in range(0,len(self.dat...
true
fd5b86b493dee836d53a726216c02e69b48cae38
correaswebert/miscellaneous
/Miscellaneous/Sudoku/creator.py
UTF-8
780
3.6875
4
[]
no_license
"""Program to create Sudoku puzzle""" import random from recursive_solution import solve, printBoard def naiveCreator(): puzzle = [] board = [[0]*9 for _ in range(9)] while not solve(board): # choose location and number to be put at that location x,y, num = random.choice(range(1,...
true
d0e50270975d5b5054adaf03846954bbfd3ad08d
wouterswijgman/project-PW
/hello.py
UTF-8
273
2.984375
3
[]
no_license
print("Hello Wouter and Pim!") print("This will test your programming skills!") print("Several data sets are obtained from OpenML, up to you to find an interesting set and to do " "some appropriate analyses. Best of luck!") print("This is a new test line for Github Desktop")
true
aa44e91448e0060cd84b725fc73f14caa39fa28d
audiofilter/audio_scripts
/cmd_pklt.py
UTF-8
2,520
2.609375
3
[ "MIT" ]
permissive
#!/Users/tkirke/anaconda/bin/python import time import sys import os from pypklt import * from lame import * from tone_est import * import numpy from rescale_audio import rescale_audio_ints,rescale_audio_floats def check_onset(audio): # Determine if there is an 'early' onset b_lpf, a_lpf = signal.butt...
true
1535f54a689393d793a5c687266e42d6d1786217
sach-12/zla-bot
/cogs/comm.py
UTF-8
4,369
2.5625
3
[ "MIT" ]
permissive
import discord from discord.ext import commands import requests from bs4 import BeautifulSoup import datetime from cogs.func import func class comm(commands.Cog): def __init__(self, client): self.client = client self.help = { "zla!controller [initials or CID]": "Returns i...
true
339efacfb954bdd05680706bf413a0ef870d9d3d
kkoutoup/Unittest-example-company-employees
/test_employee_class.py
UTF-8
1,852
3.453125
3
[]
no_license
import unittest from company import Employee, CompanyDatabaseError # Test Employee class class TestEmployeeCreation(unittest.TestCase): def setUp(self): ''' Creates re-usable cases for tests that follow ''' self.emp_1 = Employee("Kostas", "Koutoupis", 30000, 3) self.emp_2 = Employee("Sue", "...
true
0555f940481d004b3a5c71663e48f13385641f53
KhauTu/KhauTu-Think_Python
/Chap14_BinarySearch.py
UTF-8
1,410
3.859375
4
[]
no_license
import sys import time def test(did_pass): """Print the result of the test.""" linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def searc...
true
15e8542e637fdcd5f1863419f6a689034d310af0
yifengyou/crazy-python
/官方配套代码/11/11.5/Text_test.py
UTF-8
4,717
2.90625
3
[ "Unlicense" ]
permissive
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee kongyeeku@163.com # # # # version 1.0 ...
true
a83917429eefd340570e76daeac5d11c2104d9e3
babureddy1969/python
/python/scoreTracker.py
UTF-8
268
2.828125
3
[]
no_license
#scorecard def breakingRecords(scores): up=0 down=0 for i in range(len(scores)): if i<len(scores) and scores[i] < scores[i+1]: up+=1 elif i<len(scores) and scores[i] > scores[i+1]: down+=1 return up,down
true
7b99d31872018558c138f9842b752d4fdf411a4e
codesirohi/dominant-color
/script.py
UTF-8
268
2.71875
3
[]
no_license
import matplotlib.pyplot as plt from colorthief import ColorThief siro_color = ColorThief("/Users/shubham/images/test_img.jpg") # get the dominant color dominant_color = siro_color.get_color(quality=1) rgb=print(dominant_color) plt.imshow([dominant_color]) plt.show()
true
162e147ddb086f65295d16cd6873838d147d77ad
chikugoy/machine-learning-with-python-cookbook
/ch02_データのロード/ch02_01_サンプルデータセットのロード.py
UTF-8
317
2.640625
3
[]
no_license
# -*- coding: utf-8 -*- # scikit-learnのdatasetsをロード from sklearn import datasets # digitデータセットをロード digits = datasets.load_digits() # 特徴量行列を作成 features = digits.data # ターゲットベクトルを作成 target = digits.target # 最初の観測を表示 features[0]
true
6bb6b1a58116f8890bce637a243f391fe0805052
richardneililagan/euler
/python/algorithms/0012.py
UTF-8
677
3.671875
4
[]
no_license
#!/usr/bin/env python3 from math import sqrt from functools import reduce, lru_cache # :: --- @lru_cache(maxsize = None) def triangle_number (x): return 1 if x == 1 else triangle_number(x - 1) + x # :: https://stackoverflow.com/a/6800214 def factorize (n): return set(reduce( list.__add__, ( ...
true
7203a490fdd697b85713ea59838ddd7e286ae032
dldydrhkd/Problem-Solving
/백준/~10000/1629.py
UTF-8
272
3.296875
3
[]
no_license
import sys import math input = sys.stdin.readline a,b,c = map(int, input().strip().split()) def my_pow(x,y): if y==0: return 1 temp = my_pow(x,y//2) if y%2==0: return temp*temp % c else: return temp*temp*x % c print(my_pow(a,b))
true
72b7fcada39e45760d528a47b766dd1419d6cc19
deepsolar/PCGAN_Model
/util/util.py
UTF-8
6,211
2.984375
3
[]
no_license
"""This module contains simple helper functions """ from __future__ import print_function import torch import numpy as np from PIL import Image import os ##### from torchvision import utils def unnormalize(img_tensor, unnormalize_STD=[0.5], unnormalize_MEAN=[0.5]): #img_tensor = img_tensor.transpose(1, 3) ...
true
35f7d640e48f2f80d0824ced0be9111a737dfa36
qforger/CodeTranslate
/tools/add_environ_var.py
UTF-8
626
2.546875
3
[ "MIT" ]
permissive
import json import os import subprocess try: with open("../private_keys/firebase-access-key.json") as json_file: data = json.load(json_file) env = { **os.environ, "GOOGLE_APPLICATION_CREDENTIALS": json.dumps(data), } subprocess.Popen('/bin/bash', env=env).wai...
true
009c302c3ce6640428e1be4ec5743ab48ab3e6f8
zukosky/wwPython
/exceptions.py
UTF-8
1,116
3.65625
4
[]
no_license
#No exception handling #for nIndex in range(0,6): #print(nIndex-5) # div = 5 / (nIndex-5) import sys import time import random for nIndex in range(0,6): print(nIndex-3) try: #Will throw and exception on nIndex=3 div = 5 / (nIndex-3) except: #Exception caught. Loop will cont...
true
843184198f4a2a3f868f0d60aa962bee286ade60
AndrewJGaut/SchemaBasedExtraction
/Tests/miscellaneous_tests/testSplit.py
UTF-8
10,230
3.296875
3
[]
no_license
import xlrd import xlwt #from sklearn.model_selection import train_test_split import random ''' Postcondition: all of the counts in dict are normalized into essentially a probability distribution (ie they all add up to one) ''' def normalizeDict(dict, sentencesCount): for e1 in dict: dict[e1] = dict[e...
true
5e142d7f2f392a1c2057be7956748cebe67b76e9
davidlwr/InternetExplorers
/web/Entities/resident.py
UTF-8
1,848
3.21875
3
[]
no_license
class Resident(object): ''' This class represents a row entry for a resident (i.e. elderly staying at the ALFs) ''' name_tname = "name" node_id_tname = "node_id" dob_tname = "dob" fall_risk_tname = "fall_risk" status_tname = "status" stay_locatio...
true
ffe16db521bc74dd86ac6ab411859146ff149e37
AJMartel/crackmes
/san01suke's SomeCrypto~03/keygen.py
UTF-8
499
2.84375
3
[]
no_license
import argparse from collections import deque parser = argparse.ArgumentParser(description="SomeCrypto~03 keygen") parser.add_argument('name') args = parser.parse_args() name = args.name correct_key = [9,7,6,0,1,5,4,3,8,2] cypher = deque(list(range(10))) for c in name: if ord(c) % 2: cypher[0], cyph...
true
314e8a6cda380f8f1121ab14593cb705bc48dd10
evanpelfrey00/python-assignments
/HW05_EvanPelfrey.py
UTF-8
1,775
4.25
4
[]
no_license
#Exercise 1a def hasFinalLetter(strList, letters): '''Given a list of strings, and a string of characters, returns a seperate list of only the strings that end with the those characters''' returnList = [] for i in strList: for j in letters: if i.endswith(j): return...
true
b23046b0f49ae076519845e0b6272c70d63cdcbe
MartinPSE/E.T.C
/Algorithm/Shortcut/Dijkstra_shortcut.py
UTF-8
4,275
3.671875
4
[]
no_license
# 최단 경로 알고리즘 # '가장 짧은 경로를 찾는 알고리즘'을 의미한다 # Ex) 한 지점에서 다른 한 지점까지의 최단 경로 # 한 지점에서 다른 모든 지점까지의 최단 경로 # 모든 지점에서 다른 모든 지점까지의 최단 경로 # 각 지점은 그래프에서 '노드'로 표현, 지점 간 연결된 도로는 그래프에서 '간선'으로 표현 """ 다익스트라 최단 경로 알고리즘 : '특정한 노드'에서 출발하여 다른 모든 노드로 가는 최단 경로를 계산 : 다익스타라 최단 경로 알고리즘은 음의 간선이 없을 때 정상적으로 동작 -> 현실 세계의 도로(간선)은 음의 간선으로 ...
true
f814488e059c949d5f574229567f001deda484e7
blhwong/algos_py
/leet/remove_nth_node_from_end_of_list/test.py
UTF-8
768
3.03125
3
[]
no_license
from unittest import TestCase, main from leet.remove_nth_node_from_end_of_list.main import Solution from data_structures.list_node import ListNode s = Solution() class TestSuite(TestCase): def test_1(self): n = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) expected = ListNode(1...
true
c9e14ccb8644b69f7ec8c0582672d1b875503bd8
sachahu1/Evolutionary_Optimization
/Evolutionary_Optimization/src/loss_functions.py
UTF-8
2,125
3.6875
4
[]
no_license
"""This module contains some basic implementations of simple fitness functions. This module defines some basic fitness functions to use during the evolutionary process. """ from typing import Union import numpy as np def MSE(x:Union[int,float]) -> Union[int,float]: """A basic implementation of Mean Squared Error. ...
true
99bc19f40433887ad9750662ea756ee8b2eb3f50
a-kikin/learningPython
/tasks/AbramyanPartI/integer/integer14.py
UTF-8
71
3
3
[]
no_license
a = 634 firstTwo = a // 10 last = a % 10 print(last, firstTwo)
true
ce0c99af88ba3560d6d6c300bfeaf44eeee7a8d8
ArtyomKeller1/artyomkeller
/lesson4/homework1.py
UTF-8
188
3.046875
3
[]
no_license
from sys import argv def newfunc(salary, salary1, bonus): return ((salary*salary1)+bonus) _, salary, salary1, bonus = argv print(newfunc(float(salary), float(salary1), float(bonus)))
true
590503d3abdb5d2a1f2011e5abc0d81881f6155d
zw-999/learngit
/study_script/json_test.py
UTF-8
670
3.359375
3
[]
no_license
#!/usr/bin/env python # coding=utf-8 import json data = {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": True}, {"age": 29, "name": "Joe", "lactose_intolerant": False}]} print json.dumps(data, indent=4) #字符串转成json json_input = '{"one": 1, "two": { "list": [ {"item":"A"},{"item"...
true
c99332f96d5690a83d9e7d4e71a7c6821a55428b
intrig-unicamp/mininet-wifi
/mn_wifi/associationControl.py
UTF-8
1,482
2.828125
3
[ "LicenseRef-scancode-x11-stanford" ]
permissive
"""Mininet-WiFi: A simple networking testbed for Wireless OpenFlow/SDWN! author: Ramon Fontes (ramonrf@dca.fee.unicamp.br)""" class AssociationControl(object): "Mechanisms that optimize the use of the APs" changeAP = False def __init__(self, intf, ap_intf, ac): if ac in dir(self): ...
true
d800cf56107556e787c04f7c2efdb0fbebc74ec7
MichavR/simpleNumGuessingGame
/main.py
UTF-8
1,596
3.90625
4
[]
no_license
import random is_playing = True user_nums = [] drawn_nums = None while is_playing: while len(user_nums) < 6: try: user_choice = (int(input(f'#{len(user_nums) + 1}: Enter your number in range 1-49: '))) if user_choice < 1 or user_choice > 49: print('Number out of ran...
true
0423634e5fc16277d6cbdc99f96a00f5ba6193bc
sigerclx/python
/python-book01/2018/2018-06/EnglishTest/searchwordApi.py
UTF-8
1,808
3.03125
3
[]
no_license
# 利用金山词霸的api解析单词含义和美式,英式发音,音标等 import requests import os import json import pprint def createUrl(word): url_1=r'http://dict-co.iciba.com/api/dictionary.php?w=' url_2=r'&type=json&key=6FDE7DE576DE770A91C94917D29BF37C' #print(url_1+word+url_2) if word.strip()=='': return '' return (url_1+word...
true
fdbd1d01a8ec8c3ee02cad5caf3912aeaedb2707
l-schipper/MSc-Thesis-final
/9runthisscript-allbutblackbox.py
UTF-8
11,768
2.734375
3
[]
no_license
#* Dependencies functions execfile(open('a0dependencies.py').read()) import a0dependencies #* Load dataframes (fully prepped) df_total.info() df_total = pd.read_csv('df_total_5.csv') df_total = df_total.drop(columns=['Unnamed: 0']) df_total = df_total[np.isfinite(df_total['difference'])] df_reg2 = df_total....
true
99517674c646eaa24317e4ad52a8a3036a91ac79
michael-iden/shift-code-submitter
/main.py
UTF-8
1,578
2.640625
3
[]
no_license
from typing import List from src import orcicorn_client, shift_code_client, user_builder from src.gcloud_storage import GCloudStorage from src.slack_client import SlackClient from src.user_builder import User def redeem_codes(users: List[User], codes: List[str]): slack_client = SlackClient() for code in code...
true
cf186bbaf60b86d77300e1acb0d46e2df790d081
LTEGaming/PySOE
/Main-Dev/pysoe_shell.py
UTF-8
8,774
2.71875
3
[ "BSD-3-Clause" ]
permissive
import time import random def cls(): for i in range(200): print("") def cool(): wn = random.randrange(0,27) if wn == 1: return "█ Now under New Management! █" #Avg line to line distance: 56 elif wn == 2: return "█ ...
true
855ddf2df2b766d333ed1eec9283708de0ad3219
RualPerez/AutoML
/policy.py
UTF-8
3,487
2.90625
3
[]
no_license
import torch import torch.nn as nn import torch.optim as optim import numpy as np import torch.nn.functional as F class PolicyNet(nn.Module): """Policy network, i.e., RNN controller that generates the different childNet architectures.""" def __init__(self, batch_size, n_outputs, layer_limit): super(P...
true
0b92db4c97bcac7b24454ba54102c3d228d30f19
CCoxinho/Project_Euler_Python
/exercicio29.py
UTF-8
231
2.8125
3
[]
no_license
def distinct_powers(): L = [] for a in range(2, 101): for b in range(2, 101): c = a**b if c in L: pass else: L.append(c) print ((len(L)))
true
3a88dbbe8a70a61fbcde60c3401310df60e70a42
weebs/experiments
/nPyREPL/clojure/parser.py
UTF-8
5,283
3.6875
4
[]
no_license
__author__ = 'dave' # Data Types # nil, Booleans, Numbers, Strings, Maps, Keywords, Vectors, Lists, Sets def IsWhitespace(c): return (c == ' ' or c == '\n' or c == '\t') def IsEndingDataStructureCharacter(c): return (c == ')' or c == '}' or c == ']') def IsBeginningDataStructureCharacter(c): return (c =...
true
da66ec88f5326f2b452f3607f4dc6728d49745f1
webclinic017/magnet-migrade
/magnet/utils/importer.py
UTF-8
1,626
2.71875
3
[ "MIT" ]
permissive
import os class FileInfo: def __init__(self, file_name: str, path: str): self.file_name = file_name self.path = path def walk_files(root_file_path: str): """ Enumrate models.py's path as sqlalchemy model definition. This operation is useful for automatically importing sqlalchemy mode...
true
96b1f93e0d4e0e5960dadc39f4721e29d3816ce2
coldmax88/PyGUI
/GUI/Generic/BaseAlertFunctions.py
UTF-8
610
3.140625
3
[ "MIT" ]
permissive
# # Python GUI - Basic alert functions - Generic # from GUI.GAlertClasses import Alert, Alert2, Alert3 def present_and_destroy(dlog): dlog.center() try: return dlog.present() finally: dlog.destroy() def alert(kind, prompt, ok_label, **kwds): present_and_destroy(Alert(kind, prompt, ok_label)) def alert2(k...
true
f3b3918aa79cf215d3829773cdbc14c419edb8a8
fatekiller/pydiscalu
/model/Worker.py
UTF-8
251
2.8125
3
[]
no_license
class Worker(object): def __init__(self, address=None, port=None): self.address = address self.port = port def set_address(self, address): self.address = address def set_port(self, port): self.port = port
true
0abacdd82288afc1531b6eca558950fdb14caf62
alanbalugu/MEA-Analysis
/MEA_ISI_Histogram.py
UTF-8
3,381
2.6875
3
[ "MIT" ]
permissive
import numpy as np import matplotlib.pyplot as plt import quantities as pq import neo import string import pandas as pd from pprint import pprint from elephant.spike_train_correlation import spike_time_tiling_coefficient from elephant.statistics import isi from matplotlib import colorbar import plotly.graph_o...
true
acf65dfbb5bbc42d7be74e4e52236ceadb673010
niujie/DeepLearning_TensorFlow
/Chap5/chap5-2.py
UTF-8
1,053
3.09375
3
[]
no_license
import tensorflow as tf from tensorflow import keras import numpy as np # 5.2 statistics # 5.2.1 vector norm x = tf.ones([2, 2]) print(tf.norm(x, ord=1)) # L1 norm print(tf.norm(x, ord=2)) # L2 norm print(tf.norm(x, ord=np.inf)) # \inf norm # 5.2.2 max, min, mean, sum x = tf.random.normal([4, 10]) print(tf.re...
true
c3109c85f21cba6569ee984d7dafe5cd53754868
cnsapril/JZAlgo
/Ch 6 - Linked List/Partition.py
UTF-8
755
3.328125
3
[]
no_license
from ListNode import ListNode, print_list class Solution: def partition(self, head, x): left_head = ListNode(-1) right_head = ListNode(-1) left_tail, right_tail = left_head, right_head node = head while node is not None: if node.val < x: left_ta...
true
60196e709742c65a6fb948544dd9cdb864bdee70
endlosautomat/finance
/fetch_stocks.py
UTF-8
775
2.65625
3
[]
no_license
import requests import logging logging.basicConfig(format='%(asctime)s %(message)s', filename='fetch_stocks.log',level=logging.DEBUG) logging.debug('Setting the API Key') apikey="6PIRCZQQY12S49FR" logging.info('------------------------- start calling service ') dlh_stock_call = requests.get('https://www.alphavantag...
true
87274a4e7d8eb75458714668049cee63f371f0a6
takuseno/nnabla-drl-collections
/common/buffer.py
UTF-8
1,618
2.8125
3
[ "MIT" ]
permissive
import numpy as np import random from collections import deque # https://github.com/chainer/chainerrl/blob/master/chainerrl/misc/random.py def sample_n_k(n, k): """Sample k distinct elements uniformly from range(n)""" if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative...
true
5a1115ad0fc1e9e278e4e6a316a570717e3149fe
mikeo/PUG-Bot
/database/Event.py
UTF-8
7,260
2.765625
3
[]
no_license
from datetime import datetime, timedelta from pytz import timezone from utils.config import TIMEZONE from database.database import check_events_event_id, fetch_events_event_id, add_event, fetch_events_list_event_id, \ delete_event, update_events_title, update_events_description, update_events_time_est, \ update...
true
61130646cc65a14f214ed2293fce4d843c8c2001
dantasl/Operational-Systems-Project
/snakes/GameServer.py
UTF-8
2,797
2.734375
3
[ "MIT" ]
permissive
import curses import time import sys import threading import socket import pickle from random import randint from Snake import Snake from Field import Field serverAddress = (socket.gethostname(), 5010) boardSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bufferSize = 8192 field = Field(25) snakesAlive = {}...
true
2e91cd30b7b42c17c8aaf8d509c54a752a39eb7c
Vitorliberato19/520---Vitor
/teste1.py
UTF-8
486
3.546875
4
[]
no_license
#!/usr/bin/python3 # print('olá', 'mundo',sep='.') nomes = ['daniel', 'joao', 'pedro', 'maria'] # for nome in nomes: # if nome == 'joao': # break # print(nome) # for nome in nomes: # if nome == 'joao': # continue #pula o código e volta no loop # print(nome) for x in range(20,0,-1...
true
132991b16b20baeba35de5b1b80d5f33e55c05a7
toticavalcanti/uri_online_judge
/1001.py
UTF-8
190
3.421875
3
[]
no_license
# -*- coding: utf-8 -*- ''' Escreva a sua solução aqui Code your solution here Escriba su solución aquí ''' n1 = int(input()) n2 = int(input()) soma = n1 + n2 print("X = " + str(soma))
true
23bb236ed7e7e7a03f4d13852b8cf9f42e2c840e
jak2030/recurse-coding-exercise
/backend/shakespeare/extract.py
UTF-8
3,461
3.03125
3
[ "MIT" ]
permissive
import os import argparse from bs4 import BeautifulSoup import requests from constants import VILLAINS, JESTERS, DREAMERS def _match(line, archetypes): for archetype in archetypes: if ( line["character"] == archetype["character"] and line["play"] == archetype["play"] ): ...
true
886b31d3436119b287c940a1e344129c65e79282
KFurudate/Atcoder_SHOJIN
/Atcoder/20201003_くじかつ_111/D - Disjoint Set of Common Divisors.py
UTF-8
415
3.265625
3
[]
no_license
import math def factrize(num): factor = {} div = 2 s = int(num**0.5)+1 while div < s: div_cnt = 0 while num % div == 0: div_cnt += 1 num //= div if div_cnt != 0: factor[div] = div_cnt div += 1 if num > 1: factor[num] = 1 ...
true
677af742b5c72ea6fba2ecff1b26d46c2ca9444c
ayushi8795/Python-Training
/Python Task 6/4.py
UTF-8
172
2.703125
3
[]
no_license
def genfun(): str = "consultadd training" length = len(str) for i in range(length-1,-1,-1): yield str[i] for char in genfun(): print(char)
true
bc42d423ad077f62b970f9894487f25eacb4d11b
dana19-meet/meet2017y1lab5
/fun22.py
UTF-8
296
3.625
4
[ "MIT" ]
permissive
def draw_1d(n,c): for loop in range(3): print(c*n) def draw_2d(n,m,char): for loop in range(n): print(m*char) def draw_3d(n,m,border,fill): print(border*m) for loop in range(n-2): print(border+fill*(m-2)+border) print(border*m)
true
cb68a4145febf00d914d8cf569f00c8cded9e450
slaigai/atbs
/ch4/commaCode.py
UTF-8
707
4.5625
5
[]
no_license
# Practice at the end of Chapter 4 # Comma Code # Say you have a list value like this: # # spam = ['apples', 'bananas', 'tofu', 'cats'] # Write a function that takes a list value as an argument and returns a string with all the items separated by a comma # and a space, with and inserted before the last item. For examp...
true
a7ba9ac76ed75143d8a33708aaf1b23c5efcc454
evasey/smartninja_homework_6
/secretnumber.py
UTF-8
300
3.84375
4
[]
no_license
secret = 3 guess = int(input("Please think of a number between 1-10: ")) if guess == secret: print("Congratulation! You win!") elif guess < secret: print("Your guess is too low. Try again.") elif guess > secret: print("Your guess is too high. Try again.") else: print ("Error")
true
618ee1ad36bf3aff9d9fd0d865d9cec66d06bd08
AdamZhouSE/pythonHomework
/Code/CodeRecords/2129/48102/235396.py
UTF-8
267
3.296875
3
[]
no_license
def change(num): if num == 1: return 0 if num % 2 == 0: num //= 2 return 1 + change(num) else: num1 = num - 1 num2 = num + 1 return 1 + min(change(num1), change(num2)) num = int(input()) print(change(num))
true
76100ca2dbfd3e4b0cfd5bc864380a70feeb6aef
lsst-camera-dh/eotest
/tests/fe55_analysis_tests.py
UTF-8
2,660
2.515625
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
""" Test code for Fe55 analyses. """ from __future__ import print_function import os import unittest import itertools import numpy as np import lsst.eotest.sensor as sensorTest class Fe55GainFitterTestCase(unittest.TestCase): def setUp(self): # Save current floating point error handling. self.np_f...
true
6155021b6329860c5af6b44b96216838ba22bf73
Achillessanger/ctf
/xman/crypto/enc/sol.py
UTF-8
211
2.609375
3
[]
no_license
import libnum f = open('zero_one','r') s = f.read() output = '' for i in s.split(): if('ZERO' == i): output += '0' if('ONE' == i): output += '1' output = int(output,2) print output print libnum.n2s(output)
true
c51bc6b64d1c84a40201866e1a3acc6c3961dc85
viswanath-puttagunta/crmsimulation
/utils/lipsum.py
UTF-8
678
3.28125
3
[]
no_license
import random class Lipsum(object): def __init__(self): self.file = None self.wordstring = "" self.words = [] self.maxwords = 0 with open('./utils/hipster-ipsum.txt', 'r') as self.file: self.wordstring = self.file.read().replace('\n', '') ...
true
be4c3277afe22e0f0d439c3f627cdb154b902c45
geomaar/SGA
/functions.py
UTF-8
2,235
3.84375
4
[]
no_license
import numpy as np import math def st_coord_line(trd,plg,sttype): """ StCoordLine computes the coordinates of a line in an equal angle or equal area stereonet of unit radius Args: trd: trend of line plg: plunge of line sttype: An integer indicating the type of ...
true
69681271607cc1fc25d68f3b83f68f00a7f05bdb
EricLin24/SSW555-DriverlessCar
/DateValidation.py
UTF-8
3,168
3.53125
4
[]
no_license
# DateValidation from datetime import date import Error monthsStr = {'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6, 'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12} def validateDate(date): ''' US01: Dates (birth, marriage, divorce, death) should not be...
true
1c53cca30a73599ef80a0d2366be8807885c7ed9
watsona4/jupyter_notebooks
/crypto_data.py
UTF-8
3,113
2.640625
3
[]
no_license
import glob from datetime import datetime, timedelta import numpy as np import pandas as pd from sklearn import metrics from sklearn.decomposition import PCA from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.neural_network import MLPClassifier from sklearn.pipeline import make_pipeline fr...
true
fee01f691a9fcabff70ef3f7c2d0bf9872c8967b
PavanKumar1564/TCS-GS-Sample-CP-Answers
/Easy/First Non Repeating.py
UTF-8
1,239
4.03125
4
[]
no_license
""" Instructions to candidate. 1) Run this code in the REPL to observe its behaviour. The execution entry point is main(). 2) Consider adding some additional tests in doTestsPass(). 3) Implement findFirst(str) correctly. 4) If time permits, some possible follow-ups. """ """ Finds the first c...
true
15ea883e19e5190d66c40de1beb7947a5094e878
aratnamirasugab/cp-interview-things
/code/Balanced Binary Tree.py
UTF-8
995
3.375
3
[]
no_license
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool ...
true
97da3fe8394838c1bb3cb5da8418a11411285378
Elvistor/ejerciciosPy
/listas_tuplas/Ejercicio_10.py
UTF-8
221
3.421875
3
[]
no_license
"""Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por pantalla el menor y el mayor de los precios.""" precios = [50, 75, 46, 22, 80, 65, 8] print(min(precios))
true
be125c67443624c3ab1454fed82524701b39ffef
xuzhezhaozhao/ai
/vision/classification/slim/walkthrough/walkthrough.py
UTF-8
9,191
2.953125
3
[]
no_license
# code from: https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import tensorflow as tf # Main slim library from tensorf...
true
64415e8f5cf3d577ffc9b3a96969ada39371cea6
anuwu/Coursera-Data-Driven-Astronomy
/Week 2/2a_1.py
UTF-8
640
3.96875
4
[]
no_license
# Write your list_stats function here. def list_stats (lst) : lst.sort () lstSum = sum(n for n in lst) mean = lstSum / len(lst) mid = len(lst)//2 if len(lst) % 2 : median = lst[mid] else : median = (lst[mid-1] + lst[mid])/2 return (median,mean) # You can use this to test your function. # ...
true
c98baa5cb8d391e075d0805a988d0bb7d7654d7c
AhmedRaafat14/Solutions-Of-Cracking-the-Coding-Interview-Gayle-5th-Edition
/Chapter_4/4.5.py
UTF-8
2,437
4.125
4
[]
no_license
""" Implement a function to check if a binary tree is a binary search tree. """ class BinaryTree: def __init__(self, val): self.data = val self.left_child = None self.right_child = None # insert node to left of some node def insert_left(self , data): if not self.left_c...
true
6322364d339f5a3873791a3384fdc6406340070b
peleiden/dmiai
/wheres-waldo/cpp_model.py
UTF-8
582
2.75
3
[]
no_license
import numpy as np from wallyfinder import WallyFinder def setup_cpp_model(): return WallyFinder() def cpp_predict(model, img): results = model(img) if not results: return 0, 0 best = sorted(results, key=lambda x: x["confidence"])[-1] print(best["confidence"]) x = int(round((best["xmax...
true
9ab8535a3a6795080867324245eab7f3b5f38e14
robbyvan/-
/配列/26_Remove Duplicates from Sorted Array.py
UTF-8
423
3.359375
3
[]
no_license
# 26.Remove Duplicates from Sorted Array # 双指针, 一个遍历, 一个空位 # 如果遍历处是第一个 或者不是重复, 那么就移动到空位, 更新空位 # 否则跳过这个点, 这个点将成为空位. class Solution: def removeDuplicates(self, nums): if not nums: return 0 i = 0 for num in nums: if i == 0 or num > nums[i - 1]: nums[i] = num i += 1 return i
true
5974901a821410064d3cdc7824ab1fd304e265b9
cpeixin/leetcode-bbbbrent
/tree/max_depth.py
UTF-8
1,416
3.34375
3
[]
no_license
# coding: utf-8 # Author:Brent # Date :2020/9/28 3:43 PM # Tool :PyCharm # Describe : class TreeNode: def __init__(self, value): self.val = value self.left = None self.right = None # 自底向上 class Solution: def maxDepth(self, root): if not root: return 0 left = self.max...
true
c25ec41024adae91fdd60c18e8e28b080e105a91
LihengGong/concurrency_db
/adb/src/dfs.py
UTF-8
3,627
3.3125
3
[]
no_license
""" Author: Liheng Gong(lg2848) Peiyue Yang(py570) This module is responsible for build DAG. """ class Vertices: def __init__(self, v_id): self.v_id = v_id self.adjacent = set() def __repr__(self): return 'v_id: {}, adjacent list: {}'.format(self.v_id, self.adjacent) def ...
true
3b2dcf5fe1001b85e89cdb357cf763fd3ca4929a
eugence/python_training
/test_add_contact.py
UTF-8
4,105
2.796875
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver import unittest from contact import Contact def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False class test_add_contact(unittest.TestCase): def setUp(self): ...
true
98bf7f0e2cfab307a679915b782d4ab122ee1deb
KCzenczek/Cat-Watcher
/catwatcher/catwatcher.py
UTF-8
3,707
2.578125
3
[]
no_license
from flask import Flask, render_template, request import RPi.GPIO as GPIO import curses import time from datetime import datetime app = Flask(__name__) GPIO.setmode(GPIO.BOARD) # rover setup list_F = [11, 15, 12, 18] list_B = [40, 13, 16, 38] list_L = [11, 15, 16, 38] list_R = [40, 13, 12, 18] GPIO.setup(list_F, GP...
true
77d3c235fa241936e980c4c059398ec9b7d2319d
hecerinc/cenace-outlook-data
/precios/concurrent/cleanJSON.py
UTF-8
2,088
2.734375
3
[]
no_license
import json import pandas as pd import numpy as np import sys import csv from concurrent import futures if len(sys.argv) < 2: print("Usage: python cleanJSON.py <result.json>") sys.exit() # The json is an array of calls to the API. # Each element is one call. # For each call, an array of 20 nodes is returned # Each...
true
fc9a3868f966e97d49c648af08eca00ffb53dbc9
proteanhq/protean
/src/protean/domain/context.py
UTF-8
3,919
3.15625
3
[ "BSD-3-Clause" ]
permissive
"""Context Management Framework""" import logging import sys from protean.globals import _domain_context_stack # a singleton sentinel value for parameter defaults _sentinel = object() logger = logging.getLogger(__name__) class _DomainContextGlobals(object): """A plain object. Used as a namespace for storing da...
true
f06ea89571f19d2744566dd3d8beb4577c0a36be
Taneil-Kew/Chapter-2-4
/practice chapter3.py
UTF-8
338
3.453125
3
[]
no_license
import turtle wn = turtle.screen() alex = turtle.Turtle() colors = ["red","blue","green","orange"] for color in colors: alex.color(color) for i in range(4): alex.forward(100) alex.penup() alex.forward(50) alex.pendown() alex.stamp() alex.left(90) print(i) ...
true
eac1a3c5317bbb1b4f529f3ad18daec79a8e7dc4
CRosky/cp_tut1
/problem3.py
UTF-8
455
3.171875
3
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 27 11:14:11 2017 @author: rosky """ import numpy as np import matplotlib.pyplot as plt n_datapoint = [10, 30, 100, 300, 1000] err = [] for i in n_datapoint: x = np.linspace(0.0, np.pi/2, i) y = np.cos(x) total = y.sum()*(x[-1]-x[0])/i ...
true
c0014d7067b0b1d7d63bae71ad6ad703f458bb26
songzy12/LeetCode
/python/805.split-array-with-same-average.py
UTF-8
1,624
3.109375
3
[]
no_license
class Solution: def splitArraySameAverage(self, A): """ :type A: List[int] :rtype: bool """ # x + y = len(A) # ave * x + ave * y = sum(A) # ave = sum(A) / len(A) ave = sum(A) / len(A) len_A = len(A) sum_A = sum(A) prefix = [0] ...
true
9fd8a3ba926df07e1c4436f9180ee31fb38187c8
brentthongg/112tag
/Initialize.py
UTF-8
3,414
3.234375
3
[]
no_license
# This file starts all the constants, loads all the iamges, etc... basically starts the game. import pygame import random import copy from Player import Player from Maze import Maze from WaterBalloon import WaterBalloon from BalloonExplosion import BalloonExplosion from Opponent import Opponent from Background import ...
true
a271df1efabeef37b8247b45c30d1b5c7f111e6a
Aasthaengg/IBMdataset
/Python_codes/p03251/s264637001.py
UTF-8
204
3.171875
3
[]
no_license
n,m,x,y = map(int,input().split()) a = max(list(map(int,input().split()))) b = min(list(map(int,input().split()))) ans = "War" for i in range(x+1,y): if i>a and i<=b: ans = "No War" print(ans)
true
590c553690338d72b365ed0047494e5984dae507
srikanthpragada/PYTHON_17_JUN_2021
/demo/assignments/validate_password.py
UTF-8
242
3.96875
4
[]
no_license
st = input("Enter password :") upper = digit = False for c in st: if c.isupper(): upper = True elif c.isdigit(): digit = True if upper and digit: print("Valid password!") else: print("Not a valid password!")
true
3f33db4f1b13b23ce74da8e254c6d209d41ff18d
mikemill/rq_retry_scheduler
/tests/test_worker.py
UTF-8
2,523
3
3
[ "MIT" ]
permissive
import rq from rq_retry_scheduler import Queue, Worker def noop_target_function(*args, **kwargs): pass def fail_target_function(*args, **kwargs): raise Exception("I am a failure of a function") def test_init(worker): assert worker.exc_handler in worker._exc_handlers assert issubclass(worker.queue...
true
88c0bad39caf7c23f07ccb0654dae4412445c288
MillaKelhu/Lausegeneraattori_tiralabra2021
/src/tests/lauseenmuodostus_test.py
UTF-8
749
2.921875
3
[]
no_license
import unittest from src.lauseenmuodostus import Lauseenmuodostus from src.trie import Trie class TestLauseenmuodostus(unittest.TestCase): def setUp(self): self.puu = Trie() self.lauseenmuodostus = Lauseenmuodostus(self.puu) def test_muodosta_lause_toimii_oikein_tyhjalla_puulla(self): ...
true
cb999df9f11899448875bec2d11e6fdf8d99a470
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_118/2629.py
UTF-8
1,359
3.28125
3
[]
no_license
import itertools def is_palindrome(num): return str(num) == str(num)[::-1] def palindromes(k): return [sum([n*(10**i) for i,n in enumerate(([x]+list(ys)+[z]+list(ys)[::-1]+[x]) if k%2 else ([x]+list(ys)+list(ys)[::-1]+[x]))]) for x in range(1,10) for ys ...
true
96da277ad960cc5dae6b7aab40b2d7bbf6b3be3e
blobsmith/digit-recognizer
/model/abstract.py
UTF-8
2,181
2.828125
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from abc import ABC, abstractmethod class Abstract(ABC): def __init__(self, input_shape, classes): self.input_shape = input_shape self.classes = classes self.build() self.compile() @abstractmethod def build(self): ...
true
dade5119e313965831a1c4ab7b709c5244140bfd
LuiMagno/Aulas-e-Exemplos
/Aulas de Python/Jogo da Velha.py
UTF-8
2,359
4.03125
4
[]
no_license
def main(): while True: print('Bem-vindo ao Jogo da Velha do Lui!!!\n','Jogador 1 joga com X\n', 'Jogador 2 joga com O' ) mostrar_board(board) jogar() print('Fim de Jogo!') if not replay(): print('Até mais!') break def replay(): return input(...
true
3c415ed810d0aebfa22fc9a05663fd4cef508527
LennyBoyatzis/python-patterns
/patterns/patterns/abstract_classes.py
UTF-8
1,009
4.25
4
[]
no_license
from abc import abstractmethod, ABC """ Python doesn't provide abstract classes. It only comes with a module which provides the infrastructure for defining Abstract Base Classes (ABCs) """ class AbstractClassExample(ABC): def __init__(self, value): self.value = value # Invoke the abstract base cl...
true
d5b2c76a508dd6bf34ce179723fbfb3969019d6a
kvafy/python-tools
/iit.py
UTF-8
7,238
2.9375
3
[]
no_license
#!/usr/bin/env python3 import argparse import os import os.path import re # ========================== # = Intelligent ID3 Tagger = # ========================== # Specify a mask of the directory structure and/or of the filename to extract # artist, album, year, song title etc. from. # This script uses the eyeD3 utili...
true