blob_id large_string | language 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fc4c24c5b253e24fae30c74cadee920778b0e682 | Python | drakovych/Python3 | /HomeWork_Task_1.py | UTF-8 | 168 | 3.140625 | 3 | [] | no_license | lst = [1, [2, 3], 4, [[6, 7]]]
lst_new = lst[0:1] + lst[1][0:1] + lst[1][1:2] + \
lst[2:3] + lst[3][0][0:1] + lst[3][0][:2]
print(lst)
print(lst_new)
input()
| true |
7d909fc39d605bff07ec93461a0c428ba8c306eb | Python | Lucine84/web-scraping-challenge | /scrape_mars.py | UTF-8 | 3,502 | 2.671875 | 3 | [] | no_license | from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
import pandas as pd
import requests
import os
# https://splinter.readthedocs.io/en/latest/drivers/chrome.html
# get_ipython().system('which chromedriver')
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
... | true |
cb4f79deb7a00fb28038ab16dcd5b40e65f2933b | Python | agapow/relais.dev | /relais/dev/errors.py | UTF-8 | 649 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Common exception types.
"""
# NOTE: 20071125 tested and passed.
__docformat__ = 'restructuredtext en'
### IMPORTS ###
import exceptions
## CONSTANTS & DEFINES: ###
### IMPLEMENTATION ###
class FormatError (exceptions.Exception):
# TODO: needs file and line argu... | true |
4bdc02d93bc2c17603aec44f5b4a81948c5b9870 | Python | ABRG-Models/OMM_NeuroMuscular | /Model2/gauss_conn.py | UTF-8 | 513 | 2.5625 | 3 | [] | no_license |
#PARNAME=sigma #LOC=1,1
#HASWEIGHT
def connectionFunc(srclocs,dstlocs,sigma):
import math
normterm = 1/(sigma*math.sqrt(2*math.pi))
i = 0
out = []
for srcloc in srclocs:
j = 0
for dstloc in dstlocs:
dist = math.sqrt(math.pow((srcloc[0] - dstloc[0]),2) + math.pow((srcloc[1] - dstloc[1]),2) + math.pow((... | true |
7136fa2a70f57d893b5ac9454e38d0703161a79a | Python | jordanbsandoval/python3_al-descubierto | /capituloDos/number/function-int.py | UTF-8 | 159 | 3.53125 | 4 | [] | no_license | #!/usr/bin/python3
""" function str(): convierte un numero en string """
mess = "hola que edad tiene: "
num = 27
res = mess + str(num)
print("{}".format(res))
| true |
e0de7a4eaa7a53e6d11ed17d0d060e14b466dd8d | Python | thammegowda/mt-box | /src/other/oromo_norm.py | UTF-8 | 2,979 | 3.53125 | 4 | [] | no_license | #!/usr/bin/env python3
"""
Normalizes spellings of words of non-english languages that use latin script.
author: Thamme Gowda
version: 0.1
date: August 21, 2017
"""
import sys
from argparse import ArgumentParser
import codecs
import re
alphabet = 'abcdefghijklmnopqrstuvwxyz'
patterns = [r"([{0}{1}])[{0}{1}]+" .form... | true |
d5ca8b5527127bf377b3cac913b13b33e09b8a3a | Python | thedarkknight513v2/daohoangnam-codes | /Daily studies/29_May_18/1st_application.py | UTF-8 | 242 | 3.28125 | 3 | [] | no_license | print("This is a simple Python application")
print("This is a really long line of text that will "+
"appear on multiple line in the source code file")
# This is my comment on the code
"""
Application number: 1st
"""
# comment on the code | true |
8f0617a9b014298bf2608ca31c30c2037194a9a0 | Python | wsgan001/PyFPattern | /Data Set/bug-fixing-5/990f663bb82f4f63ffee575e49cc1460bd7f8d6e-<test_unary_func>-fix.py | UTF-8 | 477 | 2.703125 | 3 | [] | no_license | def test_unary_func():
x = nd.uniform(shape=(4, 5))
f_exp = (lambda x: nd.exp(x))
f_exp_grad = (lambda x: [nd.exp(x)])
autograd_assert(x, func=f_exp, grad_func=f_exp_grad)
f_half = (lambda x: (x / 2))
f_half_grad = (lambda x: [(nd.ones(x.shape) * 0.5)])
autograd_assert(x, func=f_half, grad_f... | true |
391372115a045c9c4fe8416e865d543bb31dbf10 | Python | gtokusum/CSCI-C200-Fall-2020 | /Laboratory/Lab8/filing.py | UTF-8 | 3,268 | 3.953125 | 4 | [] | no_license | import os
def getCurrentDirectory():
"""
This uses a command built into the python module `os`
that shows the current working directory.
Returns:
A string that shows the current working directory
(Where the program is being executed at)
"""
return os.getcwd()
def ourPrint(... | true |
a6287d4852bf90a191237223f5d53e628639f828 | Python | mallory-jpg/bank | /bank_ops.py | UTF-8 | 1,766 | 3.46875 | 3 | [] | no_license | """Bank User operations: new account, check balance, transfer $, deposit, withdraw"""
from bank_customers import USER_INFO
from bank_admin import Admin
import random
import threading
import logging
bal_lock = threading.Lock()
class BankAccount(Admin):
def __init__(self, balance=0, account_id=[]):
self.b... | true |
3c5e644792aa5bb1aa8db57acc3cbc10dbc19f73 | Python | devconsoft/pycred | /pycred/test/test_config.py | UTF-8 | 7,102 | 2.515625 | 3 | [
"MIT"
] | permissive | import unittest
from io import StringIO
from textwrap import dedent
from unittest.mock import MagicMock, mock_open, patch
from ..config import DEFAULT_PYCRED_CONFIG, BackendConfig, ConfigurationManager, \
PyCredBackendDefaultConfig, PyCredConfig, StoreConfig
class TestPyCredBackendDefaultConfig(unittest.TestCase... | true |
5857ffe7fafdb47a332fc7f9319db4ea73bd605d | Python | Ace314159/AoC-2018 | /Day 11_2.py | UTF-8 | 1,100 | 3.0625 | 3 | [] | no_license | import pathlib
import itertools
import collections
serialNumber = int(pathlib.Path("inputs/11.txt").read_text().splitlines()[0])
summedAreaTable = collections.defaultdict(int)
for x, y in itertools.product(range(1, 300 + 1), range(1, 300 + 1)):
rackID = x + 10
powerLevel = rackID * y
powerLevel += serialN... | true |
9b4ee0e6c70dcecbad40938c53a81961835093fb | Python | nikon-petr/kohonen | /core/net_loader.py | UTF-8 | 1,130 | 2.515625 | 3 | [
"MIT"
] | permissive | import os
from json import JSONDecodeError, dump
from json import load
import numpy as np
from core.net_errors import JsonFileNotFound, JsonFileStructureIncorrect
def upload(net_object, path):
if not os.path.isfile(path):
raise JsonFileNotFound()
try:
with open(path, 'r') as file:
... | true |
54dae27de4bab601e759bf242869530d1bf27324 | Python | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2019/Horacio Góngora/Practica 1/6-4 a 6-6.py | UTF-8 | 3,274 | 4.53125 | 5 | [
"MIT"
] | permissive | '''Try It Yourself'''
'''6-4. Glossary 2: Now that you know how to loop through a dictionary, clean
up the code from Exercise 6-3 (page 102) by replacing your series of print
statements with a loop that runs through the dictionary’s keys and values.
When you’re sure that your loop works, add five more Python terms to y... | true |
50c2bf6b3880798395650ec8e844574d01b006fd | Python | msbentley/midas | /midas/dust/fulle_flux.py | UTF-8 | 19,826 | 2.984375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#!/usr/bin/python
"""
fulle_flux.py - provides interpolated values of dust flux as a function of
cometocentric and helicentric distance. All values are interpolated from
Fulle (2010).
"""
import fulle_data as data
from dustutils import *
import matplotlib.pyplot as plt
import numpy as np
import... | true |
099ea904ed7a75a52e04a1a0acb9b9ea288ec447 | Python | Sinscerly/ProjectRobo-4onarow | /VisionCode/parts/detectcircles.py | UTF-8 | 3,911 | 3.34375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
'''
This example illustrates how to use cv.HoughCircles() function.
Usage:
houghcircles.py [<image_name>]
image argument defaults to ../data/board.jpg
'''
# Python 2/3 compatibility
from __future__ import print_function
import cv2 as cv
import numpy as np
import sys
def main():
print(... | true |
2e38bbd0937f98f1c30fdcded9a89ceb7003c3d2 | Python | imshile/Python_Regex_Engine | /Python_Regular_Expressions_Back_References.py | WINDOWS-1250 | 2,200 | 4.46875 | 4 | [] | no_license | # Python Regular Expressions.
# Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python
# and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you ... | true |
977ede3e24c9091a3e540f189b724861ba651f09 | Python | dev-everaldo-cyrino/exercicios-de-raciocinio-4 | /main.py | UTF-8 | 445 | 3.234375 | 3 | [
"MIT"
] | permissive | from classe import gato
gato.inicio(gato)
while True:
print('''
---painel de escolhas---
1- alimentar
2- brincar
3- dormir
4- status
5- sair''')
op = int(input('opção: '))
if op ==5:
break
if op ==1:
gato.alimentar(gato)
... | true |
c46071c4aa8cd3cedf9965491c78ededfa55fe65 | Python | voytekresearch/project_pac | /distinguish_pac/base_workflow_foofpacbycycle_epochs.py | UTF-8 | 7,263 | 2.640625 | 3 | [] | no_license | #%% Import standard libraries
import os
import numpy as np
#%% Import Voytek Lab libraries
#%% Change directory to import necessary modules
os.chdir(r'C:\Users\jaapv\Desktop\master\VoytekLab\Code\distinguish_pac')
#%% import self-defined modules
import module_load_data as load_data
import module_pac_functions a... | true |
2024b7dcdbb494495fe904dcde799597d788ffe9 | Python | hasan356/asu-hacktoberfest2017 | /sorting/selection.py | UTF-8 | 474 | 3.8125 | 4 | [] | no_license | def selection(numbers):
# Traverse through the array
for i in range(len(numbers)):
# Find the index of the minimum element in remaining sorted array
min_index = i
for j in range(i+1, len(numbers)):
if numbers[min_index] > numbers[j]:
min_index = j
# Swap ... | true |
8deb2070fda04f24001f67134e95c2b2eee332c6 | Python | Minolyx/Modulhandbuch | /app/database.py | UTF-8 | 11,718 | 2.8125 | 3 | [] | no_license | # coding: utf-8
import json
from operator import itemgetter
class Database(object):
modulFile = "./data/modul.json"
studiengangFile = "./data/studiengang.json"
benutzerFile = "./data/benutzer.json"
def getUser(self):
benutzer = {}
data = Database.readFile(self.benutzerFile)
... | true |
bc22548185952c00987c7d57382afeeb5cfa3625 | Python | cmattoon/mbta-pi | /list_vehicles.py | UTF-8 | 678 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
from mbtapi.client import Vehicle, Stop
from mbtapi.model import VehicleModel
from mbtapi.util import ptable
stops = {stop.id: stop for stop in Stop.getAll()}
def print_vehicle_status():
tbl_data = []
for vehicle in Vehicle.getAll():
if vehicle.isSubway():
tbl_data.ap... | true |
dda9852b14ed9a8ae079d09812bb5dffdc49a4d5 | Python | MaxwellMasaitis/SKELTER | /main.py | UTF-8 | 1,891 | 3.1875 | 3 | [] | no_license | import pygame
import os
from modules.vector2D import Vector2
from modules.drawable import Drawable
from modules.gameManagerThreaded import GameManagerThreaded
SCREEN_SIZE = Vector2(400, 400)
SCALE = 2
UPSCALED_SCREEN_SIZE = Vector2(*[x * SCALE for x in SCREEN_SIZE])
def main():
# initialize the pygame module
... | true |
d5f7b0a6c87b804d9add07365db3acff8fe1df0d | Python | snrao310/Video-Feature-Extraction | /Code/Video_Feature_Extraction/t1d/__init__.py | UTF-8 | 2,827 | 2.671875 | 3 | [] | no_license | from __future__ import division
# define imports
import numpy as np
import cv2
import os
import math
sqrt_2_by_2 = math.sqrt(2) / 2
def get_y_component(frame_count):
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count)
success, image = cap.read()
if image is not None:
height, width, channel = image.sh... | true |
48b33906cddcef6fb64161cba8f0f9dfbb1d1abb | Python | sonalpriyanshi529/GUI-Projects | /GUI_Projects/f. Stone Paper Scissor.py | UTF-8 | 9,549 | 2.96875 | 3 | [] | no_license | # from playsound import playsound
from tkinter import *
import random
win = Tk()
win.title('Stone Paper Scissor Game')
win.geometry('530x500')
scores = 0
comp_scores = 0
value = ['👊', '📄', '✂']
# comp = random.choice(value)
Label(text='', font=('Arial bold', 100)).grid(column=0, row=1, ipadx=80)
... | true |
4dd7b68d3ceb415bc3829aee7a650b928e290519 | Python | luodichen/leetcode-solution | /accepted/84-largest-rectangle-in-histogram.py | UTF-8 | 865 | 3.25 | 3 | [] | no_license | # https://leetcode.com/problems/largest-rectangle-in-histogram/
class Solution:
# @param {integer[]} height
# @return {integer}
def largestRectangleArea(self, height):
best = 0
stack = []
for h in height:
if len(stack) == 0 or h >= stack[len(stack) - 1][1]:
... | true |
8bb64e0f34d7c431f8b895b14ddb60831caf8883 | Python | d42knight/chem160homework5 | /hyperc_np.py | UTF-8 | 430 | 2.71875 | 3 | [] | no_license | import math, time, random
import numpy as np
ntrials=10000000
dist=0
t=time.process_time()
x1=np.random.random(ntrials)
y1=np.random.random(ntrials)
x2=np.random.random(ntrials)
y2=np.random.random(ntrials)
dist=np.mean(np.sqrt((x1-x2)**2+(y1-y2)**2))
et=time.process_time()-t
ex_dist=1/15*(math.sqrt(2)+2+5*math.log(1... | true |
f235c197ec6a93054944cc1b796166765691a68b | Python | DuyKhangTruong/Algorithm | /TopologicalSort.py | UTF-8 | 981 | 3.8125 | 4 | [] | no_license | from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.Vertex = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def Topological_Sort(self):
linear_order = []
in_degree = [0]*self.Vertex
nex... | true |
8e63316e92985c4b390459b7b3b79bd847202bb9 | Python | biiabauer/Av3 | /back-end/modelo.py | UTF-8 | 1,534 | 3.140625 | 3 | [] | no_license | from config import *
class Livro(db.Model):
# atributos do livro
nome = db.Column(db.String(254), primary_key=True)
autor = db.Column(db.String(254))
ano = db.Column(db.String(254))
# método para expressar o livro em forma de texto
def __str__(self):
return f'''
- Cadei... | true |
eb283fcfd391d739821bc072e828dc9d6b629a99 | Python | ceceher/Analisis-multivariado | /Scripts/Python/meanshift.py | UTF-8 | 1,147 | 2.859375 | 3 | [
"MIT"
] | permissive | from numpy.core.fromnumeric import mean
import pandas as pd
from sklearn.cluster import MeanShift
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
dataset = pd.read_csv(".\data\candy.csv")
print(dataset.head(5))
X = dataset.drop('competito... | true |
234c048c1f75839d629410fc717862d2ca72cf4f | Python | MatthijsBiondina/TimeContrastiveNetworks | /Models/src/plot/cv_plot.py | UTF-8 | 1,729 | 2.828125 | 3 | [] | no_license | import cv2
from matplotlib import pyplot as plt
import numpy as np
class CVPlot:
def __init__(self,
minx=-1.5, maxx=1.5, miny=-1.5, maxy=1.5,
cmap='gist_rainbow'):
self.minx, self.maxx = minx, maxx
self.miny, self.maxy = miny, maxy
self.canvas_size = (240,... | true |
7347293a92e4b57b26be09112abb38f1bc9931c7 | Python | shmilycowboy/mypy | /fibonacci_2.py | UTF-8 | 138 | 3.046875 | 3 | [] | no_license | s_month=int(input('input month:'))
a_list=[1,1]
for month in range(s_month-2):
a_list.append(a_list[-1]+a_list[-2])
print(a_list[-1])
| true |
0841afd518b24624cd475eb9657008d59b6bbdc8 | Python | aguycalled/ledger-app-nav | /tests/helpers/deviceappproxy.py | UTF-8 | 5,297 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | from typing import Optional, List
from .apduabstract import BytesOrStr
from ledgerblue.comm import getDongle, CommException
#decorator that try to connect to a physical dongle before executing a method
def dongle_connected(func: callable) -> callable:
def wrapper(self, *args, **kwargs):
if not hasattr(sel... | true |
377e9e1d96a4fce622f244265a6d860d1ef80386 | Python | Lindeby/toric-RL-decoder | /tests/roll_numba.py | UTF-8 | 1,414 | 3.15625 | 3 | [
"MIT"
] | permissive | import numpy as np
import time
from numba import njit
@njit
def roll2dAxis0(matrix, n):
result = np.empty(matrix.shape)
for col in range(matrix.shape[1]):
result[:,col] = np.roll(matrix[:,col], n)
return result.astype(matrix.dtype)
@njit
def roll2dAxis1(matrix, n):
result = np.empty(matrix.s... | true |
37867a3736ce7787d219261e83e7b1813c512ce1 | Python | TobiasNorlund/Exjobb | /parse_corpus.py | UTF-8 | 2,895 | 3.109375 | 3 | [] | no_license |
# Parses a corpus to for each word output a matrix of size (2k) x d, where k is the half context window size and d is
# the dimensionality of the index vectors
from Dictionary import Dictionary
from OneBCorpus import OneBCorpus
from scipy.sparse import csr_matrix
import numpy as np
import random
import numpy.random a... | true |
0205278c9651eacae1a8a1fe345f6a804376ab0e | Python | peetck/opencv-playground | /simple thresholding/main.py | UTF-8 | 1,103 | 3.375 | 3 | [] | no_license | import cv2
import numpy as np
from matplotlib import pyplot as plot
def thresholding_example(): # Thresholding is the simplest method of segmenting image from a grayscale image.
""" thresholding_example function """
img = cv2.imread("threshold.jpg") # read threshold.jpg
_, th1 = cv2.threshold(img, 120, 25... | true |
33b5461d5b47315aec1de9fe059339d253b919e4 | Python | Jeffery12138/Python- | /项目1 外星人入侵/第13章 外星人/动手试一试/13-2 更逼真的星星/run_game.py | UTF-8 | 638 | 2.859375 | 3 | [] | no_license | import pygame
from pygame.sprite import Group
from settings import Settings
import game_functions as gf
def run_game():
# 初始化游戏并创建一个屏幕对象
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("STAR ... | true |
04359403ccbf56c4fbad40b609e438fcc3354f4f | Python | yoderw/math121 | /hw/hw1/hw1_distance.py | UTF-8 | 316 | 3.765625 | 4 | [] | no_license | location_x = float(input("Location x-coordinate? "))
location_y = float(input("Location y-coordinate? "))
class_x = float(input("Classroom x-coordinate? "))
class_y = float(input("Classroom y-coordinate? "))
x = class_x - location_x
y = class_y - location_y
distance = ((x ** 2) + (y ** 2)) ** 0.5
print(distance) | true |
8d06a46786d9cd48d7f7cec8c70bebc8c5806dab | Python | twydev/Challenges-and-Interviews | /aoc2018/day7.py | UTF-8 | 2,645 | 3 | 3 | [] | no_license | # for linux
# scriptname_list = __file__.split("/")
# filename = scriptname_list[-1].split(".")[0] + ".txt"
# scriptname_list[-1] = "inputs/" + filename
# full_filename = "/".join(scriptname_list)
# print(full_filename)
# for windows
scriptname_list = __file__.split("\\")
filename = scriptname_list[-1].split(".")[0] +... | true |
ff05855e60962ec6beb4c190add731657a714975 | Python | KilburnBuilding/Leetcode | /647.py | UTF-8 | 982 | 3.453125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
record = [[0 for i in range(length)] for j in range(length)]
for i in range(length):
record[i][i] = 1
... | true |
d918aea657ac5a42fc3964e0957555cf78b72da5 | Python | Anne-Aimee/recommender_system | /utilities/helpers.py | UTF-8 | 9,340 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""some helper functions """
import csv
import numpy as np
import scipy.sparse as sp
from math import sqrt
def create_csv_submission(ids, pred, name):
"""
Creates an output file in csv format for submission to kaggle
Arguments: ids (event ids associated with each rating prediction ... | true |
c3722a1bf5a089f075ac4d45fe1d521af5ba54e9 | Python | dimoynwa/NLPTasks | /preprocess.py | UTF-8 | 3,141 | 2.828125 | 3 | [] | no_license | import numpy as np
import pandas as pd
import tensorflow as tf
EMBEDDING_DIM = 100
EMBEDDINGS_FILE_PATH = './embeddings/glove/glove.6B.%sd.txt' % EMBEDDING_DIM
TRAIN_DATA_FILE = './data/jigsaw-toxic-comment-classification-challenge/train.csv'
MAX_VOCAB_SIZE = 20000
"""Loading pre-trained embeddings"""
def load_embed... | true |
7170936dc47ba26a54a285a92daaaa8145c1c3b9 | Python | djohnsonbaugh/DWPSA | /DWPSA/TestEMSCSVFormat/TestNodeCSVStream.py | UTF-8 | 914 | 2.71875 | 3 | [] | no_license | import unittest
import io
import os
from EMSCSVFormat.NodeCSVStream import NodeCSVStream
class TestNodeCSVStream(unittest.TestCase):
def test_DataConversion(self):
testfilename = "testNodefilestream.csv"
stationname = "s"
nodename = "n"
companyname = "c"
voltage = "121"
... | true |
4bccfd5678b2949a958ebc3bcfd74e9fa44aca29 | Python | Twizwei/maskrcnn_detector | /Bbox_3d/estimate_3d_bbox_v2.py | UTF-8 | 4,837 | 2.828125 | 3 | [
"MIT"
] | permissive | import torch
import numpy as np
def dimensions_to_corners(dimensions):
"""
Note that the center of the 3D bounding box is the center of the bottom surface,
not the geometric center of the box, following KITTI's defination.
"""
h, w, l = dimensions[:, 0], dimensions[:, 1], dimensions[:, 2]
zero... | true |
405a564fa8806f42c811a8be66324fed65d2dd7d | Python | lewis841214/styleMuseGAN2 | /down_sampling.py | UTF-8 | 8,486 | 2.515625 | 3 | [] | no_license | import numpy as np
from pypianoroll import Multitrack, Track
from multiprocessing import Pool, cpu_count
import queue
#from matplotlib import pyplot as plt
#import tensorflow as tf
import os
from multiprocessing import Process
import os
import time
i=0
k=0
c=20016
batch_size=500
#print (os.getcwd())
#print(os.getcwd())... | true |
cc81dfd4db9a7dbbdbe80b0d53118aff60b25faa | Python | uchenna-j-edeh/dailly_problems | /ik_patterns/recursion_pattern/permutation_dups.py | UTF-8 | 1,373 | 3.640625 | 4 | [] | no_license | """47. Permutations II
Medium
6.9K
125
company
Amazon
company
Microsoft
company
LinkedIn
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
O... | true |
4cbd81ca0fd7ee16064e9d4f85c6c3bdd80f8ac7 | Python | totolo/Machine-Learning-101 | /simple linear regression/simple_linear_regression_data_sanitization.py | UTF-8 | 1,228 | 3.265625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 10:00:04 2018
@author: nenshu
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('revenue_rdexpense_need-sanitization.csv')
# Sanitize the data
colu... | true |
756daa28dcceb44e9fff407e58e8c726246c34bc | Python | Kuldeep-kd/Python-Projects | /Image Processing/Image_MOG_Background_Reduction.py | UTF-8 | 465 | 2.59375 | 3 | [] | no_license | import cv2
import numpy as np
cp = cv2.VideoCapture("Assets/FacesVideo.mp4")
bg_sub = cv2.createBackgroundSubtractorMOG2()
while 1:
_, frame = cp.read()
mask = bg_sub.apply(frame)
#cv2.imshow("cp",frame)
frame = cv2.resize(frame, (700,500), cv2.INTER_CUBIC)
mask = cv2.resize(mask, (700,500), cv2.INTER_CUBIC)
... | true |
c527ef71342be2fcb319e373b5ea747606c36965 | Python | huzaifabaloch/Python_Crash_Book_Exercises | /Chap_5 - If Statements/5_3_alien_colors_1.py | UTF-8 | 93 | 3.265625 | 3 | [] | no_license | alien_color = 'green'
if alien_color == 'green':
print("The player just earned 5 points.")
| true |
e48e3cf575f048c9a3b405257da4ca6272f967a4 | Python | GonMazzini/MachineLearning_DTU | /ex7_2_1.py | UTF-8 | 1,354 | 2.640625 | 3 | [] | no_license | from matplotlib.pyplot import figure, plot, xlabel, ylabel, show
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn import model_selection
import sklearn.tree
import scipy.stats
import numpy as np, scipy.stats as st
# requires data from exercise 1.5.1
from ex5_1_5 import *
X... | true |
eb45132df8ea8ce66543f817b047de48cf4015a0 | Python | usman-tahir/python-snippets | /coding-bat/logic-1/squirrel_play.py | UTF-8 | 447 | 3.9375 | 4 | [] | no_license | # The squirrels in Palo Alto spend most of the day playing. In particular, they
# play if the temperature is between 60 and 90 (inclusive). Unless it is summer,
# then the upper limit is 100 instead of 90. Given an int temperature and a
# boolean is_summer, return True if the squirrels play and False otherwise.
def sq... | true |
54571b76ff163bd7ab6805a6fa4c35af9d2881f9 | Python | schneider-simon/pydriller-vs-gitpython | /pydriller_tasks.py | UTF-8 | 1,287 | 2.8125 | 3 | [] | no_license | from pydriller import RepositoryMining
def pydriller_task1(path):
java_commits = []
commit_counter = 0
mine = RepositoryMining(path)
# How can I get the total amount of commits before traverse?
for commit in mine.traverse_commits():
commit_counter += 1
java_paths = [m.filename for ... | true |
db3dd877e1ef7e8eff7878beabaedb53fa26d8ce | Python | samansafiaghdam/python-class | /EX10-FASELE 2.py | UTF-8 | 280 | 3.296875 | 3 | [] | no_license | from math import sqrt
def fasele(p1,p2):
return sqrt(((p1.x)-(p2.x))**2+((p1.y)-(p2.y))**2)
class coordinate:
x=0
y=0
p1=coordinate()
p2=coordinate()
p1.x=int(input())
p2.x=int(input())
p1.y=int(input())
p2.y=int(input())
a=fasele(p1,p2)
print(a)
| true |
c90e0d566529cc9b90e1f3f7409c9c283b372edf | Python | maxkvant/NgsHW | /hw5_ouput/runner_assemble.py | UTF-8 | 3,101 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python3.5
import subprocess
import os
class Dataset:
def __init__(self, name, reads, long_reads, reference):
self.name = str(name)
self.reads_1, self.reads_2 = reads
self.long_reads = long_reads
self.reference = reference
def __str__(self):
return str((self... | true |
5ccee82415d2bb69a13b01fe1417fa56e33b6eb9 | Python | MichalMaciszka/si_proj | /scrapping.py | UTF-8 | 3,328 | 2.984375 | 3 | [] | no_license | import requests
import os
from tqdm import tqdm
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin, urlparse
import string
# only really used function from this file, less is irrelevant while we have access to Allegro API
def create_words_vector(all_texts):
tmp = []
words = []
for item i... | true |
197fb0c708a906071629d2d18d7b4e966f78d1a9 | Python | lickakafirst/lichao | /bigfile.py | UTF-8 | 732 | 3.265625 | 3 | [] | no_license | #!/usr/bin/python
#coding=utf-8
import os
import operator
import sys
def get_filesize(topdir):
dic = {} #定义字典,key = filename,value = filesize
a = os.walk(topdir) # 记住os.walk,目录遍历
for fpath, fdir, fname in a:
for i in fname:
fn = os.path.join(fpath, i)
f_size = os.path.getsize(fn) #得到fi... | true |
4ea223065a9b0f4b59ef069856612d2958ad9645 | Python | tommylees112/ukpopulation | /tests/setup_test_data.py | UTF-8 | 1,608 | 2.640625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
"""
create a small subset of real data for testing - 3 LADs per country and years up to 2027
test data is under source control - this script only required if the data format changes
NOTE: ensure NOMIS_API_KEY=DUMMY in order to match the cached filenames for England
"""
import pandas as pd
real... | true |
af2c229cd29579c257e856ae1b83fe7b44eb2ebb | Python | jonathanmishler/rab | /rab/utilities.py | UTF-8 | 1,735 | 3.265625 | 3 | [] | no_license | import datetime
import pandas as pd
def customer_column_map(customer_type: str) -> dict:
""" Renames the columns for the owner or operator info so they are easier to map to the html template """
info_columns = ["customer_name", "tax_id", "tax_id_type", "tax_id_print", "other"]
column_map = {
c[1]:... | true |
0e22fae526ad6147f1a7de212cd4466fd7c49bd4 | Python | evanptang/advent-of-code-2020 | /day_8/p2.py | UTF-8 | 4,437 | 3.109375 | 3 | [] | no_license | import json
import copy
# file_name = 'parsed_sample.txt'
file_name = 'parsed_input.txt'
file_name = 'parsed_testing.txt'
with open(file_name) as f:
input_obj = json.load(f)
def replace_one_operation(input_object):
"""
iteratively replaces one operation
"""
current_index = 0
intro = copy.... | true |
4c6f2c83990a16b2317c50318e666e3fe78b405f | Python | bishos123/Teste-Pratico_1 | /scratch_3.py | UTF-8 | 2,871 | 2.828125 | 3 | [] | no_license |
import sys
import pickle
#ALL_JOGO = [0, 1]
infile = open('ALL_JOGO.txt', 'rb')
NEW_ALL_JOGO = pickle.load(infile)
ALL_JOGO = NEW_ALL_JOGO
#ALL_PLACAR = [0, 12]
infile2 = open('ALL_PLACAR.txt', 'rb')
NEW_ALL_PLACAR = pickle.load(infile2)
ALL_PLACAR = NEW_ALL_PLACAR
#MIN_TEMP = 0
infile3 = open('MIN_TEMP.tx... | true |
95e2321a17f444adb60bd807b08bfb441bd610b8 | Python | ddmin/CodeSnippets | /PY/Bots/5-Minutes-Leung/5-minutes-leung-bot.py | UTF-8 | 586 | 2.6875 | 3 | [] | no_license | import discord
from discord.ext import commands
import re
TOKEN = 'NTAwMTQ3NjYzNTQ3NzkzNDA4.DqGmpw.WICruk1d4p9__fw36FJN5hNerVw'
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print('Jonnyboi is online.')
@client.event
async def on_message(message):
channel = me... | true |
4cfe103502b80008ac78830f1f12e24c942b5724 | Python | psyourluck/PDE_trial_lab | /PDE_inital/Advection_Eqn_Finite_Difference_solver/BW_solver.py | UTF-8 | 7,829 | 3.1875 | 3 | [] | no_license | """
This code solves the Advection equation
U_t + aU_x = 0
using Beam-warming (BW) scheme
"""
import numpy as np
import matplotlib.pyplot as plt
class beamWarming:
def __init__(self, N, tmax, dt, prb, yinf=0, ysup=1, dynamic=True, xmin=0, exact=True):
self.N = N # number of nodes
self.tmax ... | true |
7d7ea5f7826c7e821508cf08a6686427de0b0c48 | Python | furuiqi/DesignPatterns | /part4/demo02.py | UTF-8 | 879 | 4.03125 | 4 | [] | no_license | #桥模式
from abc import ABCMeta, abstractmethod
class Shape(metaclass=ABCMeta):
def __init__(self, color):
self.color = color
@abstractmethod
def draw(self):
pass
@abstractmethod
def _name(self):
pass
class Color(metaclass=ABCMeta):
@abstractmethod
def paint(self,... | true |
91ea93fe3d4894fd47dab987f37687dee1c01f9b | Python | SunMig/K-Means | /kMeans.py | UTF-8 | 4,867 | 3.09375 | 3 | [] | no_license | from numpy import *
# 导入数据函数
def loadDataSet(filename):
dataMat = []
fr = open(filename)
for line in fr.readlines():
curLine = line.strip().split('\t')
# fltLine=list(map(float,curLine))
fltLine = [float(i) for i in curLine]
dataMat.append(fltLine)
return dataMat
# 欧拉... | true |
7afccc9004b4de7271025875d8e7c6d6b51786a0 | Python | phyllsmoyo/Python | /rest-api/rest_api.py | UTF-8 | 368 | 2.953125 | 3 | [] | no_license | import requests
import json
response = requests.get(
"https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow"
)
for question in response.json()["items"]:
if question["answer_count"] == 0:
print(f'Title: {question["title"]}')
print(f'Link: {question["link"]}')
... | true |
9db5414e1490ebcde2ed055f8c6e6164a97e8d2c | Python | rafaelperazzo/programacao-web | /moodledata/vpl_data/182/usersdata/269/113295/submittedfiles/diagonaldominante.py | UTF-8 | 454 | 3.390625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
n=int(input('digite a quantidade de linhas e colunas: '))
m=n
a=np.zeros((n,m))
for i in range(0,n,1):
for j in range(0,m,1):
a[i,j]= float(input('digite os elementos: '))
soma=0
cont=o
for i in range(0,n,1):
for j in range(0,m,1):
soma=so... | true |
5c97a72881071e87b1a3c6dec42d523d6f034de8 | Python | sopanshewale/python-datascience | /batch_four/session-5/bmi_numpy.py | UTF-8 | 546 | 3.046875 | 3 | [] | no_license | #!/usr/bin/python3
import numpy as np
# height in inches, weight in pounds
height = [76.77, 70.86, 72.83, 70.07, 75.98, 70.07, 70.01, 70.8]
weight = [209.439, 167.551, 182.984, 165.347, 216.053, 163.142, 176.37, 191.802]
np_height = np.array(height)
np_weight = np.array(weight)
np_height_meters = np_heigh... | true |
9c96d7e38664ac1822b2d675fa932b906e356bf0 | Python | alucas2/the-python-experience | /trieur/radix.py | UTF-8 | 1,000 | 3.484375 | 3 | [] | no_license | #tri par base
def maxValue(array):
resultat = 0
for i in range(array.size):
v = array[i].getValue()
if v > resultat:
resultat = v
return resultat
def radix_countingSort(array, base, power):
resultat = array.size * [0]
offsets = base * [0]
for i in range(array.... | true |
5ef8d2de577f316bf05de342e2f1ade69e9d536d | Python | sakayaparp/CodeChef | /Contests/Strong Language (SSCRIPT)/SSCRIPT.py | UTF-8 | 598 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | # cook your dish here
# to run test cases
def TEST_FUNCTION():
N, K = map(int, input().split())
string = input()
check = 0
count = 0
for i in range(N):
if count != K:
if string[i] == '*': # check for '*'
count = count + 1
else:
... | true |
41d84e3222e37c61bcd894abd6e9ffe19b36c09b | Python | to-besomeone/algorithm | /181105-2445.py | UTF-8 | 411 | 3.265625 | 3 | [] | no_license | N = int(input())
for i in range(N):
for j in range(i+1):
print("*", end='')
for k in range(2*N-2*i-2):
print(" ", end='')
for m in range(i+1):
print("*", end='')
print("")
for i in range(N):
for j in range(N-i-1):
print("*", end='')
for k in range(2*(i+1)):
... | true |
c8d6fecdfc5ebc878702774bbaa60667963745cd | Python | ztbartolome/Mad_Libs_Generator | /main_webapp.py | UTF-8 | 2,392 | 2.59375 | 3 | [] | no_license | from flask import Flask, render_template, redirect, request
from random import choice as rand
import main
import text_processor
import os
app = Flask(__name__)
global state
state = {'mad_libs':None,
'tags_to_replace':[],
'passage_dir':os.path.join(os.path.dirname(os.path.abspath(__file__)), 'passages'), #absolute path... | true |
739e46a9b5eb2704b5350ce9d22be25d9f93e604 | Python | bugsyabbs/python-prog | /twentyseven_lines.py | UTF-8 | 320 | 3.875 | 4 | [] | no_license | # rajasekhar vanjarapu
# Twenty_seven_lines.py
# problem statement:
# print 27 lines
# using the nine line function
# which uses three line functions
def nine_lines():
three_lines()
three_lines()
three_lines()
def three_lines():
print
print
print
print "first line"
nine_lines()
nine_lines()
nine_lines()
prin... | true |
345b7f1bc9cb56d99b3d18c81a89c934104e5342 | Python | tauovir/Nielit | /ML/day10/test1.py | UTF-8 | 292 | 2.578125 | 3 | [] | no_license | import cv2 as cv
import numpy as np
#Read image
img = cv.imread('apple.jpg',0)
rows,cols = img.shape
m = np.float32([
[1,0,100],
[0,1,150]
])
dst = cv.warpAffine(img, m,(cols, rows))
cv.imshow("Apple",dst)
cv.imshow("Apple2",img)
# Hold image till anyt key pressed
cv.waitKey(0)
| true |
12027db326c792c5e96911ba21eedbee8a1e36b0 | Python | Yaachaka/pyPractice1 | /bhch13/bhch13exrc16.py | UTF-8 | 1,576 | 4.6875 | 5 | [] | no_license | """
bhch13exrc16.py: Write a function called one_away that takes two strings and returns True if the strings are of the same length and differ in exactly one letter, like bike/hike or water/wafer.
"""
print('*'*80)
def one_away(s1, s2):
count = 0
if len(s1) == len(s2):
for i in range(len(s1)):
if s1[i]... | true |
db446ca876bc0af94884fe050e117e761f4cc791 | Python | sforiz/cmdaddrbook | /jsonutils.py | UTF-8 | 287 | 2.75 | 3 | [] | no_license | import json
def python2jsonfile(dict, filename, filemode="w"):
f = open(filename, filemode)
json.dump(dict, f, indent=2, separators=(',', ':'))
f.close()
del f
def jsonfile2python(filename, filemode="r"):
f = open(filename, filemode)
return json.load(f)
f.close()
del f | true |
57348fc4c562d08f66de7ba3759a69ca77f2015b | Python | HanDaWoon/Python_Study | /Hello_coding_python/dictionary/check_element.py | UTF-8 | 323 | 3.375 | 3 | [] | no_license | # 딕셔너리 선언
dict = {
"name" : "DB-HDW",
"type" : "computer",
"element" : ["cpu", "gpu", "ram", "mainboard"]
}
print("딕셔너리 선언(고정) : dict =", dict, "\n")
key = input("key : ")
if key in dict:
print(dict[key])
else:
print("존재하지 않는 키에 접근하고 있습니다.") | true |
5a1ed272806c23d820c924259e3fa8fffd2dbc1d | Python | jjwilke/PySkyNet | /lib/skynet/socket/pysock.py | UTF-8 | 4,300 | 2.671875 | 3 | [] | no_license | from skynet.utils.utils import traceback
class SocketOpenError(Exception): pass
class SocketConfirmError(Exception): pass
class SocketDie(Exception): pass
import sys
class Communicator(object):
import os
import os.path
ONE_KB = 1024
STRIDE = ONE_KB
CONFIRM = 'conf'
RECEIVED = 'received'
... | true |
ed1b2b162da2dd8c7e299e9a9e036f7a01d6af39 | Python | hwajong/python_test | /src/comatrix/prog1.py | UTF-8 | 750 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding:utf-8 -*-
import glob
META_DATA_FILE = "null.txt"
OUTPUT_PREFIX = "meta_added_"
# null.txt 메타데이터 로딩
f = open(META_DATA_FILE, 'r')
meta_data = f.read()
f.close()
print "** Meta data read success!"
print(meta_data)
# 현 디렉토리의 모든 txt 파일에
# 메타데이터를 붙여 새로운 파일을 만든다.
for fname in glob.glob... | true |
8d862f6ad5c5f75b466d116fddd10a78782dd76e | Python | ayk-dev/python-fundamentals | /hackerrank-exercises/finding_the_percentige.py | UTF-8 | 383 | 3.453125 | 3 | [] | no_license | n = int(input())
students = {}
for _ in range(n):
data = input().split(maxsplit=1)
name = data[0]
marks = list(map(float, data[1].split()))
students[name] = marks
query_name = input()
average_score = 0
length_marks = 3
if query_name in students.keys():
average_score = sum(students... | true |
d03d5cc4a951b5f57fbc4034a4a313b586061978 | Python | simplesmall/Python-FullStack | /Day0611/Day15_今日内容回顾.py | UTF-8 | 640 | 3.8125 | 4 | [] | no_license | print("ionf")
a = lambda n, m: n * n + m + 123
print(a(12, 12))
lst = [16, 45, 23, 2, 34, 12]
ll = sorted(lst)
ll = sorted(lst, reverse=True)
print(ll)
lst = ["张无忌", "张铁林", "赵敏", "小昭"]
def func(el):
if el[0] == "张":
return False
else:
return True
f = filter(func, lst)
... | true |
069b5c64a75662dc318bbc875065e6659fe4020a | Python | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2019/JOSE ONOFRE/PRACTICAS/Practica1/MultiplesTen.py | UTF-8 | 171 | 4.03125 | 4 | [
"MIT"
] | permissive | numero = input("Ingresa un numero: ")
num = int(numero)
if num % 10 == 0:
print("\nEl numero es multiplo de 10 ")
else:
print("\nEl numero no es multiplo de 10")
| true |
ddcca27deebfe60bc9f87c7bbbd7a96b4e892b46 | Python | nilsreiter/nilsreiter.de | /assets/2018-08-16-late-summer-school/test_install.py | UTF-8 | 214 | 2.640625 | 3 | [
"MIT"
] | permissive | try:
import requests
import nltk
print("Installation successful!")
except:
print("There was a problem with the installation of your python libraries. Please contact \
hackatorial@ims.uni-stuttgart.de")
| true |
60391796272b53bf7da89c6a846f02e8d20966ea | Python | Phil-star1984/Python_Homework_11 | /main.py | UTF-8 | 1,793 | 3.453125 | 3 | [] | no_license | import random
import json
import datetime
secret = random.randint(1, 5)
attempts = 0
with open("score_list.txt", "r") as score_file:
score_list = json.loads(score_file.read())
print("Top scores: " + str(score_list))
#sorted_score_list = sorted(score_list.items(), key=lambda x: x['attempts'])[:3]
#for... | true |
2d6484a4cf250439cde51db3b5073a72f6538804 | Python | elibj123/Development | /Python/Bourne/access_router.py | UTF-8 | 2,112 | 2.53125 | 3 | [] | no_license | import requests
import time
router_address = 'http://192.168.1.1'
router_login_address = '%s/goform/login' % router_address
router_ac_address = 'http://192.168.1.1/wlanAccess.asp'
def get_devices():
wlan_access = requests.get(router_ac_address)
html = wlan_access.content
table_begin_pattern = ["<tr dir=... | true |
e5f5513a6d9ef772ad884b6a90c22cd503ae620d | Python | adrianopls/GRIPy-X | /algo/rockphysics/Substitution.py | UTF-8 | 198 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive |
def Gassmann(Kd, Km, Kfl, phi):
"""
B = (1.0 - Kd/Km)
Ks = Kd + B*B/(phi/Kfl - phi/Km + B/Km)
"""
Ks = Kd + (1.0 - Kd/Km)**2/(phi/Kfl + (1.0 - phi)/Km - Kd/Km**2)
return Ks
| true |
b17307a54cf8eb01551df0789d8ef908c682c36d | Python | petrichorcode/data_science_programming | /intro_to_python/sales_tax.py | UTF-8 | 3,692 | 4.4375 | 4 | [] | no_license |
Lesson 4:
Control Flow
1. Introduction
2. Conditional Statements
3. Practice: Conditional Statements
4. Solution: Conditional Statements
5. Quiz: Conditional Statements
6. Solution: Conditional Statements
7. Boolean Expressions for Conditions
8. Quiz: Boolean Expressions for Conditions
9. Solution: Boolean Ex... | true |
51a51d41719ac49bf9e555f1d1121f5b2e8bd33f | Python | sidramowlana/FYP-Fake-news-detection-COVID | /ML/train_model.py | UTF-8 | 2,361 | 2.671875 | 3 | [] | no_license | from .access_train_dataset import *
import pickle
import pandas as pd
import numpy as np
from sklearn.metrics import classification_report
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn import svm
from sklearn.... | true |
a8b4c931a4db428a5c1bb7fb730721715954454c | Python | RyunoT/serial_test | /CanDigitalPanel/rs232c.py | UTF-8 | 2,892 | 2.65625 | 3 | [] | no_license | import serial
class CDP_config:
config = {
# item: [begin, end, float_change, initial]
1: [0, 2, 1, 0],
2: [0, 4, 1, 1],
3: [1, 99, 0.1, 3], # [0.1, 9.9]
4: [1, 9, 1, 1],
5: [2, 9999, 1, 2],
6: [1, 99, 1, 25],
7: [0, 1, 1, 0],
10: [1,... | true |
12aee18c3b34f6d114ac125858e64a146879378e | Python | sonnentag/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | UTF-8 | 149 | 2.609375 | 3 | [] | no_license | #!/usr/bin/python3
"""6-from_json_string"""
import json
def from_json_string(my_str):
"""from_json_string"""
return (json.loads(my_str))
| true |
0ca00467b9590e8b98f2f51948fc761d3f6acd15 | Python | simpledevelopments/Speaking-Eye | /speakingeye.py | UTF-8 | 11,103 | 2.59375 | 3 | [] | no_license | import cv2
import numpy as np
import dlib
modelPath = "models/shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(modelPath)
def getFaces(faceDetector, landmarkPredictor, im, DOWNSAMPLE_RATIO = 1):
faces = []
facespoints = []
facesoffsets = []... | true |
d7d7da96de87b8bf2796752e662b5d231acde1fa | Python | tzuyichao/python-basic | /brute/leetcode5-Longest-Palindromic-Substring.py | UTF-8 | 1,280 | 3.546875 | 4 | [] | no_license | class Solution:
def longestPalindrome(self, s: str) -> str:
maxLength: int = 1
low: int = 0
high: int = 0
start: int = 0
l: int = len(s)
for i in range(1, l):
low = i-1
high = i
while low >=0 and high < l and s[low] == s[high]:
... | true |
eb90f53932a320e687a3f7b74524e9c1fa9f641f | Python | a1025502/Leetcode | /461_Hamming_Distance.py | UTF-8 | 262 | 2.96875 | 3 | [] | no_license | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
x = list(f'{x:032b}')
y = list(f'{y:032b}')
ans = 0
for i in range(32):
if x[i] != y[i]:
ans +=1
return ans | true |
7897319c2c187158cf297df0922fa23c9daf85ef | Python | hobin2017/Webapp | /test_BeautifulSoap4/tutorial_ch02.py | UTF-8 | 1,951 | 4.03125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Chapter 2
Be careful that the new line character '\n' will affect your idea about the structure of the whole HTML page.
"""
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="... | true |
7120af7843b6e367bc925815971317f552f99f05 | Python | CybernetiX-S3C/Dshell | /dshell/plugins/ssh/ssh-pubkey.py | UTF-8 | 5,442 | 2.53125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | """
Extract server ssh public key from key exchange
"""
import dshell.core
from dshell.output.alertout import AlertOutput
import struct
import base64
import hashlib
class DshellPlugin(dshell.core.ConnectionPlugin):
def __init__(self):
super().__init__(
name="ssh-pubkey",
author="... | true |
c0ca85b9131dcfbd0e2e7070c24f7eaaf9766602 | Python | yingzy57/zidong | /社群销售数据排行榜-兰兰/salesrank.py | UTF-8 | 2,877 | 2.5625 | 3 | [] | no_license | import pandas as pd
import os
file_root=os.path.dirname(os.path.realpath('salesrank.py'))
file_root=file_root.replace('\\','/')
print('文件夹路径是'+file_root)
for r,d,f in os.walk(f'{file_root}/当日数据源'):
for s in f :
if '业绩统计' in s :
yeji=pd.read_excel(f'{file_root}/当日数据源/{s}')
elif '销售目标' in ... | true |
c81752827e47bc5f3d45a9653433fdd86d035529 | Python | DiegoxK/MisionTIC2022 | /Ejercicios semana4/3.py | UTF-8 | 876 | 4.21875 | 4 | [] | no_license | # Ejercicios
# Problema #3:
# Crear una función que retorne las palabras de una lista de palabras que comience con una
# letra en específico. Utilizar la función filter
#Algoritmo:
"""
"""
#Resultado esperado:
"""
---------------------------------------------------------------
Input =
Output =
... | true |
0e3bc4812cc2da72f7fe311e0a2271d94058dae9 | Python | jesdomtri/AII | /Django/entregable_django/main/models.py | UTF-8 | 837 | 2.578125 | 3 | [] | no_license | #encoding:utf-8
from django.db import models
class Autor(models.Model):
nombre = models.CharField(max_length=30, verbose_name='Autor')
def __str__(self):
return self.nombre
class Fuente(models.Model):
nombre = models.CharField(max_length=30,verbose_name='Fuente')
def __str__(self):
... | true |
36e6ef7d5007f62328f382e5eb5e6d8f3aee9004 | Python | mayitbeegh/advent-of-code-2020 | /day5.py | UTF-8 | 869 | 3.171875 | 3 | [
"MIT"
] | permissive | def to_seat_id(boarding_pass):
return int(boarding_pass.replace('B', '1').replace('F', '0').replace('R', '1').replace('L', '0'), 2)
assert to_seat_id('FFFFFFFLLL') == 0
assert to_seat_id('BFFFBBFRRR') == 567
assert to_seat_id('FFFBBBFRRR') == 119
assert to_seat_id('BBFFBBFRLL') == 820
def part_one(inputs):
... | true |
46224abae2a1c32f43dad02068c3b62a9544798e | Python | mrkrynmdsco/codility | /00_DemoTest/missing_integer.py | UTF-8 | 432 | 3.34375 | 3 | [] | no_license |
def solution(A):
seen = [False] * len(A)
for value in A:
if 0 < value <= len(A):
seen[value-1] = True
for idx in range(len(seen)):
if seen[idx] is False:
return idx + 1
return len(A)+1
if __name__ == "__main__":
A = [[1, 3, 6, 4, 1, 2],
[1, 2, 3]... | true |
f365e2a7513f0445b47d10a5f28659fa6e97ee22 | Python | sramego/code_samples | /sort_ll.py | UTF-8 | 1,162 | 4.28125 | 4 | [] | no_license | # Insert into a sorted linked list
class Node():
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def sorted_insert(self,new_node):
if self.head is None:
new_node.next = None
self.head = new_node
re... | true |