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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
83d8f01b28464ec55edaaa39fe4cb19a0347229f | Python | xamroot/cryptopals | /set2/challenge10.py | UTF-8 | 1,008 | 2.859375 | 3 | [] | no_license | from Crypto.Cipher import AES
import base64
import sys
sys.path.insert(1, '../tools/')
import CBC as c
def xor(block0, block1):
ret = bytearray()
for (a,b) in zip(block0,block1):
ret.append(a^b)
return bytes(ret)
def cbc_encrypt(plainblocks, iv, cipher):
ret = []
prev_block = iv
for p in plainblocks:
pre... | true |
17b62124b2e11e91054331ad4722edf4c8732306 | Python | shriki001/Operating-Systems | /Python/Class/ex3.py | UTF-8 | 1,711 | 3.90625 | 4 | [] | no_license | #%%--------------------------------------------------------------------------%%#
#ex3.1
lst1 = [int(x) for x in input("enter first series").split()]
lst2 = [int(x) for x in input("enter second series").split()]
if [x**2 for x in lst1] == lst2:
m_list = [x + y for x, y in zip(lst1, lst2)]
print(m_list)
#######... | true |
e143bb92c6799bc8e8b73e47544df1cdfb433668 | Python | VanyaVoykova/SoftUni-Math-Concepts-For-Developers-February-2021 | /Training-Math-Codes/cryptography.py | UTF-8 | 1,113 | 3.515625 | 4 | [] | no_license | import matplotlib.pyplot as plt
from secrets import randbits
from sympy import Mul, factorint
import timeit
def get_bits(start_bit, end_bit, step=8):
return [bit for bit in range(start_bit, end_bit, step)]
def get_times(bits):
fact_times = []
mul_times = []
for bit in bits:
fact_param = rand... | true |
898519a17c84070ce82bd6a9d19211d1f57e0397 | Python | ramadnsyh/twitter-news-summarization | /tweet_summarization.py | UTF-8 | 3,458 | 2.71875 | 3 | [] | no_license | import os
from bs4 import BeautifulSoup
import requests
from requests_oauthlib import OAuth1
from dotenv import load_dotenv
from gensim.summarization import summarize, keywords
import argparse
load_dotenv()
def env_vars(request):
return os.environ.get(request, None)
def check_authentication():
auth = authent... | true |
55df9b47747a5c42869b00b28227553ececc7704 | Python | alexmereuta/Lab_SI | /Lab1_SI/clientUDP.py | UTF-8 | 311 | 2.859375 | 3 | [] | no_license | import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "This is a UDP message!"
print ("UDP target IP:", UDP_IP)
print ("UDP targer port:", UDP_PORT)
print ("message:", MESSAGE)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #UDP
s.sendto(MESSAGE.encode('utf-8'), (UDP_IP, UDP_PORT))
| true |
a3535a3946e13aadfa53c2ca7bca79e8576e75d7 | Python | twathit/algorithm | /changes.py | UTF-8 | 2,152 | 3.578125 | 4 | [] | no_license | #钱币找零:假设用于找零的钱币包括四种:25美分,10美分,5美分,1美分,求给用户找回数目最少的钱币。
#方法一
def recMC(coinValueList,changes):
minCoins=changes
if changes in coinValueList:
return 1
else:
for i in [c for c in coinValueList if c <= changes]:
numcoins = 1+ recMC(coinValueList,changes-i)
if numcoins < minCoins:
minCoins = numco... | true |
22aa0377be716b0ab13183a1e89a533d223efa50 | Python | QTtrash/insta-pie-bot | /webapp/Utilities.py | UTF-8 | 470 | 2.734375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | # Random comments, that i copied from Instagram, bot needs to blend in
comments = ['Damn, son, where did you find this?',
'Ayyyyy lmao, n1, n1, dude',
'What in the flying frick is that even suppose to mean?',
'Hello, officer, arrogant people wildin',
'True, it really do b... | true |
6e8b9ce0f5226bf6b2dfbcdaec4db1f691c00f95 | Python | coding1617/Word-Search | /instructions.py | UTF-8 | 2,212 | 3.484375 | 3 | [] | no_license | from tkinter import *
class Instruction_page(Frame):
def __init__(self, master, return_home):
"""Initialize Frame."""
self.return_home = return_home
super(Instruction_page, self).__init__(master, background = "mistyrose")
master.title("Instructions Page")
self.grid()
self.create_widgets... | true |
774d6789cb107c790b057320f8b235d0dc535e5e | Python | susu25/DouBanTV | /spider/parse.py | UTF-8 | 493 | 2.65625 | 3 | [] | no_license | import time
from retrying import retry
from config import SPIDER_HEADERS
import requests
@retry(stop_max_attempt_number=3)
def _parse_url(url):
response = requests.get(url,timeout=5,headers = SPIDER_HEADERS)
assert response.status_code == 200
return response.content.decode()
def parse_url(url):
print(... | true |
d236624f8d7eb91c223d8ebf1e62658e6995564b | Python | Jmyerzzz/lmu-artificial-intelligence | /HW1/Pathfinder.py | UTF-8 | 5,958 | 3.546875 | 4 | [] | no_license | '''
The Pathfinder class is responsible for finding a solution (i.e., a
sequence of actions) that takes the agent from the initial state to all
of the goals with optimal cost.
This task is done in the solve method, as parameterized
by a maze pathfinding problem, and is aided by the SearchTreeNode DS.
Jackson ... | true |
5786135e7d7068575b1dfa2fbe80b1c053491b65 | Python | FujitaHirotaka/djangoruler3 | /examples/django/応用/簡易アップローダー/project/media/広島/_iterator.py | UTF-8 | 447 | 4.09375 | 4 | [] | no_license | class MyIterator(object):
def __init__(self, *numbers):
self._numbers=numbers
self._i=0
def __iter__(self):
return self
def __next__(self):
if self._i==len(self._numbers):
raise StopIteration()
value=self._numbers[self._i]
self._i+=1
... | true |
f120141098feb6b58c81d25c72ea932d4fa15063 | Python | simonsny/challenge-card-game-becode | /utils/game.py | UTF-8 | 2,756 | 4.03125 | 4 | [] | no_license | from utils.player import Player
from utils.deck import Deck
class Board:
def __init__(self, players: list = None):
"""
:param players: List of players that will play the game. Can be added later.
"""
if players:
self.players = players
else:
self.play... | true |
870631772c54762d80469ac1004f93b5c652c647 | Python | Yonimdo/Python-Intro | /ListComprehension/42/42.py | UTF-8 | 589 | 3.671875 | 4 | [] | no_license | def word_lengths(s):
# ==== YOUR CODE HERE ===
# =======================
return [len(w) for w in s.split()]
def max_word_length(s):
# ==== YOUR CODE HERE ===
# =======================
return max(word_lengths(s))
result = word_lengths("Contrary to popular belief Lorem Ipsum is not sim... | true |
aa332da03a0d41a15cd6a834aed451b5e346a7ec | Python | qh96/leetcode | /solutions/807.custom-sort-string/custom-sort-string.py | UTF-8 | 530 | 2.890625 | 3 | [] | no_license | class Solution:
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
d = {}
set_S = set(S)
ans = ''
for i in T:
if i in d:
d[i] += 1
else:
d[i] = 1
# pri... | true |
715577069ed1c3c3e2979ecee1f3fcefee2c6700 | Python | MacRayy/exam-trial-basics | /countas/count-as.py | UTF-8 | 742 | 3.90625 | 4 | [] | no_license | # Create a function that takes a filename as string parameter,
# counts the occurances of the letter "a", and returns it as a number.
# If the file does not exist, the function should return 0 and not break.
# print(count_as("afile.txt")) # should print 28
# print(count_as("not-a-file")) # should pr... | true |
1ea04101db67ca546aa2ff63e6d3f713590b70b9 | Python | mdhiggins/ardsnet-calculator | /ardsnet.py | UTF-8 | 6,003 | 2.953125 | 3 | [
"MIT"
] | permissive | import enum
class Gender(enum.Enum):
Male = "male"
Female = "female"
class Patient():
__PBW_BASE_VALUE__ = {
Gender.Male: 50.0,
Gender.Female: 45.5,
}
def __init__(self, gender, height):
self.gender = gender
self.height = height
@property
def pbw(self):
... | true |
daf62555433e2d4fcd82423f7585ec0abdb4a8fb | Python | yamlfullsan/cursopython | /condicional.py | UTF-8 | 226 | 3.609375 | 4 | [] | no_license | print("Programa de evaluación")
nota_alumno=input("Introduce la nota: ")
def evaluacion(nota):
valoracion="aprobado"
if nota<5:
valoracion="suspenso"
return valoracion
print(evaluacion(int(nota_alumno)))
| true |
68bafc365711610eb56fcd7122baaa2f8c6dcc7e | Python | vinayakushakola/Patterns | /2. NumberPatterns.py | UTF-8 | 2,314 | 3.8125 | 4 | [] | no_license | print("Pattern 1")
for i in range(1, 5):
for j in range(i):
print(f'{i} ', end="")
print()
print("Pattern 2")
for i in range(1, 5):
for j in range(i):
print(f'{j+1} ', end="")
print()
print("Pattern 3")
for i in range(1,6):
for j in range(5-i):
print(end=" ")
for k in r... | true |
92e89899ddaeeadb607798814185ff1872e80914 | Python | shahineb/archives1819 | /reinforcement-learning/HWK1/1_Dynamic_Programming/utils.py | UTF-8 | 627 | 3.078125 | 3 | [] | no_license | import numpy as np
def bellman_operator(r, P, V, gamma):
"""Computes Bellman Operator application on V
Parameters
----------
x : int
state index
r : numpy.array
reward matrix (n_states_, n_actions_)
P : numpy.array
transition probability matrix
(n_states_, n_act... | true |
88ed2453ff90332e0f1c68cb537a1031bacf11b5 | Python | mahdifarhang/DA_CAs | /ca2/q2.py | UTF-8 | 550 | 2.96875 | 3 | [] | no_license | n, m = [int(x) for x in raw_input().split()]
array = [[int(x), 0] for x in raw_input().split()]
temp = [int(x) for x in raw_input().split()]
for i in xrange(n):
array[i][1] = temp[i]
rooms = []
for i in xrange(m):
rooms.append([0, 0])
sorted_list = sorted(array, key=lambda x: x[0])
flag = True
for i in xrange(n):
fo... | true |
71dd9b29b8044832face453ea3c46a0acd5f9922 | Python | Fredooooooo/incubator-iotdb | /importerCSV-py/src/utils/RowRecord.py | UTF-8 | 978 | 2.59375 | 3 | [
"Apache-2.0",
"EPL-1.0",
"MIT",
"BSD-3-Clause",
"CDDL-1.1",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | from IoTDBConstants import TSDataType
from Field import Field
class RowRecord(object):
def __init__(self, timestamp, field_list=None):
self.__timestamp = timestamp
self.__field_list = field_list
def add_field(self, field):
self.__field_list.append(field)
def add_field(self, valu... | true |
ed2a5fa7b84ef49ec8b7121a664994a5f9aa4e5c | Python | bgants/vagrantProjects | /spark/testPythonContext.py | UTF-8 | 575 | 2.625 | 3 | [] | no_license | from __future__ import division
from pyspark import SparkConf, SparkContext
import sys
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf)
autoData = sc.textFile("/vagrant/autos.csv")
autoCount = autoData.count()
diesels = autoData.filter(lambda line: "diesel" in line)
dieselCo... | true |
745046ba178a80a3afd01a2a2cb608008f4013df | Python | gauravaror/programming | /calcEqn.py | UTF-8 | 1,107 | 2.96875 | 3 | [] | no_license | from collections import defaultdict
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
hh = defaultdict(dict)
for eqn,val in zip(equations, values):
a,b = eqn
hh[a][b] = val
hh[b][a] = ... | true |
4015da9a11ffac7f2fafb3e70b52b19a7096259e | Python | BrandonKirklen/randomProjects | /AdventOfCode2018/day1/day1.py | UTF-8 | 1,370 | 3.640625 | 4 | [] | no_license | #!/usr/bin/python
import unittest
def freqCalc(input):
return sum(input)
def freqDouble(input):
seenFreqs = {0}
currentSum = 0
found = False
while not found:
for x in input:
currentSum += x
if currentSum in seenFreqs:
found = True
br... | true |
734226c0713e8c41a09405dacd398f0c6a0eb9b8 | Python | Mongoos/Hello-python-projects | /random_codes/Battleship.py | UTF-8 | 206 | 2.765625 | 3 | [] | no_license | import numpy as np
import random as rn
def generate_your_board(board):
"""asks user to place their battleships on their generated board."""
your_board = np.zeros(shape=(10,10))
print(your_board)
| true |
3c7ee08ef83da00c0171b24e0ccc8a78a0220936 | Python | vandanparmar/SURFcode | /dct/sim/dctcont.py | UTF-8 | 18,022 | 3.15625 | 3 | [] | no_license | """
.. _continuous:
Continuous Simulation (:mod:`cont`)
=========================================
Solving setups of the form,
.. math::
\dot{x} = \mathbf{A}x + \mathbf{B}u \n
y = \mathbf{C}x + \mathbf{D}u
Relevant Examples
******************
* :ref:`continuous_eg`
* :ref:`network_eg`
Initialisation and Setting M... | true |
3569e26a85575f8de8663f4ac921e5237a8565a7 | Python | Amazon-Lab206-Python/Todd_Enders | /OOP/MathDojo.py | UTF-8 | 737 | 3.609375 | 4 | [] | no_license | class MathDojo(object):
def __init__(self):
self.result = 0
def add(self, *nums):
for obj in nums:
if type(obj) is list or type(obj) is tuple:
for num in obj:
self.result += num
else:
self.result += obj
return... | true |
59a0701749f40d289f4e13a24cb185869929101d | Python | JaeDukSeo/Personal_Daily_NeuralNetwork_Practice | /3_tensorflow/archieve/b_dense_net_part_practice.py | UTF-8 | 1,351 | 2.8125 | 3 | [] | no_license | import tensorflow as tf
import numpy as np
# 1. Make the Graph
graph = tf.Graph()
with graph.as_default():
input_1 = tf.placeholder('float',[3,3])
batch_norm = tf.contrib.layers.batch_norm(input_1)
input_2 = tf.placeholder('float',[1,4,4,1])
max_pool = tf.nn.max_pool(input_2,ksize=[1,2, 2,1], strid... | true |
5d89c1a5987331b0966925288c47ca3b0e12bdb3 | Python | pro1zero/Machine-Learning-Loan-Prediction | /details.py | UTF-8 | 684 | 2.75 | 3 | [] | no_license | import sqlite3
conn = sqlite3.connect('customer.db')
cursor = conn.execute("SELECT NAME,GENDER,AGE,MARRIED,DEPENDENTS,EDUCATION,SELF_EMPLOYED,MONTHLY_INCOME,YEARLY_INCOME,LOAN_AMOUNT,LOAN_AMOUNT_TERM,PROPERTY_AREA from CUST_DATA")
for data in cursor:
print("name=",data[0])
print("gender=",data[1])
p... | true |
b51878e6813a4bf01d7ca0a45ac275f080bfd1ef | Python | P-Swati/MayLeetCodeChallange | /Day29_CourseSchedule.py | UTF-8 | 4,552 | 3.421875 | 3 | [] | no_license | #approach 1: in dfs, if an edge to a node which is already visited **within cur recursion stack** is encountered, then there is a cycle.
class Solution:
def detectCycle(self,start,adjList,visited):
visited[start]=1
for i in adjList[start]:
if(visited[i]==0):
... | true |
3ee2ad67fabef9374e124b210b5a36a785ec69f3 | Python | youngce/FightTheLandlordBot | /handleImg.py | UTF-8 | 878 | 2.59375 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import cv2
img=cv2.imread("./test.png")
# r = 1
#
# fig, ax = plt.subplots()
# ax.imshow(img, extent=(0,img.shape[1]/r,0,img.shape[0]/r) )
# ax.set_xlabel("distance [m]")
# ax.set_ylabel("distance [m]")
#
# plt.show()
# r=cv2.selectROI(img)
r=[216, 27, 259, 34]
# prin... | true |
824da89fe96748c616ac895a44a462cc5561e0fe | Python | reesezxf/pickleFilter | /pickleFilter.py | UTF-8 | 1,451 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python
# coding:utf-8
# author 9ian1i
# created at 2017.03.24
# a demo for filter unsafe callable object
from pickle import Unpickler as Unpkler
from pickle import *
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# 修改以下白名单,确认你允许通过的可调用对象
allow_list = [str,... | true |
bf4a14e7a15202dd98b0e7d072c07af43c19c3ed | Python | dannysvof/SUAEx | /select_aspects/select.py | UTF-8 | 2,386 | 2.890625 | 3 | [] | no_license | import codecs
def format_lines(attib_file):
totales = []
with open(attib_file, 'r') as f:
lines = f.readlines()
arr_letras = []
arr_pesos = []
for i in range(len(lines)):
if(i%4==0):
arr_letras.append(lines[i].strip().split(' '))
#print(lines[i].strip())
... | true |
7874c29a0cc568942ffa79d7e9e1ff68b93c441d | Python | rcamilo1526/Data_Science_introduction | /Basico/randomgame.py | UTF-8 | 605 | 3.765625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 11:26:45 2019
@author: Estudiantes
"""
from random import randrange
r=randrange(100)
print(r)
tries=0
for i in range(11):
print('Intento {}:'.format(tries+1))
a=int(input('Ingrese el numero: '))
if a==r:
print('Adivino el numero {} en {} intentos'... | true |
c62391b29ed3cc1b496498ff1ee8584754f2bea1 | Python | blueskywalker/junkyard | /python/greedy/powerset.py | UTF-8 | 322 | 3.3125 | 3 | [] | no_license | def powerset(data):
if len(data) == 0:
return [[]]
pivot = data[0]
results = powerset(data[1:])
new_results= results.copy()
for item in results:
new_results.append([pivot] + item)
return new_results
data = ['a', 'b', 'c']
print(list(filter(lambda x: len(x) == 2,powerset(data)))... | true |
1b4b66f45cf8ba43a52cef6cd894889dcc117a23 | Python | nikhilsampangi/CSES_Problem_Set | /1_IntroductoryProblems/10_TrailingZeros.py | UTF-8 | 147 | 3.59375 | 4 | [] | no_license | if __name__ == "__main__":
n = int(input())
p = 5
sol = 0
while n >= p:
sol += n//p
p = p*5
print(sol)
| true |
3f0eff6732ef4d2006f33b373f3b1dcd1a81a354 | Python | metadatacenter/cedar-util | /scripts/python/cedar/utils/storer.py | UTF-8 | 1,828 | 2.84375 | 3 | [
"BSD-2-Clause"
] | permissive | # -*- coding: utf-8 -*-
"""
utils.storer
~~~~~~~~~~~~~~
This module provides utility functions that are used to create a CEDAR
resource (template/element/instance) via a POST request.
"""
import requests
import json
from urllib.parse import quote
from requests.packages.urllib3.exceptions import InsecureRequestWarning... | true |
0e165278c3c4335e7b78d97485e00880917d6066 | Python | Fr4nc3/code-hints | /python/Scientific/sample2/projectile.py | UTF-8 | 1,434 | 3.28125 | 3 | [] | no_license | # *************************************
# @Fr4nc3
# file: projectile.py
# implement methods
# g(h)
# s_next ( s_current, v_current, delta_t)
# v_next(s_next, v_current, delta_t)
# s_sim(t, v_init, s_init, delta_t)
# s_standard(t,v_init)
# *************************************
GRAVITATIONAL_CONSTANT = 6.6742e-11 # grav... | true |
4a18ae9b71b01cf91408fc8b3e66ded0fb99278c | Python | ashcrow/trello-card-maker | /trello-card-maker | UTF-8 | 4,691 | 2.859375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2016 Steve Milner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | true |
553c64c46410c442b340060e7d2ee70953c6d901 | Python | PrimeCodingSolutions/otree-core | /otree/extensions.py | UTF-8 | 2,327 | 2.578125 | 3 | [
"MIT"
] | permissive | from importlib import import_module
from django.conf import settings
import importlib.util
import sys
"""
(THIS IS CURRENTLY PRIVATE API, MAY CHANGE WITHOUT NOTICE)
To create an oTree extension, add a package called ``otree_extensions``
to your app, and add the app name in settings.py to EXTENSION_APPS.
It can cont... | true |
23febe2d60eec809186243cf9481043fb6521217 | Python | AnXnA05/python_practic | /0817_triangle.py | UTF-8 | 290 | 3.6875 | 4 | [] | no_license | #coding=utf-8
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a+b>c and a+c>b and b+c>a:
print('周长为 %.2f' % (a+b+c))
p=(a+b+c)/2
print('面积为 %.2f' % (p*(p-a)*(p-b)*(p-c)**0.5))
else:
print('您输入的数据无法组成三角形') | true |
94a540d33c1fac6ccb19a78fcf621519eadd8f31 | Python | thongdong7/tb-api | /tb_api/utils/json_utils.py | UTF-8 | 352 | 2.53125 | 3 | [] | no_license | import json
from six import string_types
from tb_ioc.class_utils import get_class
class JsonDumper(object):
def __init__(self, cls=None):
if cls:
if isinstance(cls, string_types):
cls = get_class(cls)
self.cls = cls
def dumps(self, data):
return json.dump... | true |
579dbfcf7e77d69070fe84bd750defb308832fbd | Python | lukeburpee/archived-legalease-code | /legalease/pst-master/ocr/spark-newman-human-receipt-detection/NeuroTools/analysis.py | UTF-8 | 17,710 | 2.921875 | 3 | [] | no_license | """
NeuroTools.analysis
===================
A collection of analysis functions that may be used by NeuroTools.signals or other packages.
.. currentmodule:: NeuroTools.analysis
Classes
-------
.. autosummary::
TuningCurve
Functions
---------
.. autosummary::
:nosignatures:
ccf
crosscorrelate
make_ke... | true |
fccac36a133fe485f4c6b80dfc85d9bb0d75f188 | Python | WustAnt/Python-Algorithm | /Chapter3/3.3/3.3.6/3-6baseConverter.py | UTF-8 | 1,098 | 3.921875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2020/8/1 11:52
# @Author : WuatAnt
# @File : 3-6baseConverter.py
# @Project : Python数据结构与算法分析
from stack import Stack
"""
十进制数转换任意进制数:
decNumber:接受任意非负整数
base:要转换进制数
使用‘除以N’算法,待处理整数大于0,循环不停地进行十进制除以N,并记录余数
对应的N进制数,为余数,第一个余数是最后一位
"""
def baseConverter(decNumber,bas... | true |
5ee277f18cbfac9784e9029f3e68f1925cf426b2 | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4079/codes/1668_1396.py | UTF-8 | 160 | 2.953125 | 3 | [] | no_license | conta_restaurante=float(input("valor))
if (gorjeta<=300):
print(gorjeta-round(gorjeta*0.10))
else:
gorjeta(gorjeta-(gorjeta*0.06)
print(conta_restaurante,2) | true |
80434fcce27977f74e0c42f2e88aa9b7c4e4d9f3 | Python | jain-abhinav/news_clustering_nlp | /news_analysis.py | UTF-8 | 4,348 | 3 | 3 | [] | no_license | #text clustering LDA
#text processing
#visualizations
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import lda
import logging
logging.getLogger("lda").setLevel(... | true |
eca76103cafd3f03acadad15a397edc07e5b9322 | Python | pengyuhou/git_test1 | /leetcode/整数反转.py | UTF-8 | 564 | 3.28125 | 3 | [] | no_license | x=1534236469
x1=2**31+1
print(x1)
class Solution(object):
def reverse(self, x):
if x<2**31-1 and x>(-2)**31:
if x<0:
x=-x
x = str(x)
x = list(x)
x.reverse()
x = "".join(x)
ret="-"+x
r... | true |
7f61ee4d5e9039d3588138b16dc2cf83afa71c66 | Python | t77165330/260201017 | /lab6/example2.py | UTF-8 | 380 | 3.625 | 4 | [] | no_license | a = int(input("How many students : "))
d = []
for i in range(a):
print(i + 1, ". student")
x = []
b = input("Enter the grades by splitting with (,): ").split(",")
for c in range(3):
if c == 1:
x.append(int(b[c]) *40/100)
else:
x.append(int(b[c]) *30/100)
a = 0... | true |
2b3c226d00328086567c1b86175a9a373b99ddc9 | Python | mihaiconstantin/tesc-publications | /lib/TescPerf/tescworkers.py | UTF-8 | 5,504 | 2.734375 | 3 | [] | no_license | from threading import Thread
from queue import Queue
from time import time
# from teschelpers import UrlFetcher, UrlBuilder
from lib.TescPerf.teschelpers import UrlFetcher, UrlBuilder
# Links.
class LinkWorker(Thread):
'''Extracts the links of a search query.'''
all_links = []
def __init__(self, queue):
Thread... | true |
a8e72b594eb8697ce0a40bd12444e3d89a76cdd8 | Python | KaimingWan/Python_Learning | /os_homework.py | UTF-8 | 3,761 | 3.453125 | 3 | [] | no_license | __author__ = 'Kaiming'
import os
import pdb
class IO_dir(object):
flag = False # 类变量,用于在类全局内保存是否找到相应的文件
def dir_l(self):
'用于显示当前目录下所有文件和目录'
list_all = os.listdir() # listdir包括所有文件和目录,不加任何参数默认是当前目录下
print('当前目录下的所有目录如下:')
# 这里os.path.isdir不需要join,因为当前目录本来就有x
list_dirs... | true |
08940d86eb8b09534defeae14c1b946c5d15d90c | Python | swansong/labgeeksrpg | /pythia/test/page_test.py | UTF-8 | 3,135 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | """
Tests creation and editing of pages
"""
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from pythia.models import *
import datetime
import pdb
class PageTestCase(TestCase):
... | true |
7e6f893ad8a9095ce7d1374dfebd234e3ce0820b | Python | frdrkandersson/AdventOfCode2020 | /Day04/solution.py | UTF-8 | 1,499 | 2.765625 | 3 | [] | no_license | from os.path import abspath, dirname, join
import re
with open(abspath(join(dirname(__file__), 'input.txt')), 'r') as f:
data = f.read().split("\n\n")
data = [row.replace("\n", " ") for row in data]
data = [row.split() for row in data]
passports = [dict(pair.split(":") for pair in row) for row in data]... | true |
28bf362737a0b40e53c4bb35e99fd2179cd1af47 | Python | hlim1/delphi | /delphi/analysis/sensitivity/variance_methods.py | UTF-8 | 1,891 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | from abc import ABCMeta, abstractmethod
import inspect
from SALib.sample import saltelli
from SALib.analyze import sobol
import numpy as np
class VarianceAnalyzer(metaclass=ABCMeta):
"""
Meta-class for all variance based sensitivity analysis methods
"""
def __init__(self, model, prob_def=None):
... | true |
2038006dbde7623062fa291f60ff22d7e2fa569b | Python | CarsonScott/Evolutionary-Logic-Learning | /src/neural_network.py | UTF-8 | 4,943 | 2.5625 | 3 | [] | no_license | from lib.relations import *
from lib.util import *
from pattern import *
import math
def multiply(X, Y):
return [X[i] * Y[i] for i in range(len(X))]
def subtract(X, Y):
return [X[i] - Y[i] for i in range(len(X))]
class NeuralNetwork(list):
def __init__(self, shape):
shape = shape
self.weights = []
self.bias... | true |
c166d67d162e22d5171c25d88219664f17a0be6f | Python | hildebrando001/Finance | /RealTimeStock/hb_platform.py | UTF-8 | 2,931 | 2.890625 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.gridspec import GridSpec # split screen into grids
import matplotlib.ticker as mticker
import datetime
import math
fig = plt.figure()
fig.patch.set_facecolor('#121416')
gs = fig.add_gridspec(6,6) # Screen div... | true |
2586811b137ecd17cab6f79ce1ff5774e85f9407 | Python | ZhangjlGIT/test_android_for_diamond | /public/Adb_devices.py | UTF-8 | 773 | 3.078125 | 3 | [] | no_license | # -*- coding:utf-8 _*-
"""
@author:zhangjianlang
@file: test.py
@time: 2019/9/16 20:20
"""
import os
def lookforDevices():
# popen返回文件对象,跟open操作一样
f = os.popen(r"adb devices", "r")
out = f.read()
f.close()
# print(out) # cmd输出结果
# 输出结果字符串处理
s = out.split("\n") # 切割换行
new = [x for ... | true |
206a256cb5c78763e3c19a0c0dc8d0b8d8b66fc7 | Python | yolo-forks/YOLOv3 | /prepare_data.py | UTF-8 | 3,485 | 3.421875 | 3 | [] | no_license | import os
import pandas as pd
from copy import copy
import numpy as np
import shutil
import argparse
def parse_my_csv(path_to_csv_file):
"""
This function reads all the annotations from the csv file and then create a dictionary
that stores these annotations.
The dictionary will have as a key the name o... | true |
5f9a13c0c9fb4e0bbaf9c143449fc839be78f4c4 | Python | AmrKhalifa/Solutions-to-MIT-6.0002-Introduction-to-Computational-Thinking-and-Data-Science-assignments | /PS2/ps2.py | UTF-8 | 8,810 | 3.6875 | 4 | [] | no_license | # 6.0002 Problem Set 5
# Graph optimization
# Name:
# Collaborators:
# Time:
#
# Finding shortest paths through MIT buildings
#
import unittest
from graph import Digraph, Node, WeightedEdge
#
# Problem 2: Building up the Campus Map
#
# Problem 2a: Designing your graph
#
# What do the graph's nodes represent in this p... | true |
70ba4039c494a2b954302587ca0555276ef8e0de | Python | amankumarsinha/amankumarsinha.github.io | /dict.py | UTF-8 | 418 | 4.03125 | 4 | [] | no_license | #to represent real life data
#collection of data in key : value pair
user = {'name' : 'aman','age' : 20}
print(user)
print(type(user))
# 2 method
user1 = dict(name = 'aman',age = 20)
print(user1)
print(user1['name'])
# type of data store in dict
#---> number ,string, list,dict
userinfo = {
'n... | true |
f49e8afce7b6a89d82da36a8397f59c50e86f0e5 | Python | asfiowilma/rakbookoo-api | /author/models.py | UTF-8 | 762 | 2.78125 | 3 | [] | no_license | from django.db import models
from rest_framework import serializers
class Author(models.Model):
first_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
@property
def full_name(self):
"Returns the person's full n... | true |
fe3f75adbb651275870aa222e98903bcbf52188f | Python | Arkady-G/Practice-15-02 | /API response check list - 04-05.py | UTF-8 | 6,207 | 2.609375 | 3 | [] | no_license | import json
with open('json_example_QAP.json', encoding='utf8') as file: # Открываем файл
strfile = file.read()
templates_resp = json.loads(strfile)
# Список полей в шаблоне
fields_list = ['timestamp',
'referer',
'location',
'remoteHost',
'partyId',... | true |
e4b1897dbd0bad3aa46c8e885dfd875c870e2781 | Python | scottmries/eulerproject | /112.py | UTF-8 | 546 | 3.53125 | 4 | [] | no_license | ratio = 0.0
i = 100.0
bouncies = 0.0
def is_bouncy(n):
a_digit_increases = False
a_digit_decreases = False
for e, digit in enumerate(str(n)[:-1]):
if int(digit) > int(str(n)[e+1]):
a_digit_decreases = True
if int(digit) < int(str(n)[e+1]):
a_digit_increases = True
if a_digit_increases and a_digit_decr... | true |
3c7be769c5db141f4c8b0121093a3ef661a50273 | Python | awaddell77/Math-Python-Projects | /B_tree.py | UTF-8 | 3,044 | 3.34375 | 3 | [] | no_license | #bin tree
#technically it is a binary search tree
class B_tree:
def __init__(self, head):
self.head = head
def add(self, data):
root = self.head
if not root:
self.head = Node(data)
return
return self._add_help(data, root)
def _add_help(self, data, node):
#needs to control for insertions/duplic... | true |
5ebb6c67d7b864653421def66d0c4094f25d114f | Python | mugenZebra/MangaStyle | /manga_model.py | UTF-8 | 9,834 | 2.6875 | 3 | [] | no_license | import tensorflow as tf
def model(images, batch_size, classes, dropout):
"""Build the model
Args:
images: Tensor with image batch [batch_size, height, width, channels].
batch_size: Number of image of one batch.
classes: Number of classes.
dropout: Dropout probability, but ... | true |
f1e2e1fc212a722d2c8f568ed99a43e3e6b5be43 | Python | brainerazer/SustainRefer | /SRC/approximateBcalc.py | WINDOWS-1251 | 1,077 | 2.671875 | 3 | [] | no_license | #!/usr/local/bin/python3
import scipy.optimize
import numpy as np
from math import ceil, log, exp
import matplotlib.pyplot as plt
import sys
from matplotlib2tikz import save as tikz_save
data = np.genfromtxt(sys.argv[1], delimiter=',')
def B_func(p, c):
l = p
ll = np.log(l)
pw = np.multiply(np.power(l, 0... | true |
c8427d92a682caaa90b2bf6ad1a67bbf5d03d9f3 | Python | suhasghorp/QuantFinanceBook | /PythonCodes/Chapter 14/Fig14_05.py | UTF-8 | 1,373 | 3.03125 | 3 | [] | no_license | #%%
"""
Created on Feb 10 2019
Ploting of the rates in positive and negative rate environment
@author: Lech A. Grzelak
"""
import numpy as np
import matplotlib.pyplot as plt
def mainCalculation():
time = np.linspace(0.1,30,50)
Rates2008 = [4.4420,4.4470,4.3310,4.2520,4.2200,4.2180,4.2990,4.3560,4... | true |
01df016790f7b89565368e46246513d5bacab933 | Python | applecrumble123/ComputerVision | /Colour conversion and geometric transformations/Task1.2P.py | UTF-8 | 4,318 | 3.34375 | 3 | [] | no_license | import numpy as np
import cv2 as cv
img = cv.imread('/Users/johnathontoh/Desktop/SIT789 - Applications of Computer Vision and Speech Processing/Week 1/Task 1.2P/Resources_1.2/img1.jpg')
#----------------------------- colour conversion ------------------------------------
# image img is represented in BGR (Blue-Green... | true |
635fbb48899aa4178ada327a86b09f1524d710aa | Python | capaulson/pyKriging | /examples/3d_Simple_Train.py | UTF-8 | 1,377 | 3.078125 | 3 | [
"MIT"
] | permissive | from __future__ import print_function
import pyKriging
from pyKriging.krige import kriging
from pyKriging.samplingplan import samplingplan
from pyKriging.testfunctions import testfunctions
# The Kriging model starts by defining a sampling plan, we use an optimal Latin Hypercube here
sp = samplingplan(3)
X = sp.optima... | true |
b961ddf6023da7670c1aa19d5f205988cb5ff922 | Python | surzioarmani/python_for_codingTest | /2020_Coding_Test/programmers_10_1.py | UTF-8 | 345 | 3.125 | 3 | [] | no_license | def solution(n):
answer = 0
first = n
left = []
while first > 3:
left.append(first % 3)
first = first // 3
left.append(first)
print(left)
n = 1
for i in range(len(left)):
answer += left[len(left)-1-i] * n
n *= 3
print(n)
print(ans... | true |
c12a3c61535bf9a0ca438801662ceb2ee49df227 | Python | kokokong/ssu-tensorflow-lecture | /ML-lecture/2일차/Matplot/py file/Matplot02.py | UTF-8 | 510 | 2.78125 | 3 | [] | no_license |
# coding: utf-8
# In[1]:
import tensorflow as tf
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
filename = "도깨비.jpg"
image = mpimg.imread(filename)
print("Original size:" ,image.shape)
x = tf.Variable(image,name = 'x')
init = tf.global_variables_initializer()
with tf.Session() as sess:
x = t... | true |
268c895cec7413aaf5a722056c13ef4ac6fda8a6 | Python | adahya/APIServer | /API/modules.py | UTF-8 | 1,006 | 2.5625 | 3 | [] | no_license | from flask import jsonify
from configuration import Username_Policies
import re
class User(object):
username = None
password = None
session_id = None
def __init__(self,username):
self.username = username
@staticmethod
def validate_username(username):
reason = ""
if l... | true |
230703c680e44ab8d8fe6c9ace647b87f075cdf3 | Python | AlekosIosifidis/detaviz | /Source/visualisation/visualisation_utils.py | UTF-8 | 6,664 | 2.625 | 3 | [] | no_license | import os
import json
import numpy as np
import pandas as pd
from pathlib import Path
def check_flag_value(file, flag):
"""
Check the window flag size
:param file:
:param flag:
:return:
"""
with open(file) as f:
datafile = f.readlines()
for line in datafile:
if flag ... | true |
4ec19945ef8d1566d04a8f98d473646bdf526ab5 | Python | secreter/QA | /online/serverRelT.py | UTF-8 | 466 | 2.53125 | 3 | [] | no_license |
from flask import Flask
from flask import request
import json
f=open(r"./txt/dist/my/relT.txt",'r')
dic=json.load(f)
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
return '<h1>Home</h1>'
@app.route('/relT', methods=['GET'])
def relT():
print(request.args)
rel=request.args.get('re... | true |
9134ab2808f8053a6dbe75e92175ecf324f73f75 | Python | Otetz/any-comment | /app/blueprints/comments/__init__.py | UTF-8 | 8,863 | 2.578125 | 3 | [] | no_license | """Комментарии."""
import datetime
from typing import Dict, Any, List, Optional
import dateutil.parser
import flask
from dateutil.tz import tzlocal
from flask import Blueprint, stream_with_context, Response, redirect, url_for
from app.blueprints.doc import auto
from app.comments import get_comments, get_comment, remo... | true |
ab8df62c765a8a2bf67e88b2d4b1ae14960262e4 | Python | xadupre/xadupre.github.io | /draft/mlprodict/_downloads/b352f437bf7c07763e099b765029f9c0/numpy_api_onnx_ccl.py | UTF-8 | 9,135 | 3.421875 | 3 | [
"Python-2.0",
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# # Introduction to a numpy API for ONNX: CustomClassifier
#
# This notebook shows how to write python classifier using similar functions as numpy offers and get a class which can be inserted into a pipeline and still be converted into ONNX.
# In[1]:
from jyquickhelper... | true |
1458b91a857795aa2cffd7c356ecf8634746b319 | Python | bazhenov4job/client_server | /to_send/client.py | UTF-8 | 3,601 | 2.921875 | 3 | [] | no_license | """
Реализовать простое клиент-серверное взаимодействие по протоколу JIM (JSON instant messaging):
клиент отправляет запрос серверу;
сервер отвечает соответствующим кодом результата. Клиент и сервер должны быть реализованы в виде отдельных скриптов,
содержащих соответствующие функции. Функции клиента: сформировать pres... | true |
a824e7b7c280d80aca7885fe8c1074b80da62886 | Python | umiundlake/links-api | /app.py | UTF-8 | 3,726 | 2.78125 | 3 | [] | no_license | from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from marshmallow import Schema, fields
import os
# This method to get an absolute path of a file works with all the operative systems.
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#DB_URI = "sqlite:///" + os.path.join(BASE_DI... | true |
fe14849dca7379077c4835c53f6fdcd6f35e5ec9 | Python | YoungcsGitHub/PythonHouse | /pyqt5/chapter3/menu_toolbar/Toolbar.py | UTF-8 | 1,911 | 3.015625 | 3 | [] | no_license | # -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: Toolbar
# Description:
# Author: Dell
# Date: 2019/10/6
#-------------------------------------------------------------------------------
'''
创建和使用工具栏
工具栏默认按钮:只显示图标,将文本作为悬停提示
工具栏按... | true |
c5bd0e0534ad73caff3a607af087af2cbc6e7a08 | Python | vlaguillo/M03 | /Ejercicios_python/Ejercico_Hoja_calculo.py/hoja_calculo.py | UTF-8 | 614 | 3.359375 | 3 | [] | no_license | def my_range(inici, fi, increment):
while inici <= fi:
#Retorna l'element actual del rang (llista)
yield inici
inici = inici + increment
for fil in my_range(1,5,1):
for col in my_range(1,4,1):
if (fil==1 and col==2):
print "A",
elif (fil==1 and col==3):
print "B",
elif (fil==1 and col==4):
pri... | true |
785b54164cc535c4d001eaeb6ec0921cb682c734 | Python | MahdiZizou/Hamun-Lake-NLP-project | /NLPproj_task2.py | UTF-8 | 1,410 | 2.875 | 3 | [] | no_license | #region Description: task2
print('you should execute line by line because run does not work on seperate py files')
print('input is: tweets_data')
print('Your querry was:', query)
print('The length of tweet data set is:', len(tweets_data))
###########################################################################... | true |
08201c81fc49686a34012d0d0aa4fd5b16d2a967 | Python | niminjie/iptv | /sim.py | UTF-8 | 8,021 | 2.5625 | 3 | [] | no_license | import cPickle as pickle
import codecs
from math import sqrt
from dfs import find_connection
log = open('sim.log', 'w')
DEBUG = False
def across(interval, time):
if interval[0] <= time < interval[1] or (time == 23 and interval[1] == 23):
return True
else:
return False
def convert_to_hour(time... | true |
2bff24e452881474533b290f156d3c76d7c4aa5f | Python | bagaki/Python | /ginko/my/view.py | UTF-8 | 2,816 | 3.3125 | 3 | [] | no_license | # coding:utf-8
'''
管理员界面
类名: View
属性:账号、密码
行为:管理员初始化界面 管理员登录 系统功能界面 管理员注销
系统功能:开户、查询、取款、存款、转账、改密、销户、退出
'''
from check import Check
import time
class View(object):
def __init__(self, admin, pwd):
self.admin = admin
self.pwd = pwd
def initface(self):
print("-----------------... | true |
673aec45ac2032a0faf6b2653e01f1a88d03318a | Python | ottohahn/data | /gender_model/gender_io_nokey.py | UTF-8 | 850 | 2.953125 | 3 | [] | no_license | # encoding: utf-8
"""
gender_io_nokey.py
"""
import requests
import json
def get_genders(names):
"""Create a call to genderize for up to 10 names in a list."""
url = ""
cnt = 0
if not isinstance(names, list):
names = [names, ]
for name in names:
if url == "":
url = "na... | true |
e8a01d7e5726d4ba84c70b6ba7a190d5867b9e59 | Python | soulgchoi/Algorithm | /Programmers/Level 1/test.py | UTF-8 | 280 | 3.40625 | 3 | [] | no_license | def solution(n):
answer = 0
if n >= 2:
answer += 1
numbers = list(range(3, n + 1, 2))
for number in numbers:
flag = True
for num in range(3, number, 2):
if not number % num:
flag = False
break
if flag:
answer += 1
return answer
n = 5
print(solution(n)) | true |
a5eaa755f7408f30999c36693c8abf599533dc5e | Python | daqingyi770923/SDCFun | /pathPlanClass.py | UTF-8 | 6,857 | 2.953125 | 3 | [
"MIT"
] | permissive |
import math
from enum import Enum
import matplotlib.pyplot as plt
import numpy as np
class RobotType(Enum):
circle = 0
rectangle = 1
class PPClass:
def __init__(self,
max_accel = 2.0,
min_accel = -2.0,
yawRange = 0.5,
max_speed = 2.0,
... | true |
2d7da8478e3b0ae800ca9c0cd0a73a201a3468d8 | Python | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/429c8b675cc147a9a0d0ce2c388eb8b5.py | UTF-8 | 179 | 2.90625 | 3 | [] | no_license | def is_leap_year(year):
byfour = not bool(year % 4)
by100 = not (year % 100)
by400 = not (year % 400)
if(byfour and not by100 or by400):
return True
return False
| true |
40144f7644169908a4cfc5f658bc9787da05d600 | Python | Pookie-Cookie/pongproject2017 | /BetterMovement.py | UTF-8 | 1,147 | 3.328125 | 3 | [] | no_license | from tkinter import *
x = 10
y = 10
width = 100
height = 100
x_vel = 0
y_vel = 0
def move():
global x_vel
global y_vel
if abs(x_vel) + abs(y_vel) > 0:
canvas1.move(rect, x_vel, y_vel)
window.after(16, move)
def on_keypress(event):
print(event.keysym)
global x_vel
global y_vel
... | true |
d24232d27b92fb894aa3c56a329018c386acdd16 | Python | julianofhernandez/ctf | /column_text_format/column.py | UTF-8 | 3,264 | 2.9375 | 3 | [] | no_license | import os
import boto3
from .metadata_conversion_funcs import metadata_types
from .file_management import open_iterator
class Column:
'''
The column object is returned as an iterable for each column that needs to be accessed.
For multiple columns a list of Column objects should be returned.
Attribute... | true |
138daf81911811306ea85035857ce9e7b5d932b0 | Python | CatPhillips103/Recipe-Search | /Recipe.py | UTF-8 | 1,532 | 3.390625 | 3 | [] | no_license | import requests
import hiddenkeys
id = hiddenkeys.app_id
key = hiddenkeys.app_key
def recipe_database(ingredient, health_labels, diet_labels):
url = f'https://api.edamam.com/search?q={ingredient}&app_id={id}&app_key={key}&Health={health_labels}&Diet={diet_labels}'
response = requests.get(url)
found_reci... | true |
9541e980f7d4eeeb7d9d3dbb3d49b4b25fdd3e0f | Python | itrowa/arsenal | /algo-lib/5_string/readdg.py | UTF-8 | 440 | 3.515625 | 4 | [] | no_license | # 用于处理算法一书提供的图
import sys
# 读入V和E
v_cnt = sys.stdin.readline()
e_cnt = sys.stdin.readline()
# 读入剩下的边
raw_edges = [line.split() for line in sys.stdin]
# 把元素从string类型转换为int
for pair in raw_edges:
for i in range(len(pair)):
pair[i] = int(pair[i])
# print
print(v_cnt)
print(e_cnt)
for edge in raw_edges:
... | true |
b7371664e8ace64d63daaa12dbb7710bb9460c4a | Python | Ph0en1xGSeek/ACM | /LeetCode/118.py | UTF-8 | 441 | 2.953125 | 3 | [] | no_license | class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
arr = []
for i in range(numRows):
arr.append([0]*(i+1))
for j in range(i+1):
if j == 0 or j == i:
arr[i]... | true |
4b9d80840d593ef8f6ceeacaa87ce086b66fd51e | Python | devourer3/algorithm_py | /algo_str/algo_3.py | UTF-8 | 1,514 | 3.890625 | 4 | [] | no_license | # 로그파일 재정렬
# 로그를 재정렬하라. 기준은 다음과 같다.
# 1. 로그의 가장 앞 부분은 식별자다
# 2. 문자로 구성된 로그가 숫자 로그보다 앞에 온다.
# 3. 식별자는 순서에 영향을 끼치지 않지만, 문자가 동일할 경우 식별자 순으로 한다.
# 4. 숫자 로그는 입력 순서대로 한다.
# https://leetcode.com/problems/reorder-data-in-log-files
from typing import List
logs = ["dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", ... | true |
87d06cdcb59e41f9aa6d9cf0ed0e74d8ae175fcd | Python | ofl/design-patterns-for-humans-python | /Creational/factory_method.py | UTF-8 | 1,048 | 3.421875 | 3 | [
"CC-BY-4.0"
] | permissive | # Factory Method Pattern
from abc import ABCMeta, abstractmethod
class Interviewer(metaclass=ABCMeta):
@abstractmethod
def ask_questions(self) -> None:
pass
class Developer(Interviewer):
def ask_questions(self) -> None:
print('Asking about design patterns!')
class CommunityExecutive(I... | true |
40bc818a526e5d30d7a0b0303be714ef75644e36 | Python | tboztuna/Hackerrank | /Python/Basic Data Types/Find the Runner-Up Score.py | UTF-8 | 213 | 2.859375 | 3 | [] | no_license | if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
max = max(arr)
arr.sort()
for i in arr:
if i < max:
second_max = i
print second_max
| true |
ebbb31c49c6015c50bfc10b6207a7e82c48c3dd5 | Python | printdoc2020/disinfo | /app.py | UTF-8 | 3,418 | 2.90625 | 3 | [] | no_license | import streamlit as st
import pandas as pd
import json
def get_num_words(text, key_words, return_keys):
count = 0
key_res = []
if (not text) or (not key_words):
return count
text_list = text.split(" ")
for key in key_words:
if key in text_list:
key_res.append(key)
count+=1
continue
if return_keys:... | true |
be44c08833afd8a3739e984b978c4a6a7b3c6d58 | Python | ltrabas/X-Serv-15.8-CmsUsersPut | /cms_users_put/views.py | UTF-8 | 2,251 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | from django.shortcuts import render
from django.http import HttpResponse
from models import Pages
from django.views.decorators.csrf import csrf_exempt
from django.template.loader import get_template
from django.template import Context
# Create your views here.
def mostrar(request):
if request.user.is_authenticated... | true |
fb8014f3411c6ecb5bd3fda6d40dde12bb55738b | Python | rnsdoodi/Programming-CookBook | /Back-End/Python/Basics/Part -4- OOP/07 - Metaprogramming/Attribute-Read-write-Accessor/01_attributeread_accessor.py | UTF-8 | 4,643 | 3.5 | 4 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | class Person:
def __getattr__(self, name):
alt_name = '_' + name
print(f'Could not find {name}, trying {alt_name}...')
try:
return super().__getattribute__(alt_name)
except AttributeError:
raise AttributeError(f'Could not find {name} or {alt_name}')
p = Pers... | true |
183a9931d98b484d49e4c4f3621ac17a9d452452 | Python | signorcampana/Viking-Saga-Quest | /enemys.py | UTF-8 | 1,661 | 3.875 | 4 | [] | no_license | import random
ENEMY_NAMES = (
"Minotaur",
"Hydra",
"Griffin",
)
class Enemy:
name = None
hp = 100
maxHp = 100
stat_defense = 0
stat_attack = 0
level = 1
isPlayer = False
weapon = None
def __init__(self, level, weapon):
self.name = random.choice(ENEMY_NAMES)
self.weapon = weapon
self.level = l... | true |
b48c133014e4e6a7f28faee7495763088d20f4ad | Python | sarvaaurimas/part_1A_floodwarning_system | /Task2B.py | UTF-8 | 567 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 10 19:40:44 2017
@author: samue
"""
from floodsystem.stationdata import build_station_list ,update_water_levels
from floodsystem.flood import stations_level_over_threshold
def run():
""" Requirement for Task 2B"""
stations = build_station_list()
update_wa... | true |
89cb63d9581a90dc7cd27a431e7d1ac8d00d5fc5 | Python | asherif844/100DaysOfCode | /searchApp/program.py | UTF-8 | 917 | 3.53125 | 4 | [] | no_license | import os
def main():
print_header()
folder = get_folder_from_user()
if not folder:
print("Sorry, we can't search this folder")
text = get_search_text_from_user()
if not text:
print("Sorry, can't search for nothing")
search_folders(folder, text)
def print_header():
pri... | true |