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
ea034edd4a53142c90f1a0e28e93d06743b19a2f
Phibi95/PythonBasics
/13-oop/example-1.py
UTF-8
718
3.546875
4
[]
no_license
class Person: def __init__(self, name, height, weight): self.height = height self.weight = weight self.name = name self.bmi = weight / (height * height) def printBMI(self): print(self.name + '\'s BMI ist: ' + str(self.bmi)) def getHeightIn(self,metric): if ...
true
38c87282e445c4bdb0d543843f6f28db046e3c35
NechaevDA/vehicles_counter
/count_vehicles.py
UTF-8
5,628
2.5625
3
[]
no_license
import cv2 import numpy as np from vehicle_counter.display import draw_information from vehicle_counter.contour_detect import ContourDetect from vehicle_counter.counter import Counter border_line_y = 300 border_line_x = 450 offset_y = 70 great_britain = False # Вечно у британцев все наперекосяк step = 0 # 0 - borders,...
true
27eed0aa80f80b91dc0cea59c146c89fb6589c8d
tsurumeso/chainermin
/chainermin/functions/activation/sigmoid.py
UTF-8
304
2.578125
3
[ "MIT" ]
permissive
import numpy from chainermin import function class Sigmoid(function.Function): def forward(self, x): self.y = numpy.tanh(x[0] * 0.5) * 0.5 + 0.5 return self.y, def backward(self, x, gy): return gy[0] * self.y * (1 - self.y), def sigmoid(x): return Sigmoid()(x)
true
08e40e74784122c3815f36c4f863c8d299099d13
ryancallihan/tensorflow_lstm
/train.py
UTF-8
3,851
2.5625
3
[ "MIT" ]
permissive
import timeit import tensorflow as tf from tensorflow.python.framework import ops from model import Model, Phase def train(config, train_batches, validation_batches, vocab_size, save_path, from_saved=False): print("Beginning training...") train_start_time = timeit.default_timer() train_batches, train_len...
true
ab10d76493ceeb2d11f5e437069a7e60a95cd031
Dikshantdhall/pythonModule
/task3.py
UTF-8
3,026
3.859375
4
[]
no_license
# ////// 1 elementList = [10, "welcome", 30.0, 10 + 20j, 40, 50.0,"to", "Python", 40 -10j, 100] # ////// 2 elements = ["10",40, 30.0, "hello", "world"] print(elements[0]) print(elements[2:4]) print(elements[4:5]) # ////// 3 numberList = [10, 20, 30, 50] sum = 0 mult = 1 for i in numberList: sum = sum + i m...
true
50277b49f64175abe0b4f1710514c32a47f7a5b4
nathantheinventor/solved-problems
/kattis/NAIPC Practice 10/G Ambiguous Result/amb2.py
UTF-8
3,929
3.0625
3
[]
no_license
import re def num(): global pos ans = 0 while pos < len(string) and string[pos] in "1234567890": ans *= 10; ans += int(string[pos]) pos += 1 return ans def exprMin() -> int: global pos tmp = termMin() if pos < len(string): pos += 1 tmp += exprMin() ...
true
88a4430381b93f3c5386a946fa46d907a5f78239
zmnoval/noaasolarweather
/src/DiscreteParticleFlux.py
UTF-8
4,865
2.546875
3
[]
no_license
from MyMplCanvas import MyMplCanvas from numpy import linspace from NoaaApi import storeGOESDiscreteParticleFlux from NoaaApi import getGOESDiscreteParticleFlux import colors_and_globals """ As of MatPlotLib 1.5 qt4_compat will be deprecated for the more general qt_compat. Pulling that in instead. """ from matplotl...
true
0500d3a149ab58e47b4594c29f4a568d4ce86b26
vnscriptkid/Flasky-Yumroad
/tests/test_product.py
UTF-8
6,390
2.53125
3
[]
no_license
import pytest import vcr from flask import url_for from app import db from app.models import Product def create_book(name="Sherlock Homes", description="a house hunting real estate agent"): book = Product(name="Sherlock Homes", description="a house hunting detective", price_cents=500) db.session.add(book) ...
true
08753397cc04e1c6db1e8287d6938e385f02feff
jimmyhmiller/one-hundred-lines-or-less
/libraries/python/flask/__init__.py
UTF-8
1,483
2.609375
3
[ "MIT" ]
permissive
from itertools import imap, ifilter from functools import wraps import json import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from http import create_server from inspect import getargspec not_found = { "status": 404, "headers": {"Content-type": "application/json"}, "body": json...
true
ad514cce5b4340a0c7ab6ed1c72b8a7182069b5b
JerJohn15/pyexcel-io
/tests/test_service.py
UTF-8
1,896
2.59375
3
[ "BSD-3-Clause" ]
permissive
from nose.tools import eq_, raises from pyexcel_io.service import date_value, time_value from pyexcel_io.service import detect_int_value from pyexcel_io.service import detect_float_value def test_date_util_parse(): value = "2015-08-17T19:20:00" d = date_value(value) assert d.strftime("%Y-%m-%dT%H:%M:%S") ...
true
5ebaebcd7ff2082cc9b0c1821f32f0d2c84ac264
LialinMaxim/birthday_calculator
/birthday_calculator.py
UTF-8
930
3.734375
4
[]
no_license
from functools import wraps from math import factorial def convert_to_percent(f): @wraps(f) def decorated(*args, **kwargs): probability = f(*args, **kwargs) return f'{round(probability * 100, 3)}%' return decorated @convert_to_percent def birthday_probability(people: int, days_range=0, ...
true
5336f577ab10bf75fa8205f68aada36f6a319abc
Aidan28/pp2_summer_edition
/tsis4/lec5/4.py
UTF-8
103
2.828125
3
[]
no_license
a_file = open("example.txt", "r") lines = a_file. readlines() last_lines = lines[-5:] print(last_lines)
true
461afe4b08d38b47a09e6f36f9dbcfbb7bc1cf18
StoryMonster/ZhaJinhua
/tools/generateCardsComposes.py
UTF-8
1,499
3.21875
3
[]
no_license
import random class CardCompose(object): def __init__(self, nums): self.cards = nums self.cards.sort() def __hash__(self): strCard0 = str(self.cards[0]) if self.cards[0] >= 10 else "0" + str(self.cards[0]) strCard1 = str(self.cards[1]) if self.cards[1] >= 10 else "0" + str(self...
true
d274e01d738b333f7f88ac420c8681532d26ba9f
KhangxLi/Simple-Calculator-Game
/SimpleCalculatorGame.py
UTF-8
3,516
3.46875
3
[ "MIT" ]
permissive
import sys running = True choosing = True def main_menu(): '''Main menu options.''' while running: print("\nChoose your desired operation:") print("\nEnter '1' = Addition") print("Enter '2' = Substraction") print("Enter '3' = Multiplication") print("Enter '4' = Division"...
true
49569b0ecba0079c88285e8ec27761250ff0780e
llwsykll/leetCode
/longestCommonPrefix/longComPre.py
UTF-8
528
2.78125
3
[]
no_license
class Solution: def longestCommonPrefix(self, strs: 'List[str]') -> 'str': if len(strs): common = strs[0] else: return '' for i in range(len(strs[0])): for str in strs[1:]: if str.find(common)==0: pass el...
true
2674dc057479baae7c79a65a363155096355e4df
bopopescu/mastersproject
/src/mastersproject/GTS/deprecated_files/geological_model_visualization.py
UTF-8
10,999
3
3
[]
no_license
""" This is a replicate of the geological_model_visualization.m file from""" from pathlib import Path import os import numpy as np class GeologicalModel: def __init__(self): """ Define the global constants for the geological dataset. These include: GTS_coordinates (np.array, (3)): ...
true
587b57636c109e71d07512604cfee2bfe3742b5a
JBMatthews/python-for-everybody
/python-data-structures/assignments/10.2_assignment/solution.py
UTF-8
878
3.5625
4
[]
no_license
# 10.2 Data Structures - Tuples # # Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. # # From stephen.marquard@uct...
true
695333fef53f38b5910c5975f3b4381cdcd57a01
Thinguyen23/group3_project
/apps/myapp.py
UTF-8
2,432
2.515625
3
[]
no_license
# Run ml.py to get machine learning model first # !/usr/bin/env python # coding: utf-8 from flask import Flask, render_template, redirect, request from flask_sqlalchemy import SQLAlchemy import pandas as pd from ie import forecast # Add SQLAlchemy dependencies import sqlalchemy from sqlalchemy.ext.automap import auto...
true
744de12991fda57a3dc5a8d9895d34369d847412
Alsock/ghMaxi.github.io
/muiv/2/hlp/Seminar03/Source01/test.py
UTF-8
466
2.890625
3
[]
no_license
import pprint from main import start_new_game, bomb_matrix def test_start_new_game(): """Тест начала новой игры""" test_cases = ( (1, 1, 1, None), (6, 8, 9, None), (6, 8, 49, None)) for w, h, b, _ in test_cases: try: start_new_game(w, h, b) except Value...
true
8ab392e013ec8b21394edf7e2e4d1d02f06d8a4a
nasirsotudeh/Python_Spark_classification
/tests/test_etl_job.py
UTF-8
1,517
2.671875
3
[]
no_license
""" test_etl_job.py ~~~~~~~~~~~~~~~ This module contains unit tests for the transformation steps of the ETL job defined in etl_job.py. It makes use of a local version of PySpark that is bundled with the PySpark package. """ import unittest import json from pyspark.sql.functions import mean, col from Kmeans.K_means ...
true
0403e6a0f63c2c39a0e29cb0c506016d58bc50b8
amit-kr-debug/GIC_calculator
/app.py
UTF-8
869
2.734375
3
[]
no_license
from flask import Flask, request from twilio.twiml.messaging_response import MessagingResponse import calculator app = Flask(__name__) @app.route("/") def hello(): return "Webserver" @app.route("/calculator", methods=['POST']) def user_sms_reply(): msg = request.form.get('Body') reply = MessagingRespon...
true
378124f24592ffa8483db7d2d9fd26a1d5300341
MounikaYellu/Python_Programs
/reg_ex02.py
UTF-8
112
2.921875
3
[]
no_license
import re string = " A fat cat doesn't eat oat but a rat eats bats" mo=re.findall("[force]at",string) print mo
true
536b26de04baa8ed5b5e5ae2478806f660c58b5b
jerevon/Simple-Hourglass
/lib/model/UNet.py
UTF-8
2,778
2.53125
3
[]
no_license
import tensorflow as tf import layers class UNet(object): def __init__(self, img_ph, ann_ph): # Form the network self.network = {} self.prediction, logits = self.formNet(img_ph, ann_ph) self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.squeeze(ann_p...
true
4879375006287869a0917e8cf8271875bc470c98
sparrowljq/numpy
/matrix.py
UTF-8
1,581
4.03125
4
[]
no_license
# 矩阵运算 import numpy as np # 点积运算 a = np.array([[1, 2], [3, 4]]) b = np.array([[11, 12], [13, 14]]) # 输出结果为 # [[37 40] # [85 92]] # 计算公式为[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]] # print(np.dot(a, b)) # 向量乘积 # 输出结果为130 # 计算公式为1*11 + 2*12 + 3*13 + 4*14 = 130 print(np.vdot(a, b)) # 向量内积 numpy.inner() 函数返回一维数组的向量内积...
true
fc6d95bb109d7d9cd9fdaeed54511f6e07a0a239
FredOleary/python-finance-1
/playground2.py
UTF-8
3,532
2.5625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 11 10:26:16 2017 @author: fredoleary """ import urllib.request import json import sys import feedparser import requests from html.parser import HTMLParser import re import demjson from datetime import datetime from WebFinance import FinanceWeb from ...
true
a0c47aa21e00fa2bc67b01433fa2a4ca6cf997d1
rafaelhbz/Written_RPG
/ep1.py
UTF-8
16,027
3.078125
3
[]
no_license
# Alunos: # - aluno A: Rafael Henrique Belini Zanfolin, rafaelhbz@insper.edu.br # - aluno B: João Pedro Farias Araujo, joaopfa2@al.insper.edu.br import json import random hp_character = 30 atk_character = 2 def_character = 0 if hp_character <= 0: game_over = True # o dicionário inventário está sendo modificad...
true
9f3b4947637d0520951f9ed7afea41344f3e14d9
pasaunier/car_b_finder
/car_finder_app/app.py
UTF-8
4,465
3.046875
3
[]
no_license
#stl import os import sys import inspect #image browsing from PIL import Image, ImageTk import tkinter.filedialog as tkFileDialog from tkinter import Tk, RIGHT, BOTH, RAISED from tkinter.ttk import Frame, Button, Label, Style from classes.mediator import Mediator # Set current path to project root # currentdir = o...
true
528226409a16fc7b3bb2353610d2ad253cfc1cd8
kovaley/HAMR-Simulation
/Code/older methods/ADI.py
UTF-8
7,688
3.0625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 29 18:50:49 2020 @author: josephbattesti """ from scipy.sparse import linalg as lina import utility as ut from scipy.sparse import csr_matrix as csr, lil_matrix as lil """ Ici se trouvent les fonction en lien avec le schéma numerique La méthode a...
true
5b603e60a25e0b7bbc42bfee12d7baa4c5110cf5
ixime/antares3
/madmex/lcc/transform/kapur.py
UTF-8
8,987
2.96875
3
[]
no_license
''' 2018 07 10 @author: jequihua ''' import logging from scipy import stats from madmex.lcc.transform import TransformBase import numpy as np def optimal_bins(data_vector, method="shimazaki-shinomoto", bins=1000): '''Computes optimal number of bins to produce a histogram Args: data_vector (np.ndar...
true
ec80aa5297c9e258abea4715698b7b058cd4be71
sunyihuan326/kx_detection
/data_script/print_all_labels.py
UTF-8
1,186
2.796875
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2021/3/2 # @Author : sunyihuan # @File : print_all_labels.py ''' 输出标注文件夹下,所有xml文件的标签 ''' import os import xml.etree.ElementTree as ET from tqdm import tqdm def label_name(file): ''' 检查标签是否有更改完成,标签名不正确的输出 :param inputpath: xml文件路径 :param label_name: 标签名 :r...
true
94e6a143744f6d60b6ea1195d61dbf4955e5416c
MarigoldJ/DaconTFT
/config/folder.py
UTF-8
287
2.53125
3
[]
no_license
import os base = os.path.dirname(__file__).replace("\\config", "") dataset = os.path.join(base, 'dataset') def get_dataset_path(file_name: str): """ /dataset 폴더 내의 파일의 경로 반환 """ file_path = os.path.join(dataset, file_name) return file_path
true
8e29c9378bbdfaa7c1c48856917220400621b19a
hiter-joe/dl-surrogates
/shape-opt/airfoil_optimizer/Helper.py
UTF-8
4,354
2.859375
3
[ "Apache-2.0" ]
permissive
import math import numpy as np import torch import logging import matplotlib.pyplot as pyplt class Mode: ShapeGen = 1 AsymmetricShapeGen = 2 RotatingShapeGen = 3 BezierShapeGen = 4 DebugShapeGen = 5 class Solver: DummySolver = 1 OpenFoamSolver = 2 DeepFl...
true
f62c9f2f9533687987e5efd4b3b29a194142c16b
AlessandroLovo/Physics_Laboratory-g19
/Timing/data/Day1/Analysis_LEMO.py
UTF-8
1,175
3.140625
3
[]
no_license
# Analysis of LEMOs done measuring the delay of each LEMO plus 13ns (-> Base channel 13ns = (2230 +- 20) ch) # Calibration of TAC: # channel = a * t + b # ('[a,b] = ', array([ 677.2140816 , -6576.89957312])) # ('cov: ', array([[ 18.21537828, -340.21625909], # [ -340.21625909, 6920.47269011]])) # LEMO_4 # ...
true
5beb75656aa846921efcf1074701508d9242dd65
Areso/gb-p2
/lesson2-ex3.py
UTF-8
552
3.078125
3
[]
no_license
import yaml def write_savegame_to_yaml(mychar): with open('data.yaml', 'w') as f_n: yaml.dump(mychar, f_n, default_flow_style=True, allow_unicode=True) return 0 def load_savegame_from_yaml(): with open("data.yaml", 'r') as stream: print(yaml.safe_load(stream)) return 0 mycharname = {...
true
dc0ab771548e5b63a4c274d0b88b4e9fa7e459c1
dmerkus/Aether
/aether/ontology/gender/__init__.py
UTF-8
112
2.5625
3
[ "MIT" ]
permissive
from enum import Enum, auto class Gender(Enum): Male = auto() Female = auto() NonBinary = auto()
true
e53255b5d485f6ba91819e21af12a58bd202d1e3
arangoml/arangopipe
/arangopipe/tests/pytorch/ch_data_loader.py
UTF-8
2,073
2.9375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 13 08:59:42 2019 @author: Rajiv Sambasivan """ from math import ceil import numpy as np import pandas as pd import torch from sklearn.preprocessing import StandardScaler from torch.utils import data class CH_Dataset(data.Dataset): "Characteri...
true
933d971c45828ecfab5699413fdb7fc07f6246e0
uu-isrc-robotics/uu-isrc-robotics-pr2-pkgs
/pr2_trajectory_markers/src/trajectory_markers.py
UTF-8
15,625
2.5625
3
[]
no_license
#!/usr/bin/env python """ Copyright (c) 2012, Lorenzo Riano. All rights reserved. """ import roslib; roslib.load_manifest("pr2_trajectory_markers") import rospy import pr2_control_utilities from pr2_control_utilities.utils import (create_tuples_from_pose, normalize_trajectory) from interactive_markers.intera...
true
761d1f33eef8c1edd1edbd9ca7af872e17e00466
sen99/Cifar10-pytorch
/Models/dencenet.py
UTF-8
5,154
2.671875
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np class Bottleneck(nn.Module): def __init__(self, in_ch, growth_rate): super().__init__() inter_ch = 4 * growth_rate self.bn1 = nn.BatchNorm2d(in_ch) self.conv1 = nn.Conv2d(in_ch, inter_c...
true
a97d117e46aa5b185383b6bebe680a83fbf525a8
antonshcherba/my-edx
/ProbabilityAndHashing/Histograms.py
UTF-8
1,581
3.25
3
[ "Giftware" ]
permissive
__author__ = 'aDmin' import random import pylab def stdDev(data): mean = sum(data)/float(len(data)) tot = 0.0 for val in data: tot += (val - mean)**2 return (tot / len(data))**0.5 def flip(numFlips): heads = 0.0 for i in range(numFlips): if random.random() < 0.5: ...
true
50bb7b6b0b5b7ab512279e3b02de8a2aeb857223
SkipperJK/netease-sentiment-analyze
/sentiment.py
UTF-8
2,058
2.515625
3
[]
no_license
#coding=utf-8 import os import sys import myclassifier as mclf import train_doc_vector as dv from snownlp import SnowNLP if sys.getdefaultencoding() != 'utf-8': reload(sys) sys.setdefaultencoding('utf-8') cwd = os.getcwd() file_path = os.path.join(cwd, "text/cmt_stit.txt") def get_stit_label(sentences, file_path,...
true
59cddec51ee2ab81b9cfe27f301d5ca323062a09
SorinGumeni/SmartHome
/SmartHome/SerialCom/SerialSub.py
UTF-8
834
2.703125
3
[]
no_license
import sys sys.path.insert(0, '/home/pi/Desktop/SmartHome/AppMngr') sys.path.insert(0, '/home/pi/Desktop/SmartHome/Common') import serial import SerialSettings import SerialHandler class SerialSub: def __init__(self, a_sSerialPortAdress, a_oAppMngr): self.m_oReceiver = serial.Serial(a_sSerialPortAdres...
true
657444adbb663819ea7817c908160d7fcaf77a49
greenfox-zerda-lasers/h-attila
/week-03/day-3/10.py
UTF-8
369
4.5625
5
[]
no_license
# Create a function that prints a triangle like this: # * # *** # ***** # ******* # ********* # *********** # # It should take a number as parameter that describes how many lines the triangle has def mistery_triangle(lines): i = 1 while i <= lines: print(" " * (lines - i), "*" * (...
true
adea315dd69519075302fe77009755001473f09e
Osc4ar/ScraperCreditos
/extractor/db_manager.py
UTF-8
969
2.625
3
[]
no_license
import sqlite3 class DBManager: def __init__(self): self.create_connection_cursor() def close_connection(self): self.conn.commit() self.conn.close() def create_connection_cursor(self): try: self.conn = sqlite3.connect('./db/Credito.db') self.c = sel...
true
3dd295e04d29108eca90db2968508c144aa31bda
tsushiy/competitive-programming-submissions
/AtCoder/ABC/ABC051-100/abc099/abc099c_1.py
UTF-8
291
2.859375
3
[]
no_license
n = int(input()) dp = [1e9 for i in range(100001)] dp[0] = 0 ans = n yen = set() for i in range(7): yen.add(6**i) dp[6**i] = 1 for i in range(6): yen.add(9**i) dp[9**i] = 1 for i in range(1, n+1): for e in yen: if i+e<=100000: dp[i+e] = min(dp[i+e], dp[i]+1) print(dp[n])
true
2b6328ac3ce52da4655b13e8cafe4e4af6b1e07b
oumarPoulo/flask-tutorial
/tasks_app/blueprints.py
UTF-8
825
2.8125
3
[]
no_license
"""All Flask blueprints for the entire application They shall be imported by application.py. Blueprint URL paths are defined here as well """ from flask import Blueprint def _factory(partial_module_string, url_prefix): """Generates blueprint objects for view modules. Positional arguments: partial_module_...
true
cc19809da398ea006720ea026f9ca3ea7005a195
jaymindesai/software-analytics
/w5/src/unsuper.py
UTF-8
2,368
2.59375
3
[]
no_license
from math import pow from w3.src.num import Num from w4.src.data import Data UNSUP_ENOUGH = 0.5 UNSUP_MARGIN = 1.05 def unsuper(data: Data): """Discretizing independent continuous numeric columns""" rows = data.rows most = 0 enough = pow(len(rows), UNSUP_ENOUGH) margin = UNSUP_MARGIN def ba...
true
fb6d78019534289b9c56c58329d1d4464e086c54
SeanMFranklin/ProjectEuler
/Euler58.py
UTF-8
393
3.375
3
[]
no_license
import Euler start = 9 diff = 2 numerator = 3 denominator = 5 while numerator/denominator > .1: diff += 2 for p in (start + diff, start + 2*diff, start + 3*diff, start + 4*diff): if Euler.is_prime(p): numerator += 1 denominator += 4 start += diff * 4 if denominator % 101 == 0: ...
true
e5a7a3347d4c3c4dd4cd0d2c040f8756db2086a9
adafruit/circuitpython
/tests/cpydiff/modules_random_getrandbits.py
UTF-8
404
3.015625
3
[ "MIT", "GPL-1.0-or-later" ]
permissive
""" categories: Modules,random description: ``getrandbits`` method can only return a maximum of 32 bits at a time. cause: PRNG's internal state is only 32bits so it can only return a maximum of 32 bits of data at a time. workaround: If you need a number that has more than 32 bits then utilize the random module from mic...
true
b7c8fe1a8afc64e71ae75b22d156b6328645ae8a
Dor-Sloim/usefull-python-scripts
/csgo_discord_bot.py
UTF-8
3,916
3.046875
3
[]
no_license
""" Discord Bot for creating csgo teams from people inside voice channel. Setup: - pip install -U discord.py - pip install python-dotenv """ # bot.py import os import random import discord from discord.ext import commands from discord.ext.commands import CommandNotFound, CommandInvok...
true
c2248f3e738cffc011fa991cc94774b46a213f41
KamilyaBikmaeva/Python_Course
/Task4_1/pack/prog.py
UTF-8
1,171
3.484375
3
[]
no_license
import pickle def create_file(): file_name = input('Enter filename: ') open(file_name, 'w').close() modify_file(file_name) def modify_file(file_name=None): if file_name: with open(file_name, 'w') as file: lines_count = 0 while True: inp = input(f'Enter...
true
fdbbb2b682abf47cc1b18c97a94bbd55b9514511
daniel-reich/ubiquitous-fiesta
/WyttgdGuQGaRBqhhP_7.py
UTF-8
177
3.28125
3
[]
no_license
def min_palindrome_steps(txt): if isPalindrome(txt): return 0 txt = txt[1:] return 1 + min_palindrome_steps(txt) def isPalindrome(x): return x == x[::-1]
true
419f44bc716c3c05b5ef1ea223bb6a2cb09dd78b
NIEKnox/RepulsionBot
/repulsionbot_public.py
UTF-8
12,126
2.671875
3
[]
no_license
import sqlite3 import uuid import discord from discord.ext import commands TOKEN = "INSERT TOKEN HERE" GUILD = "INSERT DISCORD SERVER ID HERE" bot = commands.Bot(command_prefix=';') encryption_log = "INSERT CHANNELID TO PRINT ENCRYPTED MESSAGES TO HERE" bot_actions = "INSERT CHANNELID TO PRINT ALL BOT ACT...
true
ed961646ba9f5c06e45882cfc336efd8835667c2
b1ueskydragon/PythonGround
/leetcode/p1024/video_stitching.py
UTF-8
716
2.84375
3
[]
no_license
class Solution: def videoStitching(self, clips: [[int]], T: int) -> int: end_points = [0] * 101 # can have extra video after the event ends. constraint T<=100 for start, end in clips: end_points[start] = max(end, end_points[start]) end_before = reachable = count = 0 for ...
true
c7945efcb31baa9131f7482deacf786e48525e0a
Mahendran-Nadesan/PyTetClone
/OldBoard.py
UTF-8
4,954
3.015625
3
[]
no_license
# OldBoard.py # This is the old Board.py (Board class). # Decided to redo classes after Commit 5 # Main issue is the collision() and draw() methods from Tetras import tetras import pygame class board: def __init__(self, surf, num_rows, num_columns, inner_colour, outer_colour): self.surf = surf self.num_rows = nu...
true
52644074443aad1cb14d4ed805fa1bd53bf7ca73
Waihlan103/Open-CV
/Week 2/Mouse _click_event.py
UTF-8
445
2.59375
3
[]
no_license
import cv2 as cv import numpy as np def click(event, x, y, flags, param): if event == cv.EVENT_LBUTTONDOWN: print(x, ',', y) font = cv.FONT_HERSHEY_SIMPLEX pt = str(x)+','+str(y) cv.putText(img, pt, (x, y), font, .5, (0, 0, 255), 2) cv.imshow('image', img) img = ...
true
9167dd5be9aa8458166eacd2560a1c7dac2ca6ab
BenWng/Networking-Fundamentals-s2015
/project4/ip/IPPacket.py
UTF-8
6,256
3.03125
3
[]
no_license
import logging import socket import struct __author__ = 'njhazelh' log = logging.getLogger("IP Packet") def packet_id_gen(): """ :return: A generator that returns a infinite, cyclic sequence of 16-bit numbers. """ current = 0 while True: yield current current += 1 current...
true
0e58207f96faa49fb0f84073bd2f12c46b1d5d65
Takkakynttila/historicalStockPricePlotter
/main.py
UTF-8
387
2.828125
3
[]
no_license
import fetcher_plotter as fp def main(): stock_name = input('Give LSE: ') stock_period = input('Give optional period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max) - max by default: ') if stock_period == None: stock = fp.plotter(stock_name) else: stock = fp.plotter(stock_name, stock...
true
b7639a0a5eda2266d9829c9644b277ce4b03a62d
IAmAnalyst/Level_0_Coding_Challenges
/Task0_7.py
UTF-8
249
3.921875
4
[]
no_license
def Celsius_to_Fahrenheit(c): F=((c/5)*9)+32 return f'This temperature is {F} degrees fahrenheit' def Fahrenheit_to_Celcius(f): C=((f-32)*5)/9 return f'This temperature is {C} degrees celsius' print(Fahrenheit_to_Celcius(98.6))
true
78a5f2a3a741d70dc359340d4736a53ac12df145
mihirk/reporting
/models/Patient.py
UTF-8
1,032
2.515625
3
[]
no_license
import json from models.serialization_helper.serialization_helper import to_json, instance_json from models.validation.CleanInputs import CleanInputs class Patient: def __init__(self, name=None, identifier=None, address=None, relatives=None, age=None, gender=None, encounters=None, adherences=None...
true
0abbf1d138806f71c1a812c3baa30a1bd00724cf
dashuncel/gb_python
/byankina_dz9_4.py
UTF-8
2,648
4.21875
4
[]
no_license
''' 4. Реализуйте базовый класс Car. у класса должны быть следующие атрибуты: speed, color, name, is_police(булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда); опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar; добавьте...
true
4a7721c721adac4bc91893b1f61dfb971ee5a3b7
Perilynn/HackerRank-Coding-Challenges
/Code Golf/The Trigonometric Ratios/ryan.py
UTF-8
168
2.84375
3
[ "NCSA" ]
permissive
input() def z(x,n):return 1 if n==0 else x/n*z(x,n-1) while 1: a=[0,0];q=input() for i in range(10):a[i%2]+=(-1)**(i/2)*z(q,i) print a[1],a[0] #Score: 12.30
true
a7f28227799f0a35ce12e10cbdc7c59c7e20e429
SardulDhyani/MCA3_lab_practicals
/MCA3A/Dixit_Gusain_MCA_20711051/q12_standarddeviation.py
UTF-8
183
3.1875
3
[]
no_license
import numpy as np # creating a simple data - set sample = np.array([1,3,5,7,9]) # Prints standard deviation print("Standard Deviation of sample is % s "% (np.std(sample)))
true
d8c48fd8784ec5dd6ef521b341092ff2e3b25040
ggv8/TareaProgramada1
/libreriaExtra.py
UTF-8
1,277
3.234375
3
[]
no_license
# Elaborador por: Ignacio García Galagarza, Gabriel Gomez Vega # Fecha de creación: 21/09/2021, 12:14 AM # Última edición: 08/10/2021, 06:00 AM # Versión: 3.9.6 ############################################################## ##### Importación de Librerías ##### ################################...
true
bc1523bdbe0a13c9f3cfe477c45ef4000fe3fe07
Rahul-J94/Machine_Learning
/Mathplotlib.py
UTF-8
107
2.53125
3
[]
no_license
import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.xlabel("some data") plt.ylabel("ylabel") plt.show()
true
f39ec6c4271cc74cd21431d7c702621f74eb5e8a
prasanna-ranganathan/mypython
/Mdchecksum.py
UTF-8
384
3.265625
3
[]
no_license
#!/usr/bin/env python import hashlib import sys def Create_checksum(path): """ reads in file.creates checksum of files line by line. """ fp = open(path) checksum = hashlib.md5() while True: buffer = fp.read(8192) if not buffer: break checksum.update(buffer) fp.close() checksum = checksum....
true
cc57cc2b66cbe6dc4d5124574148fb12284c3893
maxoxo/2016-NFL-Prediction-Model
/nfl_model_functions.py
UTF-8
4,506
3.09375
3
[]
no_license
# functions.py # load libraries import pandas as pd import numpy as np import math ### Necessary functions & values # - prob_win # - simulate_game # - k value # - Expectation function (E) # - mov_multiplier # - update_ratings # - divisions and conferences ### prob_win function -------------------------------------...
true
43410b84bc5c5f37833362b9e67e5792aa1244e4
akhileshjain/CS50
/pset6/cash/cash.py
UTF-8
783
3.96875
4
[]
no_license
from cs50 import get_float # Prompt for input while input is not valid while True: cash = get_float("Change owed:") if cash > 0: break # Convert dollars to cents change = round(cash * 100) # Initialize count count = 0 # If change is more than 25 cents if change > 25: count += int(change / 25) ...
true
20244d19a1400d2593e8f0d776029ed5b7d17c49
softmatterlab/DeepTrack-app
/deeptrack/math.py
UTF-8
43,178
3.03125
3
[]
no_license
''' Mathematical oprations and structures Classses -------- Clip Clip the input within a minimum and a maximum value. NormalizeMinMax Min-max image normalization. ''' from deeptrack.features import Feature from deeptrack.image import Image import numpy as np class Average(Feature): ''' Average of input i...
true
7cc2b0bcf5174e516ce2226a7d1bf57f4c7a9cb4
letsjdosth/fluentPython
/chap2/deque99.py
UTF-8
628
4.1875
4
[]
no_license
from collections import deque dq=deque(range(10),maxlen=10) #최대길이 10 (선택 요소임) print(dq) dq.rotate(3) #3번 오른쪽으로 민다 print(dq) dq.rotate(-4) #4번 왼쪽으로 민다 print(dq) dq.appendleft(-1) #왼쪽에 -1 추가 (maxlen을 맞추기 위해 밀리며 맨 오른쪽 하나가 삭제된다) print(dq) dq.extend([11,12,13]) #오른쪽에 [11,12,13] 추가 (밀리며 왼쪽 3개가 삭제된다) print(dq) dq.extend...
true
97aee2c29bc22baa0c36e449a7e195be2fd0bf8e
CharisseU/CodingDojo_Assignments
/Python_Stack/flask/flask_foundations/playground/server.py
UTF-8
497
2.6875
3
[]
no_license
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/play') def play(): return render_template('index.html', times=3) @app.route('/play/<x>') def level2(x): return render_template('index.html', times = int(x)) ...
true
5ab072ccf409133987442d85ff66ce175650f2ab
YevgenyY/Python_Course1
/week3/human_planet.py
UTF-8
452
3.984375
4
[]
no_license
class Human: def __init__(self, name, age=0): self.name = name self.age = age class Planet: def __init__(self, name, population=None): self.name = name self.population = population or [] def add_human(self, human): print('Welcome to {}, {}'.format(self.name, human...
true
fae9e40804e8e8486e11a564fa38e7fa1670b6d4
albertkklam/hackerrank
/python/mathematics/number theory/smithNumbers.py
UTF-8
563
3.640625
4
[]
no_license
# Identify Smith Numbers ## https://www.hackerrank.com/challenges/identify-smith-numbers/problem import math def primeFactors(n): primes = [] while n % 2 == 0: primes.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: primes.appen...
true
0ac4b3c9e44dda69324228ba7927a032e7adf016
135790zs/rsnn
/wip/Code/scheduler.py
UTF-8
2,739
2.5625
3
[]
no_license
from subprocess import PIPE, Popen from time import sleep from threading import Thread, BoundedSemaphore import json import signal sem = BoundedSemaphore() nq = [] processes = {} total_mem = 15000000000 def load_config(id): with open('configs/'+id+'.json') as file: config = json.load(file) return ...
true
4f98b7687a0b0f0bea82065b0e32d50600a32481
swk072798/Beat_monster_game
/Window.py
UTF-8
1,220
2.796875
3
[]
no_license
import pygame from pygame.locals import * from monster_small import monster_small_jin from Monster_Boss import Monster_Boss import time import random class Window(): def __init__(self): #窗口的初始化 self.screen = pygame.display.set_mode((1280,720)) self.title = pygame.display.set_caption("打怪兽游戏") ...
true
3a9b5f2f0842abe1599913d44680041372cf9d3d
stevembc/Undercover
/code/data.py
UTF-8
149
2.796875
3
[]
no_license
#Taille de l'écran import pygame WIDTH = 1280 HEIGHT = 720 #Taille du personnage SIZE = 190 LENGTH = 325 #Couleur WHITE = (255, 255, 255) #FONT
true
37d4be7334d034cd30635c7a00c0511c2bc0d263
ParkYoungUn/Python_Study
/5.4_set.py
UTF-8
688
4.09375
4
[]
no_license
# 집합 (set) # 중복 안됨, 순서 없음 my_set = {1, 2, 3, 3, 3, 2} print(my_set) java = {"박영운", "김보성", "한윤정"} python = set(["박영운", "정도원"]) # 교집합 (java와 python을 모두 할 수있는 사람) print(java & python) print(java.intersection(python)) # 합집합 (java도 할 수 있거나 python 할 수 있는 개발자) print(java | python) print(java.union(python)) # 차집합(java 할 수 ...
true
8bc6e65f83a43c65483806c025dc0f4ec85b5262
ncullen93/pyBN
/pyBN/learning/structure/score/info_scores.py
UTF-8
4,250
3.609375
4
[ "MIT" ]
permissive
""" Various metrics for evaluating score-based search for Bayesian Networks structure learning. Generally, score-based structure learning involves finding the structure which maximizes some function of the likelihood of the data, given the structure and parameters of the learned BN. It is important to take advantage ...
true
cf3ac9ae6357c75057991c83db89cc2b3a5f9120
xiangjie818/dockerfile
/xtreemfs/osd/snmp_proxy/utils/cli.py
UTF-8
1,782
2.546875
3
[]
no_license
# encoding: utf-8 import subprocess from threading import Timer class CLI: """ Just a wrapper around the openssl command """ def __init__(self): pass @staticmethod def call_wait_rtn(command, timeout_sec=0): print('Running command: %s' % command) p = ...
true
a6457c7a7761de07f9a750244449876c25c158b5
robbisg/pyitab
/pyitab/analysis/decoding/roi_decoding.py
UTF-8
5,525
2.546875
3
[]
no_license
import numpy as np from sklearn.metrics._scorer import _check_multimetric_scoring from sklearn.svm import SVC from sklearn.preprocessing import LabelEncoder from sklearn.pipeline import Pipeline from sklearn.model_selection._split import LeaveOneGroupOut from pyitab.utils.dataset import get_ds_data from pyitab.analys...
true
5630281742425b2fd2df1aa1b4d8ebd8d0d1f37e
davidgutierrez611/formy-project-python
/02_04/Scroll.py
UTF-8
589
3.046875
3
[]
no_license
from selenium import webdriver; import time # import Action chains from selenium.webdriver.common.action_chains import ActionChains #Launches the webdriver in this case chrome. Then goes to website driver = webdriver.Chrome(); # Navigates to web address driver.get("https://formy-project.herokuapp.com/scroll") ti...
true
8a456256cbdc551a89243395a966335fe2c42e57
SousaPedro11/genomics
/app/app.py
UTF-8
8,649
2.84375
3
[ "MIT" ]
permissive
import re import pandas as pd RE_GENE_NAME = re.compile(r'Name=(?P<gene_name>.+?);') def extract_gene_name(attributes_str): res = RE_GENE_NAME.search(attributes_str) return res.group('gene_name') RE_GENE_ID = re.compile(r'gene_id=(?P<gene_id>ENSG.+?);') def extract_gene_id(attributes_str): res = RE_...
true
05e9b5d8e118c10f3dde5820f9d019bfa5f58beb
sarahcp5/SGBD_Materia
/Practica 1 - Preprocesamiento de Datos/Ejercicio1_1.py
UTF-8
230
3.71875
4
[]
no_license
#!/usr/bin/python3 import re S = input("Ingrese texto: ") match = re.search(r'[^IVXLCDM]', S) #Matchea los valores que no se encuentran entre corchetes. El ^ indica todos if match: print('FALSE') else: print('TRUE')
true
2428d40bc7be6454f0d224ba365e86b2d25e6bf9
nsshayan/DataStructuresAndAlgorithms
/HackerEarth/Arrays-multiD/transposeMatrix.py
UTF-8
298
3
3
[]
no_license
N,M = map(int,raw_input().split()) mat = [] for i in range(N): mat.append(map(int,raw_input().split())) mat = zip(*mat) for i in range(len(mat)): matElements = '' for j in range(len(mat[i])): matElements += str(mat[i][j]) matElements += ' ' print matElements
true
8eb33612eceb578ac1d41550bba53bb3b9118ce6
MstrZhang/project_euler
/euler5.py
UTF-8
598
4.0625
4
[]
no_license
# no programming required for this one # the naive approach is to take this number big_num = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 # prime factorization (this is equal to big_num) prime_factor = 1 * 2 * 3 * (2 * 2) * 5 * (3 * 2) * 7 * (2 * 2 * 2) * (3 * 3) * (5 * 2) *...
true
dd088f4cc3982e92f192cfdbce5bbfa6e92f0194
qtbgo/Strategy-Bet-Sizing
/feature_modeling/create_feature_objects.py
UTF-8
3,419
2.765625
3
[]
no_license
import attr from feature_modeling import feature_heuristics as fh import pandas as pd START_TIME, END_TIME = '9:15:00', '16:00:00' @attr.s(auto_attribs=True, frozen=True) class InputParameters: table_name: str ticker: str bench_table_name: str bench_ticker: str @attr.s(auto_attribs=True, frozen=True...
true
8b17c8297d0076c57eb22f6ea5be5f4b00db405f
502463708/Microcalcification_Detection
/loss/t_test_loss_v2.py
UTF-8
3,820
2.890625
3
[]
no_license
""" This file implements another version of t-test loss which is derived from the original version of t-test loss implemented in t_test_loss.py This version implements what the authors actually did """ import numpy as np import torch import torch.nn as nn class TTestLossV2(nn.Module): def __init__(self, beta=0.8,...
true
4c8987584e9269892bc407c8318288685c78eb16
shunsunsun/data-store
/dss/operations/secrets.py
UTF-8
19,263
2.5625
3
[ "MIT" ]
permissive
""" Get/set secret variable values from the AWS Secrets Manager """ import os import sys import select import typing import argparse import json import logging import copy import subprocess from botocore.exceptions import ClientError from dss.operations import dispatch from dss.operations.util import polite_print fro...
true
00e44abf8f9e659162503f07f9fdc34ab0f75c31
dan8919/python
/coding_test/DSF_BSF/DFS1test.py
UTF-8
269
3.375
3
[]
no_license
graph =[[],[2,3,8],[1,7],[1,4,5,],[3,5],[3,4],[7],[2,6,8],[1,7]] visited =[False]*9 def dfs(graph,v,visited): visited[v] = True print(v, end=" ") for i in graph[v]: if not visited[i]: dfs(graph,i,visited) print(dfs(graph,1,visited))
true
cc888f4eb31d02e4ff2be85321788b3bd85902e6
robinentjes/fourinarow
/model.py
UTF-8
3,540
3.8125
4
[]
no_license
import copy class Board: # this file contains all the information, in regards to the game board # the status of the game board is stored as a 2d array, where 0 means that there is no coin, # 1 if there is a coin from player 1 and -1 if there is a coin for player 2 def __init__(self): self.__...
true
aeca9a74c7b9b26f18331d88c7a058fe13ef868f
AstroStucky/magicai
/python/mai/prep.py
UTF-8
2,967
2.75
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Jun 10 12:24:22 2017 @author: Fomalhaut """ import ibmseti import matplotlib.pyplot as plt import numpy as np import zipfile baseDir = '/Users/jimh/SETI/basic/' index = open(baseDir + 'public_list_basic_v2_26may_2017.csv','r') # globals zz_file = '' def read_zip( zip_name...
true
4e72e27c00a16c5e61dce34ce23f8a72303c331b
daphnevandijk/masterthesis
/models/LR occupation (subset data).py
UTF-8
3,228
3
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: # Import the required libraries import pandas as pd import numpy as np from scipy import stats from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, roc_auc_score from sklearn.model_selection import KFold, GridSearchCV, train_te...
true
d0120b80347de60c496111f2c15146138e122b35
ZacharyAnstey/beginner-Python-projects-
/dice.py
UTF-8
188
3.359375
3
[]
no_license
""" The folowing program simulate rolling a pair of dice 10 times """ from random import randint for i in range(10): d1 = randint(1,6) d2 = randint(1,6) print(d1,d2)
true
626c9ed7d8d79944fb6c032bd2bd89d3984f9874
derSoerrn95/plugin.video.nowtv
/resources/lib/view.py
UTF-8
3,341
2.84375
3
[]
no_license
''' Provides functions for formatting data ready for rendering. ''' def guidedata(schedule, plugin_uri='', aspect='16-9', image_size='400'): ''' Attempts to transform the input schedule data from the Sky EPG into a format compatible with uEPG guidedata elements. Args: schedule (dict): A dicti...
true
adb01ee5e9f7161d9234e15c026421c0b93a1333
Aasthaengg/IBMdataset
/Python_codes/p02712/s768163602.py
UTF-8
100
3.375
3
[]
no_license
a = int(input()) b = 0 for i in range(1, a+1): if (i%3!=0) and (i%5!=0): b += i print(b)
true
e87126e24f30e62c05baef850217761453816fa8
FrankLu007/2020-AI-Cup-Mango
/grade/train3.py
UTF-8
5,885
2.59375
3
[]
no_license
import os import torch import torchvision.transforms import torchvision.datasets from model import EfficientNetWithFC, FixResNet from argparser import get_args def forward(DataLoader, model, LossFunction, optimizer = None, scaler = None) : correct = [0.0] * 3 cases = [0.0] * 3 TotalLoss = 0.0 for _, (inputs, lab...
true
23442d070084297b764cb6e90cef00201a09feec
dragonfir2016/Twitter_lab
/Task_2_twitter_navigation.py
UTF-8
954
3.078125
3
[]
no_license
import urllib.request import urllib.parse import urllib.error import twurl import json import ssl def get_account_api(): TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json' ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE print('') acct =...
true
378d403fa5dbefb6a395deea17ef4cf9ced641e9
JonFillip/web_API
/python_repo_visual.py
UTF-8
2,690
3.5
4
[]
no_license
import requests from plotly import offline # Call the git API and store the response def get_response(): """Make an API call and return the response""" url = 'https://api.github.com/search/repositories?q=language:python&sort' \ '=stars' header = {'Accept': 'application/vnd.github.v3+json'} #...
true
b685b03662a748c64a9289b3aba8c087fbacfa9b
marcus-aurelianus/Lintcode-with-Python
/30. Insert Interval/sol30.py
UTF-8
1,149
3.921875
4
[]
no_license
class Interval: def __init__(self,start,end): self.start=start self.end=end class Solution: """ Insert a new interval into a sorted non-overlapping interval list. @param intevals: Sorted non-overlapping interval list @param newInterval: The new interval. @return: A new sorted non...
true
8b77707a4e4e22bc728cd8197e5e730675d3127b
lijielife/stock_chart
/daily_price_v3.py
UTF-8
3,531
3.21875
3
[]
no_license
import pandas as pd item_name = "KODEX 200" url = "http://finance.naver.com/item/sise_day.nhn?code=069500" # 일자 데이터를 담을 df라는 DataFrame 정의 df = pd.DataFrame() # 1페이지에서 91페이지의 데이터만 가져오기 for page in range(1, 91): pg_url = '{url}&page={page}'.format(url=url, page=page) df = df.append(pd.read_html(pg_url, header...
true
96f24a7513c2aa8f3940d5622695c791b9c61b7b
sfallou/mes-programmes-python
/dimensionnement/flask/app.py.wo
UTF-8
2,051
2.578125
3
[]
no_license
#!/usr/bin/python2.7 # -*-coding:Utf-8 -* from flask import * from werkzeug import secure_filename import os import pickle import time import copy ####### Les Fonctions ################### #=============================les differentes fonction necessaires=========================== def factoriel(n): res=1 n=n+1 ...
true