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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
98e0ad4b2689f09c35d283536cf3c2c08e95e4ae | Python | 9vinny/cw_api | /utils/donation.py | UTF-8 | 1,758 | 2.609375 | 3 | [] | no_license | from classes.sql_conn import SqlConn
import logging
def calculate_donor_month_total():
"""calculate and save donor's accumulated change amount"""
pass
def make_donations():
"""make donations for users who have selected drives"""
#get user_id and amts for active donors
#make donation entry
#re... | true |
4596f01883cc85093f11ce30f373423da6cf3b41 | Python | terrenceliu01/python1 | /src/languageBasics/operator/comparison.py | UTF-8 | 384 | 4.0625 | 4 | [] | no_license | """
Comparison Operators
== Equal
!= NotEqual
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
"""
a, b = 10, 20
f = a==b
# comparison operator always return True or False bool type.
print(type(f))
print(f)
print(a == b)
print(a != b)
print(a <= b)
print(a >= b)
print(a > b)
print(a < ... | true |
18546f4f5d60c372a459ac8bb997e304717c2fb4 | Python | helcerion/T1000 | /src/t1000/infrastructure/persistence/events_in_memory_repo.py | UTF-8 | 3,466 | 3.15625 | 3 | [
"MIT"
] | permissive | from datetime import datetime
from ...domain.entity import Event, Events
class EventsInMemoryRepo():
DATE_FORMAT = '%Y-%m-%d'
def __init__(self):
self._events = [
{'uuid': 'asdf', 'date': '2019-10-01', 'time': '07:20:00'},
{'uuid': 'qwer', 'date': '2019-10-01', 'time': '14:35... | true |
cf605449ce61daf7a1553117138e91b2e70cd37f | Python | juanmatg/practica | /6-kyu/denumerate string.py | UTF-8 | 439 | 3.34375 | 3 | [] | no_license | def denumerate(enum_list):
#rebuild the string
res = ''
try:
enum_list = sorted(enum_list, key = lambda x: x[0])
for i in xrange(len(enum_list)):
if enum_list[i][0] != i or len(enum_list[i]) != 2 or not enum_list[i][1].isalnum() or len(enum_list[i][1]) != 1:
retur... | true |
141df951d7139f7ed6f25a38d6301ff578329aa1 | Python | josephramsay/anzlic-validator | /setup.py | UTF-8 | 3,153 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
anzlic-validator setup.py run by
'sudo python setup.py'
Will Check the current system has the correct versions:
- QGIS v2.18
- PyQT v4
- Koordinates python module is installed, if not will install.
- Python v2.7
- An Api file exists, .apikey
Then move the anzlic-validator directory to the ... | true |
d6332035dd99f8beca6ca7ffb5472a45150ffb05 | Python | alex-i-git/LearnPython | /bot.py | UTF-8 | 4,800 | 2.921875 | 3 | [] | no_license | #!/usr/bin/python3
# version 0.1
# Добавляем функцию подсчета слов
# Usage: /wcount word1 word2 ...
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import date, datetime
import ephem
import csv
#Updater - связь с telegram
#CommandHandler - обработчик команд
#MessageHandler - о... | true |
d822042380f54ef9f0d596163048b5cac479cc4c | Python | ashleymcnamara/LearnPythonTheHardWay | /ex36.py | UTF-8 | 3,819 | 3.65625 | 4 | [] | no_license | from sys import exit
def joe():
print "Joe has a beautiful woman in his sights, but she is diseased!"
print "which disease does she have? herpes, aids, or the clap?"
next = raw_input()
if next == "herpes":
std_treatment()
elif next == "aids":
dead("Joe is DEAD!")
if next == "clap":
std_treatment()
el... | true |
dd18762ec144c39d18ea7b5eb4d74f7a07fb2ae3 | Python | Quynhbh122/BuiHuongQuynh-Fundermantals-C4E32 | /L1/Homework/area.py | UTF-8 | 55 | 3.296875 | 3 | [] | no_license | r = int(input('radius?'))
a = r*r*3.14
print('area=',a) | true |
eb5923f1aad3c6d502880415f1c5a6b8c3d90cc4 | Python | ngodoy/asoc_members | /website/members/management/commands/import_members.py | UTF-8 | 2,430 | 2.75 | 3 | [
"MIT"
] | permissive | import csv
import os
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from members.models import Person, Member, Category
class Command(BaseCommand):
help = "Import members from csv generated with data from Google Spreadsheet"
def add_arguments(self, parser):
... | true |
449b16c129c391575332415d49df7f0c80e46423 | Python | BilalQadar/Data_visualization | /main.py | UTF-8 | 3,507 | 3.234375 | 3 | [] | no_license | from framework import *
import numpy as np
if __name__ == "__main__":
parameters = ("#763dff",'-',"#000000",'--', 3)
destination_folder = "/Users/bilalqadar/Documents/GitHub/Data_visualization/saved_figures/"
# x_bully = [2007,2009,2010,2011,2013,2014,2015,2016,2019]
# y_bully = [18.8,21.5,20.8,29.2,2... | true |
534b82ac77f309ae4ee9060a9305aa3725639cd2 | Python | Erniejie/PYTHON---multiply-two-matrices-using-nested-loops | /2021-08-20_Python_Program to Multiply two Matrices using Nested Loops.py | UTF-8 | 619 | 4.0625 | 4 | [] | no_license | #Program to multiply two matrices using nested loops
"Computer Programmming Tutor, 17th August 2021"
#3x3 Matrix
A = [[5,3,2],
[2,3,4],
[3,4,3]
]
#3x4 Matrix
B = [[2,4,1,2],
[3,2,3,0],
[3,2,5,1]
]
# Result is a 3x4 Matrix
result = [[0,0,0,0],
[0,0,0,0],
... | true |
86fbeadb29247b0b99e509ae8701937379c52b0b | Python | VenishaDias/Leaf-Classification | /hog.py | UTF-8 | 1,353 | 2.828125 | 3 | [] | no_license | import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import imutils
import math
from scipy import ndimage
def foreground(image):
boundaries = [([0,0,0],[100,255,100])]
# loop over the boundaries
for (lower, upper) in boundaries:
# create NumPy arrays from the boundaries
... | true |
e3c8278858c088dc20afb97d74f3dd5df253c62c | Python | Zahidsqldba07/codefights-2 | /intro/throughTheFog/stringsRearrangement.py | UTF-8 | 877 | 4.21875 | 4 | [] | no_license | """
Given an array of equal-length strings, check if it is possible to rearrange the strings in such a way that after the rearrangement the
strings at consecutive positions would differ by exactly one character.
Example
For inputArray = ["aba", "bbb", "bab"], the output should be
stringsRearrangement(inputArray... | true |
fa052383097c3b66bd82a24959675196fb7636a0 | Python | nadjacarolyneckert/basictrack_2021 | /Week 4/Homework Part 1/4.9.4.py | UTF-8 | 380 | 3.75 | 4 | [] | no_license | import turtle
paper = turtle.Screen()
leonardo = turtle.Turtle()
leonardo.color("pink")
def draw_poly(draw_turtle, number_of_sides, size):
angle = 360 / number_of_sides
for _ in range(number_of_sides):
draw_turtle.forward(size)
draw_turtle.left(angle)
for _ in range(20):
draw_poly(leonard... | true |
e50475089e1c42e98c41aac74792adc85fe71f7d | Python | linlin547/UI_25_11 | /Base/data.py | UTF-8 | 478 | 2.75 | 3 | [] | no_license | import os, json
class Data:
"""解析测试数据"""
@classmethod
def get_json_data(cls, file):
"""
解析json文件
:param file: 项目Data目录下文件名字
:return: json文件数据
"""
# 打开json文件
with open("./Data" + os.sep + file, "r", encoding="utf-8") as f:
# 使用json库解析数据
... | true |
a8602b820d3ec6b200fbc0fb1d8a793e743ce7cb | Python | tikhomirovd/2sem_Python3 | /rk/rk_python.py | UTF-8 | 2,038 | 2.765625 | 3 | [] | no_license | import sys, pygame
import time
pygame.init()
def smoke():
i = 0
x = 170
y = 380
while i < 10:
pygame.draw.ellipse(screen, grey, [x-i, y-3*i, 15, 20])
pygame.draw.ellipse(screen, grey, [x+i, y-3*i, 15, 20])
x, y = x-i, y-3*i
time.sleep(0.25)
pygame.dr... | true |
6b892aa8254b7301d5aa53f01589e0cde60f572e | Python | binbinErices/python_crawler | /maoyan_top100/code/test.py | UTF-8 | 916 | 2.734375 | 3 | [
"MIT"
] | permissive | #!usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author:binbinzhang
@file: test.py
@time: 2018/04/27
@email:binbin_Erices@163.com
@function:测试使用webdriver拿网页数据
"""
import datetime
from selenium import webdriver
from openpyxl import load_workbook
service_args = [].append('--load-images=false') ##关闭图片加载
driver =... | true |
ec24623d44580908bb849e0c562c67df204c60df | Python | XuLongjia/PyTorchLearning | /start4.py | UTF-8 | 2,511 | 3.578125 | 4 | [] | no_license | #1、学习如何用PyTorch做个回归:regression
#2、学习两种保存模型的方法
#3、学习DataLoader
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
x = torch.linspace(-1,1,100)
#torch.squeeze()是用来对数据的维度进行压缩,去掉维数为1的维度
#squeeze(a)就是将a中所有为1的维度删掉,不为1的没有影响
#a.squeeze(N) 就是去... | true |
dc70a866afc0e6d3cdc8701b1b68e13a65cea99e | Python | TeBeau/AlgorithmsExamples | /longest_palindromic_sequene.py | UTF-8 | 812 | 3.796875 | 4 | [] | no_license | import random
def palindrome(s):
n= len(s)
#create table
A= [[0 for x in range(n)]for x in range(n)]
#strings of len 1 are palindromes of len 1
for i in range(n):
A[i][i]=1
#Fill table
for l in range(2,n+1):
for i in range(n-l+1):
j=i+l-1
i... | true |
10ca0d73627b8b9ff0780ac49e49bd86646aa381 | Python | slavkoBV/solved-tasks-SoftGroup-course | /rock_scissors_paper.py | UTF-8 | 709 | 4.03125 | 4 | [] | no_license | import random
items = {1: 'rock', 2: 'paper', 3: 'scissors'}
def select_winner(user_choice):
if user_choice not in ('1', '2', '3'):
return print('Make correct choice!')
computer_choice = random.randrange(1, 3, 1)
print('Computer choice: ', items[computer_choice])
who_win = (int(user... | true |
8d40b566d0dc612995ed67873ac10b196a1df2be | Python | wbl1996/python | /spiders/beautifulsoup_urlretrive_spider.py | UTF-8 | 758 | 2.734375 | 3 | [] | no_license | from bs4 import BeautifulSoup
import urllib.request
url = "https://tieba.baidu.com/p/5639915974"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
def get_html(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'})
res = urllib.request.urlo... | true |
0b58000dd482b8cec8d7372c65a661ab665fb359 | Python | bmuller/readembedability | /readembedability/parsers/oembed.py | UTF-8 | 2,906 | 2.609375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | import json
from bs4 import BeautifulSoup
from robostrippy.utils import absolute_url
from readembedability.parsers.base import BaseParser
from readembedability.io import get_page
class OEmbedParser(BaseParser):
async def enrich(self, result):
if self.soup is None:
return result
oembe... | true |
dc006bf341e02e633ae01dec54de94eff555dbc3 | Python | SebastianRatanczuk/Uczelnia | /main.py | UTF-8 | 1,808 | 2.859375 | 3 | [] | no_license | # Sebastian Ratańczuk 44476
import numpy as np, math, random
from sklearn import datasets
from sklearn.model_selection import train_test_split
class MLP:
def __init__(self, hidden=100, epochs=100, eta=0.1, shuffle=True):
self.hidden = hidden
self.epochs = epochs
self.eta = eta
self... | true |
ce7d33321d5f78514e2c3edc4d9e026cc7e0b6fa | Python | ksdivesh/python-test-project | /console-app/main.py | UTF-8 | 786 | 3.390625 | 3 | [] | no_license | from models.Item import Item
from models.ItemCategory import ItemCategory
# category = ItemCategory(category_id=1)
# result = category.get()
# print(result)
# category_name = input("Enter category name")
#
# itemCategory = ItemCategory(category_name = category_name)
# itemCategory.insert()
#
# print("Category insert... | true |
949f0cf006561d56751e95d73cc2cfbe5d8986ce | Python | DanielDworakowski/flot | /rasp/blimp_ws/src/blimp_control/src/PID.py | UTF-8 | 2,161 | 3.046875 | 3 | [] | no_license | import time
class PID:
"""PID Controller"""
def __init__(self, P = 0.0, I = 0.0, D = 0.0, min_ = 0.0, max_ = 0.0):
self.k_p = P
self.k_i = I
self.k_d = D
self.min_ = min_
self.max_ = max_
self.current_time = time.time()
self.last_time = self.current_t... | true |
ab902b0602b621f20153bb94ffbe4e6db5f965eb | Python | michaelkerr/influence_api | /tests/api_test_system.py | UTF-8 | 16,898 | 2.75 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# api_test_system.py
""" System functional testing """
#from itertools import combinations
import json
from types import *
import unittest
from urllib2 import Request, urlopen
server_ip = '127.0.0.1'
server_port = '5000'
base_url = 'http://' + server_ip + ':' + server_port + '/metrics/centralit... | true |
cfe6258989b562229da14ff5454d043bcefb5908 | Python | emilmanolov/holidayextras | /models/user.py | UTF-8 | 2,462 | 3.234375 | 3 | [] | no_license | import re
class User(object):
def __init__(self, email='', forename='', surname=''):
self.id = None
self.email = email
self.forename = forename
self.surname = surname
self.created = None
def __str__(self):
return '<User {0}>'.format(self.id)
__repr__ = __s... | true |
8981340c78e4635a3950c3aac54511d9f9697062 | Python | bioCKO/lpp_Script | /HTseq_Count.py | UTF-8 | 1,240 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/python
#coding:utf-8
"""
Author: --<>
Purpose:
Created: 2014/11/1
"""
import collections,sys,HTSeq
from optparse import OptionParser
usage = '''usage: python2.7 %prog [options] Kmer
Kmer is a list of K value you want,e.g [ 1, 2, 3, 4 ]'''
parser = OptionParser(usage =usage )
parser.add... | true |
b96cc8b400309f0f5a8411c5df8f800dba885b9d | Python | jamiejamiebobamie/pythonPlayground | /tictactoe2.py | UTF-8 | 18,573 | 3.78125 | 4 | [] | no_license | # Design a Tic-tac-toe game that is played between two players on a n x n grid.
#
# You may assume the following rules:
#
# A move is guaranteed to be valid and is placed on an empty block.
# Once a winning condition is reached, no more moves is allowed.
# A player who succeeds in placing n of their marks in a horizont... | true |
c4082c30e187ba2de5ef99bfc4931da860e46071 | Python | iam-vignesh/network-monitoring-scripts | /ping.py | UTF-8 | 856 | 3.09375 | 3 | [] | no_license | import os
import csv
print("+------------------------------------------------------------------+")
with open('PATH TO FILE\\filename.csv', newline='') as csvfile:
filereader = csv.reader(csvfile)
next(filereader)
for row in filereader:
ips = (row[0])
print(f"Pinging....{ips}")
... | true |
2e16588e115c8bca74bdc14aaf66f92b21bd826f | Python | herolibra/PyCodeComplete | /Others/Modules/kafka/access_kafka.py | UTF-8 | 884 | 2.5625 | 3 | [] | no_license | # coding=utf-8
from pykafka import KafkaClient
import codecs
import logging
logging.basicConfig(level=logging.INFO)
# create kafka data, string format
def produce_kafka_data(kafka_topic):
with kafka_topic.get_sync_producer() as producer:
for i in range(4):
producer.produce('test message ' + ... | true |
70075756a020a68f98df3f7f28ca59a01ceb8f48 | Python | shivduttbharadwaj/data_structures_algorithms | /guess_find_binary_search.py | UTF-8 | 621 | 4.65625 | 5 | [] | no_license | def binary_search(sorted_list, item):
"""
This binary_search function takes a sorted array and an item.
If the item is in the array, the function returns its position.
"""
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = int((low + high) / 2)
print("mid is, ", m... | true |
b3d36a94ef39addfe5c7abd613a5b3159d272ece | Python | nekromant8/Jet_projects | /Banking/banking.py | UTF-8 | 5,928 | 3.125 | 3 | [] | no_license | import random
import string
import sqlite3
conn = sqlite3.connect('card.s3db')
cur = conn.cursor()
first_6 = 400000
count = 0
card = 0
pin = 0
card_number = None
pin_code = None
n = None
user_card = None
cur.execute('CREATE TABLE IF NOT EXISTS card(id INTEGER PRIMARY KEY, number TEXT, pin TEXT,balance INTEGER DEFAULT ... | true |
568e372a82c35dcbf7b5247df871ff7ab4335400 | Python | Vincannes/TradeFinance | /app/libs/widgets/combobox.py | UTF-8 | 1,637 | 2.859375 | 3 | [
"MIT"
] | permissive | from PySide2 import QtGui, QtCore, QtWidgets
class ComboBox(QtWidgets.QComboBox):
def __init__(self, parent=None, *args, **kwargs):
super(ComboBox, self).__init__(parent)
class StyleComboBox(ComboBox):
"""Combobox used to define line style in the setting indicator dialog"""
def __init__(self, p... | true |
3238e76cf0fb368b4bed5a7dcf4a8813ba0227c4 | Python | soh516/cmcdata | /plotspeed | UTF-8 | 1,717 | 2.65625 | 3 | [] | no_license | #! /usr/bin/python
import datetime
from time import sleep
import os
import re
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as md
pauseDur = 10.0 #pasue in min
index = 0
with open('/home/tst023/physics/cmc-home-migration/datamigrationspeed_2017_11_07_10_39_17') as file:
for line in ... | true |
ee9d15b07dc4ad0d00dd7e5a664a8425b6c13356 | Python | dineshram/PythonModule1 | /Day9/Classwork/ReadFromDatabase.py | UTF-8 | 291 | 2.75 | 3 | [] | no_license | import sqlite3
def readTableItems(dbName):
with sqlite3.connect(dbName) as db:
cursor = db.cursor()
sql = 'SELECT * FROM Customer'
cursor.execute(sql)
items = cursor.fetchall()
print(items)
db.commit()
readTableItems("EspressoHouse.db")
| true |
99bbf6781c28bcc59c79890939c5d7638c5b5e58 | Python | Taiji-pipeline/Taiji-utils | /python/taiji-utils/taiji_utils/Knee.py | UTF-8 | 836 | 2.59375 | 3 | [] | no_license | import numpy as np
import math
from csaps import csaps
def fitSpline(X, Y):
def getW(xs):
ds = []
for i in range(len(xs)):
if i == 0:
d = (Y[0] - xs[0]) + (xs[0] - xs[1])
elif i == len(xs)-1:
d = (xs[-2] - xs[-1]) + (xs[-1] - Y[-1])
... | true |
22476310666034c5047909479bf75168425bb949 | Python | dolejska-daniel/fit_vutbr-dp2020 | /python/other/point_cluster.py | UTF-8 | 2,184 | 3.359375 | 3 | [] | no_license | import itertools
import functools
import math
import operator
class Cluster:
def __init__(self):
self.points = set()
def __hash__(self) -> int:
return functools.reduce(operator.xor, map(hash, self.points))
def __len__(self) -> int:
return len(self.points)
def __repr__(self)... | true |
1d757cdb3140326bc143dd70876d9c14b52c0c70 | Python | dmitrikuksik/GermanCredit | /random_forest.py | UTF-8 | 6,957 | 2.953125 | 3 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import sys
from Node import Node
def numeric2categoric(df,attr,q): #konwertacja ciaglych danych na kategorii
df[attr] = pd.qcut(df[attr], q=q, labels=False)
def split_dataframe(df,split_at): # podzial danych na zbior trenujacy i te... | true |
0fffc05dacf2646bb493626eb4359404be5c53eb | Python | kren1504/Training_codewars_hackerrank | /sumaDigitosRecursiva.py | UTF-8 | 609 | 3.609375 | 4 | [] | no_license | def sumOfDigits(num):
if num == 0:
return num
else:
return (( num % 10) + sumOfDigits( (num//10)))
def sumarDigitosDeNumero(num):
suma = 0
tam = len(str(num))
for i in range(tam):
suma += num % 10
num = num //10
return suma
def back(num,tamNum):
if tam... | true |
f6237d1167464c1c3a3ebb9bcd540771d220a0fe | Python | Al153/Programming | /Python/Cryptography/Julian's Code/Key Generator 1.0.py | UTF-8 | 418 | 2.8125 | 3 | [] | no_license | import time
while True:
try:
keylen = int(raw_input("Enter the keylength: "))
break
except ValueError:
pass
start = time.time()
cddkey = (keylen + 1)*[0]
while cddkey[keylen] != 1:
print cddkey
cddkey[0] += 1
for n in range(keylen):
if cddkey[n] == 26:
cdd... | true |
2131f5597d72898eacd65bf22e88bb6790b4f710 | Python | alexelt/linkedin | /linkedin_scraper.py | UTF-8 | 10,480 | 2.5625 | 3 | [] | no_license | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException as Nosuch
from bs4 import BeautifulSoup
from random import randint
import time
import csv
import ast
def login():
opts = Options()
opts.add_argument(
"user-age... | true |
71532dba09e974748d322ee91ac1187f7ef9bd77 | Python | MrNewaz/Learning-Dgango | /Done/lesson 2/integers.py | UTF-8 | 57 | 2.890625 | 3 | [] | no_license | items = 4
price = 5.12
print('Na' * 10)
print('Batman')
| true |
af055cbd2759be60833605b54bc459637d15fb2a | Python | nikolkam/Automated-Plant-Watering-System | /water.py | UTF-8 | 2,197 | 3.328125 | 3 | [] | no_license | #initialization
import RPi.GPIO as GPIO
import time
import schedule
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
soil_in = 21 #PIN for reading soil moisture
soil_out = 18 #PIN for turning on/off soil moisture sensor
motor = 20 #PIN for water pump
#setting up PINS
GPIO.setup(soil_out,GPIO.OUT)
G... | true |
9db388d616413c6f04cd29d85f0b2790dfba873f | Python | ns-m/netology_ad_py_Tests | /API_yandex/main.py | UTF-8 | 569 | 2.546875 | 3 | [] | no_license | import requests
URL = "https://translate.yandex.net/api/v1.5/tr.json/translate"
def translate_to_file(text, lang):
resp_translate = requests.post(URL, params={
"key": "trnsl.1.1.20191128T170444Z.c56d359e1889b3b7.8fccca1aa4fe51ff1bb52de2213efc89f26608ff",
"text": text,
"lang": lang})
... | true |
6fb82edd6333569362acbdf0df8f890fdcac5986 | Python | ChrisEngelhardt/flambda-sentim | /lambdas/sentim-batch/sentim-batch.py | UTF-8 | 785 | 2.765625 | 3 | [] | no_license | import json
import math
def batch(arr, n):
n = max(1, n)
return list((arr[i:i+n] for i in range(0, len(arr), n)))
def main(j):
all_tweets = j['arrayToSplit']
desired_num_batches = j['splitNumber']
# do the calculation
batch_size = math.ceil(len(all_tweets) / desired_num_batches)
batched_all_twee... | true |
584cad7a09a5637e1451d0fbfd2fb3d88a7a1ffc | Python | Tayuba/Data-MInning-From-Webscrapping | /exams.py | UTF-8 | 612 | 3.03125 | 3 | [] | no_license | import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
num = [0,1,2,3,4,5,6,7,8]
dict = {
"name": num
}
let = [ "a", "b", "c", "d", "e", "f"]
array_num = np.array(num)
df = pd.DataFrame(num, columns=["list"])
print(df)
half = []
for i in range(len(num)//2):
print(num[i])
mat =... | true |
fea58c2ea0adca5242f7b77fe4edd0d239b1656f | Python | quekdylan/Assignment1 | /RatVenture/RatVenture.py | UTF-8 | 8,724 | 3.265625 | 3 | [] | no_license | from RatVenture_functions import *
from RatVenture_classes import *
import sys
#Default values
v_filename = "save.txt"
v_location="0,0"
v_day = 1
v_rat_encounter = False
v_town_locations = ["0,0", "3,1", "5,2", "1,3", "4,6"]
v_orb_location = setOrbLocation(v_town_locations)
v_rat_king_alive = True
#Display Main Menu ... | true |
89d0fb0b31a8b320e1392551ed74bff4b3f28fbd | Python | s70c3/searchmachine | /service/models/nomeclature_recognition/utils.py | UTF-8 | 2,100 | 3.125 | 3 | [] | no_license | import pdf2image
import cv2
import numpy as np
from PIL import Image
def pil2cv(pil_img):
return cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2GRAY)
def cv2pil(cv_img):
return Image.fromarray(cv_img)
def stats(arr, unique=False):
print(f'shape={arr.shape}, type={arr.dtype}, min={arr.min()}, max={arr.m... | true |
3d9ce669d1007b93732b21c4a3ee1a666b955662 | Python | ebebbington/denv-creator | /denv-creator/test.py | UTF-8 | 1,990 | 3.046875 | 3 | [
"MIT"
] | permissive | import os
def get_current_directory():
current_dir = os.path.dirname(os.path.realpath(__file__))
print(current_dir)
def add_white_spaces_at_start_of_string(text, numberOfSpaces) -> str:
spacey_string = text.rjust(len(text)+numberOfSpaces)
return spacey_string
spaces = add_white_spaces_at_start_of_stri... | true |
ead39756db3a23879feb6c9d6cd9bb83b79faef4 | Python | TaylorBoyd/Pente | /PenteMainCode.py | UTF-8 | 8,219 | 3.546875 | 4 | [
"MIT"
] | permissive | class Board(object):
def __init__(self, height, width):
self.width = width
self.height = height
self.winner = False
self.spaces = {}
for x in range(self.width):
for y in range(self.height):
self.spaces[(x, y)] = "+"
def is_ston... | true |
d04e1b55cf756e5a542139098e28d21059387bcd | Python | MiKoronjoo/Finglish2Farsi-telegram-bot | /finglish2farsi.py | UTF-8 | 1,792 | 2.828125 | 3 | [] | no_license | import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent
from config import TOKEN
from time import sleep
from finglish import f2p
def f2f(text):
std_text = ''
for char in text:
if(not char.isalpha()):
std_text += ' ... | true |
07ecadc07c1410b8a3091ebb3e52a3ab1c87ef79 | Python | rlecaro2/uni-operating-systems-and-networks-homeworks | /verPosicion.py | UTF-8 | 481 | 2.703125 | 3 | [] | no_license | from proceso import Proceso
from fileManager import fileManager
from time import localtime, strftime
class verPosicion(Proceso):
def __init__(self, args):
Proceso.__init__(self,args)
self.duracion = int(args[4])
def imprimir(self):
return strftime("%Y-%m-%d %H:%M:%S", local... | true |
b19edcee688801cd11b85ac499851ab22411bf3a | Python | Sebastian-Torres-Matrix/mysql-project | /mysql-from-python.py | UTF-8 | 805 | 2.859375 | 3 | [] | no_license | import os
import datetime
import pymysql
# Get username from workspace
# modify this variable if runnin on another environment
username = os.getenv('C9_USER')
# Connect to database
connection = pymysql.connect(host='localhost', user = username, password = '', db = 'Chinook')
try:
# Run a query
with connectio... | true |
6115ff39e9a25d7df13f1432813edde4ff522d06 | Python | ppuetsch/tankstellen_crawler | /tankstellen_crawler.py | UTF-8 | 1,196 | 3.078125 | 3 | [] | no_license | """
Ermittelt links zu individuellen Tankstellen von mehr-tanken.de
"""
import requests_html
import re
from multiprocessing.pool import ThreadPool
def get_links_for_plz(plz):
"Gibt alle Tankstellen, die im Umkreis um eine bestimmte PLZ sind, als Links (URLs) zu den Detailseiten zurück"
with requests_html.HTML... | true |
a9f7c958fd140736520b299d4c028a093f992c00 | Python | uzin1021/pyworks | /ch01/indent.py | UTF-8 | 491 | 4.21875 | 4 | [] | no_license | #indent(들여쓰기) - 4칸 들여쓰기 : {}을 대체
n = 10 #자료형 int 생략, 세미콜론을 찍지 않음
if n % 2 == 0: #if문(명령문)에서 콜론(:)을 사용 - 자동 들여쓰기
print("짝수입니다")
else:
print("홀수입니다")
"""
# 예시
print('a')
print('b')
print('c') #붙여서 쓰기 들여쓰기 주의!
"""
#주석 달기
"""주석 달기 """ #따옴표 위치 조심
msg = '''
사과
귤
감
''' #여러줄로 문자열 출력
print(msg)
| true |
ee3e56c9dbbb6bd1d0083c69cf30bcf8438c9f00 | Python | half-potato/loopclosure | /models/finetune_contrast.py | UTF-8 | 1,698 | 2.546875 | 3 | [] | no_license | import tensorflow as tf
import model_util
slim = tf.contrib.slim
# Top half of the network that computes the features of each image
# layer_cutoff: The layer at which to cutoff the frozen mobilenet
# graph_path: The filepath to the frozen mobilenet
# is_training: Whether or not the network is training
# Returns:
# l_... | true |
d139fa492feb37d83bc8309ab3186d26a589131e | Python | tommymcglynn/samsa | /samsa/topics.py | UTF-8 | 3,785 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | __license__ = """
Copyright 2012 DISQUS
Copyright 2013 Parse.ly, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable l... | true |
f3446133e004cc3d7c7ffdededed5eef1fb92355 | Python | Esantomi/ygl | /hg-python/format01.py | UTF-8 | 355 | 4.3125 | 4 | [] | no_license | # format() 함수로 숫자를 문자열로 변환하기
format_a="{}만 원".format(5000)
format_b="파이썬 열공하여 첫 연봉 {}만 원 만들기 ".format(5000)
format_c="{} {} {}".format(3000, 4000, 5000)
format_d="{} {} {}".format(1, "문자열", True)
# 출력하기
print(format_a)
print(format_b)
print(format_c)
print(format_d)
| true |
4d13996d26a3061d87231b2eaea467d4e264ec4c | Python | Simplon-IA-Bdx-1/the-movie-predictor-nicoOkie | /utils.py | UTF-8 | 250 | 3.5625 | 4 | [] | no_license | def split_name(name):
name_list = name.split(" ")
for name in name_list:
firstnames = (len(name_list) - 1)
firstname = " ".join(name_list[:firstnames])
lastname = name_list[firstnames]
return (firstname, lastname)
| true |
f75542e2c3a39f7b4bac1bafca5070c025578d84 | Python | cyy0523xc/pytorch_yolov1 | /util/loss.py | UTF-8 | 3,387 | 2.59375 | 3 | [] | no_license | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn import *
from shapely.geometry import Polygon
import numpy as np
class YoloLoss(Module):
def __init__(self, num_class=20):
super(YoloLoss, self).__init__()
self.lambda_coord = 5
self.lambda_noobj... | true |
07b36690c90020eca963ff0d589799accecb5797 | Python | recuraki/PythonJunkTest | /atcoder/_codeforces/1658_b.py | UTF-8 | 1,690 | 2.65625 | 3 | [] | no_license |
import sys
from io import StringIO
import unittest
import logging
logging.basicConfig(level=logging.DEBUG)
"""
TLEのポイント:
- 入力高速化(*dat)
- グラフをsetでたどろうとしていませんか?
REの時のポイント
- inputしきっていますか?
"""
def resolve():
#import pypyjit
#pypyjit.set_param('max_unroll_recursion=-1')
import m... | true |
086237b63f7f05b35b5a46acbe807c677b601aaf | Python | naisargidave/PageRank | /PageRank.py | UTF-8 | 6,662 | 3.046875 | 3 | [] | no_license | # homework 3
# goal: ranked retrieval, PageRank, crawling
# exports:
# student - a populated and instantiated cs525.Student object
# PageRankIndex - a class which encapsulates the necessary logic for
# indexing and searching a corpus of text documents and providing a
# ranked result set
# #################... | true |
13edb85fecc36fd76fec818051231480de1e3292 | Python | SwagLyrics/SwSpotify | /SwSpotify/__main__.py | UTF-8 | 253 | 2.71875 | 3 | [
"MIT"
] | permissive | from SwSpotify import spotify, SpotifyNotRunning
def main():
try:
title, artist = spotify.current()
except SpotifyNotRunning as e:
print(e)
else:
print(f"{title} - {artist}")
if __name__ == "__main__":
main()
| true |
b28fc6c37f98f92333bcc9abd1d9fbc6f5319a65 | Python | Julymycin/codes | /traditional_features/rootsift_test.py | UTF-8 | 827 | 2.78125 | 3 | [] | no_license | # import the necessary packages
from traditional_features.rootsift import RootSIFT
import cv2
# load the image we are going to extract descriptors from and convert
# it to grayscale
# image = cv2.imread("example.png")
image = cv2.imread("example1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatur... | true |
d4c283f71492760a37534ea34325520a28474e0d | Python | Yin-dihe/Python | /07-格式化字符串.py | UTF-8 | 181 | 4.09375 | 4 | [] | no_license | name = 'TOM'
age = 18
# 我的名字是x 今年x岁了
print('我的名字是%s, 今年%s岁' % (name, age))
# 语法f'{表达式}'
print(f'我的名字是{name}, 今年{age}岁')
| true |
9914538eca0bb029b011f6fe8b98ba6f4e891924 | Python | SurenderHarsha/CogModSudkou | /Brain_class.py | UTF-8 | 14,451 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 17:41:03 2020
@author: battu
"""
import threading
import time
import numpy as np
from Strategy_selection import *
## A function to get all data in the focus
def get_focus_data(matrix,focus):
data = []
data.append(focus)
square = (int(foc... | true |
55500cf02422e6ae50bd3506e8188c83824476e0 | Python | Akimyou/onigiri_jp_dict | /tmp.py | UTF-8 | 787 | 2.59375 | 3 | [
"BSD-3-Clause",
"MIT",
"CC-BY-3.0"
] | permissive | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import json
import codecs
tmp_path = './_tmp'
tmp_file_path = tmp_path + '/.tmp'
if not os.path.exists(tmp_path):
os.mkdir(tmp_path)
def set (tmp):
tmp_file = codecs.open(tmp_file_path, 'w+', 'utf-8')
try:
tmp_file_w_con = json.dumps(tmp).decod... | true |
d098793fa090609d27661f1feb64d228b35ccaa6 | Python | PouringRain/Algorithmn | /39.py | UTF-8 | 435 | 3.1875 | 3 | [] | no_license | # -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
d = {}
for num in numbers:
if not d.has_key(num):
d[num] = 0
else:
dupli... | true |
bf92398599a96da99884ee898271fe04e193c5ea | Python | Patrick-Ali/PythonLearning | /Writing_To_Pickling.py | UTF-8 | 466 | 2.921875 | 3 | [] | no_license | import pickle
f = open("DataStore.txt", "wb")
eng2sp = { "one": "uno", "four": "cuatro", "three": "tres", "two": "dos"}
sp2eng = { "cinco": "five", "seis": "six", "siete": "seven", "ocho": "eight"}
DiceCombos = { "12": "6+6", "11": "6+5", "10": "5+5", "9": "5+4",
"7": "4+3", "6": "3+3", "5":... | true |
141e23c912f0c8ca03873b4784485294f9b0a32c | Python | 20Mhz/copperv | /scripts/namespace.py | UTF-8 | 5,579 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | from typing import List
import dataclasses
import string
from collections.abc import Iterable
import logging
class Template(string.Template):
def __init__(self,template,*args, **kwargs):
super().__init__(str(template),*args, **kwargs)
self.names = self.get_var_names()
def get_var_names(self):
... | true |
949b73aaa56ea106fe0519b45e7540b42d74797b | Python | dujiacheng1994/python | /NLP/Tfidf_test_3.py | UTF-8 | 672 | 3.171875 | 3 | [] | no_license | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
document = ["I have a pen.", "I have an apple."] # 字符串list,每个元素为1个document
tfidf_model = TfidfVectorizer().fit(document) # 建立tfidf模型,... | true |
607bc1b571de3b2ea30b061d87657fb14f240ca5 | Python | tanlei0/land_use_modified_FLUS | /simulation_ca.py | UTF-8 | 14,549 | 2.640625 | 3 | [] | no_license | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020/10/28 9:19
# @Author : cmk
# @Email : litaoyo@163.com
# @File : simulation_ca.py
# @Software: PyCharm
import multiprocessing
import time
import numpy as np
from numpy.ma import MaskedArray
from typing import List
import random
from tqdm import tqdm
... | true |
370a80ec0f8931cb827f92fa64ef73ca4c9a48d4 | Python | Ilovelibrary/Leetcode-Problems | /682-Baseball-Game.py | UTF-8 | 656 | 2.9375 | 3 | [] | no_license | class Solution(object):
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
def func(x):
try:
x=int(x)
return isinstance(x,int)
except ValueError:
return False
stack = []
fo... | true |
5a98ddb1def614a4d4e3989b0b3e9134c38f1fe3 | Python | Hackin7/Programming-Crappy-Solutions | /School Exercises/3. H2 Computing Notes/Searching and Sorting/test1.py | UTF-8 | 2,304 | 3.59375 | 4 | [] | no_license | import random
array = [random.randint(0,1000) for i in range(10)]
print(array)
def bubblesort(array):
noSwaps = False
while not noSwaps:
noSwaps = True
for i in range(len(array)-1):
if array[i] > array[i+1]:
noSwaps = False
temp = array[i]
... | true |
f73cc4d8040adff861da601097478ddb368baa1a | Python | aliciatoshima/python-exercises | /9-4.py | UTF-8 | 599 | 3.578125 | 4 | [] | no_license | # Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come grom each email address, and print the dictionary.
# basically exercise 8-5 to start
mbox = open('mbox-short.txt')
list = []
dict = dict()
for line in mbox:
this_line = line.split()
if len(th... | true |
eae3578a81d39a16fd4fd06274c3e96502f79270 | Python | haiyang1013/PythonSpiderEast | /EastSpider/spiders/eastspider.py | UTF-8 | 1,945 | 2.515625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule
from EastSpider.items import EastspiderItem
class eastspider(scrapy.spiders.CrawlSpider):
name = 'eastspider'
allowed_domains = ['eastbay.com']
start_urls = ['https://www.eastbay.com/cate... | true |
963c154d5cfa4d212ac4d68162f95a7e1983452a | Python | allanlealluz/Python-First-tests | /ex074.py | UTF-8 | 456 | 3.796875 | 4 | [] | no_license | from random import randint
n1 = randint(1,10)
n2 = randint(1,10)
n3 = randint(1,10)
n4 = randint(1,10)
n5 = randint(1,10)
lista = (n1,n2,n3,n4,n5)
print(lista)
c = 0
menor = lista[0]
maior = lista[0]
while c < len(lista):
if(lista[c] < menor):
menor = lista[c]
print(lista[c])
if(lista[c] > maio... | true |
343b236f37f0fe21083dc1c3f44173f3e9182fae | Python | Dancing-in-air/Bd-bar-sp | /百度贴吧/baidu_tieba01.py | UTF-8 | 753 | 3.25 | 3 | [] | no_license | import requests
import re
class BaiduTieba():
def __init__(self, name, page):
self.name = name
self.page = page
self.url = "https://tieba.baidu.com/f?kw={}&ie=utf-8&pn={}".format(self.name, (self.page - 1) * 50)
self.header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86... | true |
28005fdbfed6c22d828f1e21f1e623c77edcb41a | Python | chetakks/SV_SDA | /test_load_data.py | UTF-8 | 1,566 | 2.671875 | 3 | [] | no_license | # import pickle
# import cPickle
# data_path = '/home/aditya/store/Datasets/pickled/bbbc+feat/'
# f1 = open(data_path+'bbbc+feat_valid.pkl', 'rb')
# valid_set = cPickle.load(f1)
# print 'done'
# print 'nr validation instances: ', len(valid_set[0])
# print 'nr features: ',len(valid_set[0][0])
# print 'nr targets:... | true |
792f4979c72e54c2e36448af2736b94c0fc660b5 | Python | xiciluan/YelpDataAnalysis | /Code/DataCleaning_Business/biz_resturants.py | UTF-8 | 1,619 | 2.5625 | 3 | [] | no_license | import csv
import json
from collections import defaultdict
with open('category_biz.csv') as f:
reader = csv.reader(f)
restaurants_id = set()
for row in reader:
if row[0] == 'Restaurants':
restaurants_id.add(row[1])
f.close()
# print(restaurants_id)
id_features = defaultdict(lambda... | true |
b3d25474a838e378f7543dda980737ff1b5e1013 | Python | ankurs/Game-On | /Game-On-toy_car/proxy.py | UTF-8 | 257 | 2.515625 | 3 | [] | no_license | import socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind(("",9092))
s1.listen(1)
a,b = s1.accept()
print b
s2.connect(("192.168.122.163",9091))
while True:
s2.send(a.recv(1))
| true |
e01011c1cc91f58ad950e80adcc71c9da235320a | Python | EDA2021-1-SEC05-G8/Reto1-G08 | /App/controller.py | UTF-8 | 2,432 | 2.515625 | 3 | [] | no_license | """
* Copyright 2020, Departamento de sistemas y Computación,
* Universidad de Los Andes
*
*
* Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published b... | true |
18f77329505ef51bc95e9b5586f408a43686104e | Python | semipumpkin/BOJ | /15686_Chicken.py | UTF-8 | 1,364 | 2.9375 | 3 | [] | no_license | import sys
sys.stdin = open('input.txt', 'r')
def chicken_distance():
global answer
total = 0
for house in houses:
min_distance = 9999999
for sel in sels:
distance = abs(sel[0] - house[0]) + abs(sel[1] - house[1])
if distance < min_distance:
min_di... | true |
ee6c95d9315f7c16764b8d4ba73ebb47f112b06f | Python | ashleyliangzy/maya-parallel-samelength | /maya_average_parallel.py | UTF-8 | 3,346 | 2.78125 | 3 | [] | no_license | import pymel.core as pm
import pymel.util as pmu
import pymel.core.datatypes as dt
window=pm.window(title="align edge length",widthHeight=(350,350))
pm.columnLayout(rowSpacing=10)
startVertsList=[]
edgesList=[]
directionList = []
standardEdgeLen=0
#def OnChoosePlane(*args):
# selectObjList=pm.ls(sele... | true |
aefccdfe4067cd1229f4b2e63a2195a6281b06b4 | Python | hzengin/ArchiveOrganizer | /NameFinder.py | UTF-8 | 3,528 | 2.765625 | 3 | [] | no_license | #-*-coding: utf-8-*-
from xml.dom.expatbuilder import parseString
__author__ = 'hzengin'
import re
import urllib.request
import os
from Movie import *
from xml.dom.minidom import parse
class NameFinder:
texts=[]
def __init__(self):
toDelete = open("toDelete","r")
data=toDelete.read()
... | true |
03f8b927f43f39c1bcee159db2294f0f373b02dd | Python | donno/warehouse51 | /basic/py/lexer.py | UTF-8 | 7,527 | 3.28125 | 3 | [] | no_license | """Parses (tokenizers) a stream of characters into tokens (lexeme) for a BASIC
language.
Copyright (C) 2019 Sean Donnellan.
SPDX-License-Identifier: MIT
"""
import enum
import functools
import string
class LexemeType(enum.Enum):
Unknown = 0
Integer = 1
IntegerBase16 = 2
Real = 3
String = 4
Ide... | true |
e42ea9cd7f5f8e8a1a7b7f848b2430d08d65f02e | Python | muskan-aggarwal/PYTHON | /pattern_twochardownandup.py | UTF-8 | 656 | 3.65625 | 4 | [] | no_license | def printTwoCharUp(symbol,n):
ch='.'
space=0
chars=n
m=1
if(n%2==0):
line=n//2
else:
line=(n//2)+1
count=1
while(count<line):
print(ch*((chars//2)-space),symbol*m,ch*((chars//2)-space))
space+=1
m+=2
count+=1
return
def ... | true |
07e04e8d0f7a66517a5c96b61870689c8ca2bca5 | Python | CVxTz/taxi_duration | /read_data.py | UTF-8 | 3,965 | 2.984375 | 3 | [
"MIT"
] | permissive | import math
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from geopy.distance import vincenty
def read_data_base():
train = pd.read_csv("data/train.csv", parse_dates=['pickup_datetime', 'dropoff_datetime'])
test = pd.read_csv("data/test.csv", parse_dates=['pickup_dat... | true |
a374a88220dc7dc135726bfc7164ca7dfcf2135e | Python | Aye-Theingi/learningpython | /learningPython/learningPython/OOP_methods.py | UTF-8 | 803 | 3.75 | 4 | [] | no_license | '''
Created on Jun 8, 2020
@author: isgm137
'''
class Dog():
species='mammal'
def __init__(self,breed,name):
self.breed=breed
self.name=name
# print('Breed',self.breed)
# print('Name',self.name)
def bark(self):
print("Wolf,My name is {}".format(self... | true |
d4c190cd841cc1ee38fc7fba2e69ca472009a639 | Python | mengjie514/Twitter-notes | /notes_file_objects.py | UTF-8 | 1,176 | 3.3125 | 3 | [] | no_license | # File Objects
f = open('pre-SCOvENG.json', 'r')
print(f.name)
print(f.mode)
f.close()
# Open file with context manager (small file)
with open('pre-SCOvENG.json', 'r') as f:
print(f.read())
with open('pre-SCOvENG.json', 'r') as f:
f_contents = f.read()
print(f_contents)
# Open large file
... | true |
91884b4cbcfe68308ccfb804f864fc116c5c0790 | Python | meizhaohui/flask_web | /usesqlalchemy.py | UTF-8 | 6,425 | 3.40625 | 3 | [] | no_license | #!/usr/bin/python3
"""
@Author : 梅朝辉 Meizhaohui
@Email : mzh.whut@gmail.com
@Time : 2018/11/1 23:54
@File : usesqlalchemy.py
@Version : 1.0
@Interpreter: Python3.6.2
@Software: PyCharm
@Description: 使用sqlalchemy操作数据库
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionma... | true |
ee82866e7a0e684fd785138da27a8eeea1500c33 | Python | thehimel/data-structures-and-algorithms-udacity | /m04c02-graph-algorithms/i13e00_heapq.py | UTF-8 | 1,433 | 4.9375 | 5 | [] | no_license | """
Python's inbuilt heapq
With heapq module, you can convert a list into a min-heap.
The following two functionalities can be very handy for this task:
heappush(heap, item) — add item to the heap
heappop(heap) — remove the smallest item from the heap
Let's look at the above methods in action. We start by creating a... | true |
39854d8c0a7b8b44d1f1074145a1424617863618 | Python | victornjr/SoftwareQuality-Testing | /UnitTests/test_hello.py | UTF-8 | 723 | 3.546875 | 4 | [] | no_license | import unittest
import hello
class TestHello(unittest.TestCase):
# First test case -> returning Hello World!
def test_SayHello(self):
# If the method returns "Hello World!", then the test will pass
self.assertEqual(hello.sayHello(),"Hello World!")
def test_add(self):
# For this te... | true |
1014a1e8f6b4110c2e5b8c8a0c853429a8f371cb | Python | igortereshchenko/amis_python | /km73/Mirniy_Nickolay/5/task5.py | UTF-8 | 343 | 3.5 | 4 | [] | no_license | x = []
y = []
n = 8
for i in range(n) :
x.append(int(input('Введите x'+str(i+1) + ':' )))
y.append(int(input('Введите y'+str(i+1)+':')))
for i in range(n) :
for j in range(i+1 , n) :
if (abs(x[i]-x[j])) == (abs(y[j]-y[i])) or (x[i] == x[j]) or (y[i] == y[j]):
answer = 'Yes'
else :
answer = 'No'
print(... | true |
2ca2a51c3248075131085edc1b068ba563801820 | Python | itsintheletterbox/Racing | /Racing.py | UTF-8 | 9,621 | 2.609375 | 3 | [] | no_license | #Imports
import time
import datetime
import urllib2
from lxml import etree
from multiprocessing import Pool
## Parameters
valid_meets = {"AR"} #, "BR", "MR", "SR", "PR", "NR", "QR", "VR"}
## Date
curDate = datetime.datetime.today()
year = curDate.year
month = curDate.month
day = curDate.day
## Daylight savings time... | true |
f3e2a3b0a0fa1a7281d756556025219860480d6a | Python | yuribyk/library-assistant | /Library_Manager/DatabaseInteractor/DatabaseUtilities.py | UTF-8 | 1,329 | 2.546875 | 3 | [] | no_license | import pymysql
from DatabaseInteractor.DTO.DataPacker import DataPacker
class DataBaseUtilities:
def __init__(self):
pass
@staticmethod
def get_data_base_connection():
try:
db_connection = pymysql.connect("localhost", "root", "Peacer1490!", "LibrarySystem")
return ... | true |
1ef4eba1ca70947cdedad1336f8117ad9c254497 | Python | alb7979s/boj | /삼성기출/17136_색종이붙이기.py | UTF-8 | 1,320 | 2.625 | 3 | [] | no_license | #시간초과 뜸 수정하기
from sys import*
input = stdin.readline
def check(x, y, pos):
if colored_paper[pos] <= 0: return 0
for i in range(x, x+pos+1):
for j in range(y, y+pos+1):
if i>9 or j>9 or not a[i][j]: return 0
for i in range(x, x+pos+1): #색종이 덮기
for j in range(y, y+pos+1):
... | true |
bcb9909ba0d0b9ad850c78fa624147be4e4fde3e | Python | samparkewolfe/mido_extension_classes | /MidiSaver.py | UTF-8 | 2,573 | 3.21875 | 3 | [
"MIT"
] | permissive |
import mido_extension_classes.MidiNote as MidiNote
from mido import Message, MidiFile, MidiTrack, MetaMessage, second2tick
import copy
"""
MidiSaver Class
Details:
This object converts a list of custom MidiNote objects back to the mido midi message format and writes it to file.
Usage:
MidiSaver(notesToWrite... | true |
99483e4c7a9ff7e7b21851089586ac733fab638f | Python | jvanvugt/advent-of-code-2019 | /day19.py | UTF-8 | 1,670 | 3.03125 | 3 | [] | no_license | from intcode import Computer
from utils import neighbours
from collections import deque
import itertools
class BeamComputer(Computer):
def __init__(self, program, x, y):
self.inputs = iter([x, y])
self.res = float("nan")
super().__init__(program)
def process_output(self, o):
s... | true |