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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
64be4e2d34f5a5297b34d830c2038892e146c3e7 | Python | valot3/music-player-simulator | /music_player_simulator.py | UTF-8 | 683 | 3.3125 | 3 | [] | no_license | from data_structures import TwoWayNodeQueue
from time import sleep
class MusicPlayer(TwoWayNodeQueue):
def play_all(self):
if self.front is not None:
current_song = self.front
while current_song is not None:
print('Reproducing... ', current_song.data)
... | true |
6f9168ec98d97b2a235bc978073296f35619d310 | Python | wickworks/CURRYRECIPE | /prawncurry.py | UTF-8 | 1,642 | 3.640625 | 4 | [] | no_license | #This is a pawn
class Pawn:
team = 0
x = 0
y = 1
#kinged
kinged = 0
def initialize(self, team, x):
self.team = team
self.x = x
if team == 1:
self.y = 6
else:
self.y = 1
# returns a list of all MOVES given the location, team, and whether it's kinged
# e.g. [[2,0],[0,2]]
def possibleMoves(... | true |
149bf67be97efa7607c6bd1613a2e3097e38cb39 | Python | chhuang215/GreenPanel | /playground/gpio/temperature_ui/temperature_ui.py | UTF-8 | 3,046 | 2.671875 | 3 | [] | no_license | import sys
import os
import glob
import time
import random
import RPi.GPIO as GPIO
from PyQt5.QtCore import (QUrl, QThread, pyqtSignal)
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView, QQuickItem
from PyQt5.QtQml import QQmlApplicationEngine, QQmlProperty, QQmlComponent
class Temperature... | true |
afa26fa32d919a4b6d877f02f7e2f2a8334b5ae4 | Python | airuibel/python3 | /model_score/LG_model_test.py | UTF-8 | 3,182 | 2.796875 | 3 | [] | no_license | #-*- encoding:utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.externals import joblib
import math
import sklearn.preprocessing as preprocessing
import matplotlib.pyplot as p... | true |
8f042b98553e2c65fc1ee648e6cc49f5ebd7b862 | Python | starlightromero/flower-garden | /main.py | UTF-8 | 1,061 | 3.625 | 4 | [] | no_license | """Import Turle Graphics, Random, Flower, Tree, and Bush."""
import turtle as jerry
from random import choice, randint
from Flower import Flower
from Tree import Tree
from Bush import Bush
colors = ["pink", "green", "red", "blue", "yellow", "purple"]
jerry.speed(10)
screen = jerry.Screen()
screen.setup(800, 800)
for... | true |
2f38bcccb0ed7489720f4485eaa1a0bcd23eec29 | Python | gawhelan/jsonrpc | /util.py | UTF-8 | 860 | 3.0625 | 3 | [] | no_license | import socket
from contextlib import contextmanager
@contextmanager
def open_socket(address, family=socket.AF_INET, type=socket.SOCK_STREAM):
"""A basic context manager for sockets."""
sock = socket.socket(family, type)
sock.connect(address)
yield sock
sock.close()
def socket_recv(sock, bufsize)... | true |
38a9f956aaeccdc22fcb37ce4cc059a2258505cd | Python | sumanth82/realpy-proj | /dictionaries.py | UTF-8 | 1,382 | 4.34375 | 4 | [] | no_license | # Dict start with a {} and MUST be key:value pairs
# Keys must be immutable and MUST be UNIQUE in a dict.
# Dict themseleves are mutable types, just like lists
ages = {'Kevin': 59, 'alex': 29, 'Bob': 40}
print(ages)
# O/P: {'Kevin': 59, 'alex': 29, 'Bob': 40}
print(ages['Kevin'])
# O/P: 59
# Add new object to the ... | true |
3255c47f7dd104e1cc8527647751ceca121762fb | Python | HAMDONGHO/USMS_Senior | /python3/python_Practice/functionPractice.py | UTF-8 | 173 | 2.59375 | 3 | [
"MIT"
] | permissive | def FuncPrac():
print('Hello World')
def Adder(num1, num2, num3, num4):
return num1+num2+num3+num4
print(Adder(1,4,5,6))
if __name__=='main':
print('The End') | true |
577fe0dd027749558d4bb893ea8bfe3ac5b7b643 | Python | heiseish/DawnPy | /src/utils/json_encoder.py | UTF-8 | 517 | 2.734375 | 3 | [
"MIT"
] | permissive | import json
import numpy
__all__ = ['json_encode']
def json_encode(data):
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.integer):
return int(obj)
elif isinstance(obj, numpy.floating):
return float(obj)
... | true |
0107559f9e9f790f849a469586de4922fd19c941 | Python | zc-staff/th-bot | /preprocess1.py | UTF-8 | 743 | 2.640625 | 3 | [] | no_license | # preprocess raw qq txt to lines
# filter special messages
# args: <raw txt> <output file>
import sys
import re
pat1 = '[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ '
pat2 = r'\[图片\]|@|\[表情\]|\[发起投票\]'
pat3 = r'https?://.*$'
pat4 = r'^.+撤回了一条消息$'
pat4 = r'^.+礼物\].*$'
with open(sys.argv[1]) as f:
lines = [ l.strip(... | true |
89384f81c28ad084efdbc4b761e9d71856c1e4da | Python | cona-dev/python-prac | /basic-syntax/list-prac.py | UTF-8 | 657 | 4.34375 | 4 | [] | no_license | subway = ["유재석", "조세호", "박명수"]
print(subway)
print(subway.index("조세호"))
subway.append("하하")
print(subway)
# 유재석과 조세호 사이에 정형돈을 태움
subway.insert(1, "정형돈")
print(subway)
# 뒤에서부터 꺼내기
print(subway.pop())
print(subway)
# 정렬하기
num_list = [5, 2, 4, 3, 1]
num_list.sort()
print(num_list)
# 순서 뒤집기
num_list.reverse()
print... | true |
de0afbc00bcd141a12e0254dd2aac293f3a56631 | Python | ei1994/opencv_practices | /padding.py | UTF-8 | 1,704 | 3.25 | 3 | [] | no_license |
import cv2
import numpy as np
import matplotlib.pylab as plt
import scipy.misc as misc
'''
src - input image
top, bottom, left, right - border width in number of pixels in corresponding directions
borderType - Flag defining what kind of border to be added. It can be following types:
cv2.BORDER_CONSTANT - Adds a co... | true |
e9d5f241159500ef14ac047e422e02112c5e1871 | Python | scan3ls/holbertonschool-web_back_end | /0x00-python_variable_annotations/1-concat.py | UTF-8 | 171 | 3.21875 | 3 | [] | no_license | #!/usr/bin/env python3
""" Basic Annotations """
def concat(str1: str, str2: str) -> str:
"""concat function w/ annotations"""
return "{}{}".format(str1, str2)
| true |
73455f80aba7614d7bbd79d9bb989e0d22aecc50 | Python | shma1664/Project | /Python/runoob/src/com/shma/运算符/位运算符.py | UTF-8 | 982 | 3.96875 | 4 | [] | no_license | '''
Created on 2015年10月14日
@author: admin
& 按位与运算符 :全1为1,有0为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
| 按位或运算符 :有1为1,全0为0 (a | b) 输出结果 61 ,二进制解释: 0011 1101
^ 按位异或运算符:相同为0,不同为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
~ 按位取反运算符:取反 (~a ) 输出结果 -61 ,二进制解释: 1100 0011, 在一个有符号二进制数的补码形式。
<< 左移... | true |
a6a914207a0aded3e13ce5934cbe4b62330b712d | Python | rantschler/VideoGamePhysics | /boilerplate.py | UTF-8 | 5,453 | 3.484375 | 3 | [] | no_license | #
# Project Title:
#
# Author:
#
#
# PACKAGES
#
import gameclass_0_95 as gc
import pygame as pg
from pygame.locals import *
from sys import exit
#
# CLASSES
#
#
# FUNCTIONS
#
def draw_field(field,background,color = gc.BLACK):
""" Modfies the background to mirror the playing surface.
... | true |
6a1a429e75da773ac17bb31692abf8f5f55c08b3 | Python | SamelaBruna/Curso-Python | /ex097.py | UTF-8 | 174 | 3.671875 | 4 | [] | no_license | def escreva(msg):
tamanho = len(msg) + 4
print('~'* tamanho)
print(f' {msg}')
print('~' * tamanho)
escreva('Gustavo Guanabara')
escreva('Bruna')
escreva('C++') | true |
9ad7014f77cbb148c267e28e0cf810bff8d24dc7 | Python | WiggidyW/WarcraftProject | /Firebase/Firebase.py | UTF-8 | 1,416 | 2.609375 | 3 | [] | no_license | import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
class Firebase:
def __init__(self, cert):
cred = credentials.Certificate(cert)
firebase_admin.initialize_app(cred)
self.client = firestore.client()
# Retrieves a specific document by its ID.
def fetch... | true |
e94835b0c51a5890cfa2faa580d91010f9661466 | Python | Winnull/Algorithms-and-Data-Structure | /2.2 Dijkstra Algorithm using Heap.py | UTF-8 | 4,618 | 3.84375 | 4 | [] | no_license | from MinHeapForDijkstra import *
########################################################
# Reading the data, store the number of nodes
file = open("data/dijkstraData.txt", "r")
data = file.readlines()
num_nodes = len(data)
########################################################
# Class definitions
class Node(obje... | true |
56dd705e0cf7c4bbfa2886f0de2f7309f90c1180 | Python | KbearW/assessment-2 | /oo.py | UTF-8 | 6,046 | 4.34375 | 4 | [] | no_license | """Discussion Questions
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
1. Abstraction- Hiding details we don't need
2. Encapsulation- Keeping everything "together"
3. Polymorphism- Interchangeability of components
2. What is a class?
Class ... | true |
a39f64b51ae961dcaf2f5a28576a342774944055 | Python | lucasHSA/KostalPikoPy | /tests/test_piko.py | UTF-8 | 2,860 | 2.5625 | 3 | [
"MIT"
] | permissive | import httpretty
import unittest
from pikopy.piko import Piko
class Test(unittest.TestCase):
def setUp(self):
httpretty.enable() # enable HTTPretty so that it will monkey patch the socket module
httpretty.register_uri(httpretty.GET, "http://example.com", body=open("fixtures/index.html").read())
... | true |
94ae9b2f9386ef25669038eed0cefcf705e717cd | Python | Alektrona/psyc161-hw1 | /factorial.py | UTF-8 | 1,025 | 3.96875 | 4 | [] | no_license | """Module for estimation of factorial (Homework #1)
Note: this is just a skeleton for you to work with. But it already
has some "bugs" you need to catch and fix.
"""
# Katherine Alfred Homework 1, 4/4/2015
from nose.tools import assert_equal
# Counts activations of factorial_recursive in stack until it hit... | true |
3d9ac12f186cb2118b377c137cf9e032de8b88d4 | Python | Aasthaengg/IBMdataset | /Python_codes/p03252/s117297911.py | UTF-8 | 864 | 2.796875 | 3 | [] | no_license | from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator impo... | true |
f573e88975d0c243436a172dc005c35168d8fb22 | Python | gmarap/Grafos | /GarotoIxpertinho.py | UTF-8 | 1,110 | 3.5 | 4 | [] | no_license | import networkx as nx
'''
Autor: Gabriella Mara
Version: 1.0
'''
QCT = input().split()
while not (QCT.count('0') == 3):
Q = int(QCT[0]) #Quantidade de quarteirões/vértices
C = int(QCT[1]) #Quantidade de arestas
T = float(QCT[2]) #Fôlego
g = nx.Graph()
for i in range(0,C):
... | true |
89e6be1d173694615c24f515350228581bd8b15b | Python | COCOpuffonline/CSE | /notes/Alexis Pacheco - Lucky 7s.py | UTF-8 | 337 | 3.390625 | 3 | [] | no_license | import random
money = 15
rounds = 0
playing = True
while money > 0 and playing:
money -= 1
rounds += 1
if random.randint (1, 6) + random.randint (1, 6) == 7:
money += 1
money += 4
else:
playing = True
if money == 0:
print("Rounds played")
print(r... | true |
0b662c6561f8f9f96c768fa1f6b4e2aaeab9a285 | Python | Jean-BaptisteHatt/CSTwitterAnalysis | /twitter_collect/TwitterPredictor.py | UTF-8 | 2,477 | 2.984375 | 3 | [] | no_license | import tweepy
import numpy as np
def twitter_setup():
"""
Utility function to setup the Twitter's API
with an access keys provided in a file credentials.py
:return: the authentified API
"""
# Authentication and access using keys:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
... | true |
b6caf9b9c2b861315bdf8f7bc89c0ad93b1ac1db | Python | Aasthaengg/IBMdataset | /Python_codes/p03633/s813247917.py | UTF-8 | 177 | 2.890625 | 3 | [] | no_license | import math
def lcm(l):
r=l.pop(0)
for i in l:
r=r*i//math.gcd(r,i)
return r
N=int(input())
T=[]
for i in range(N):
T.append(int(input()))
print(lcm(T)) | true |
207cd0beefc676429b8eddbfd427cc78bb81a7ac | Python | MrBenGriffin/or-tools-fun | /domino/domino_cf.py | UTF-8 | 23,883 | 3.640625 | 4 | [
"Apache-2.0"
] | permissive | # Copyright 2021 Ben Griffin; All Rights Reserved.
#
# 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 law or ... | true |
472d4046d6a89e55bd5ecb217ef1783cd542927c | Python | ndjman7/Algorithm | /Leetcode/maximum-binary-tree/source.py | UTF-8 | 1,472 | 3.6875 | 4 | [] | no_license | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
def find_max_index(start, end):
if start == end:... | true |
14ddd256a78ef0ac593c5d6a9d83d1adab6453de | Python | lewtun/huggingface_hub | /api-inference-community/docker_images/sklearn/app/pipelines/structured_data_classification.py | UTF-8 | 977 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | from typing import Dict, List, Union
import joblib
from app.pipelines import Pipeline
from huggingface_hub import cached_download, hf_hub_url
DEFAULT_FILENAME = "sklearn_model.joblib"
class StructuredDataClassificationPipeline(Pipeline):
def __init__(self, model_id: str):
self.model = joblib.load(
... | true |
d48961b48823d8ec365e9a8da9c7184a4f6100b2 | Python | Vshalson/PYTHON-REST-API | /services/web/project/__init__.py | UTF-8 | 2,190 | 2.859375 | 3 | [] | no_license | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
#Initializing playlist app
app = Flask(__name__)
app.config.from_object("project.config.Config")
#Database SQLalchemy
db = SQLAlchemy(app) #object relation mapper
ma = Marshmallow(app) #convert o... | true |
ba76ef932729963720133ffe6518098b92e31169 | Python | Epariani/SanValentino | /sv/main_sv.py | UTF-8 | 728 | 3.109375 | 3 | [] | no_license | import streamlit as st
import pandas as pd
def get_max(lista):
array = [0, 0, 0, 0]
array[0] = lista.count("A")
array[1] = lista.count("B")
array[2] = lista.count("C")
array[3] = lista.count("D")
return array.index(max(array))
st.title("Che tipo sei? - ***S. Valentino Edition***")
df = pd.re... | true |
e098c123502c474d44ce12fb3ebc823270d29b8d | Python | cu-swe4s-fall-2019/best-practices-mderousseau | /basics_test.py | UTF-8 | 1,835 | 3.40625 | 3 | [] | no_license | import unittest
from get_column_stats import mean_col
from get_column_stats import stdev_col
import numpy as np
import random
def main():
# Unit testing mean_col and stdev_col methods
# for planned values
class TestColumnStats(unittest.TestCase):
def test_mean(self):
col = np.array([1,... | true |
043538f0d5e545b369840ca4b7bbe42e89b1a5bb | Python | quentintruong/UCLA-CS111-W18 | /P3B/lab3b.py | UTF-8 | 6,516 | 2.984375 | 3 | [] | no_license | #!/usr/local/cs/bin/python3
# NAME: Quentin Truong
# EMAIL: quentintruong@gmail.com
# ID: 404782322
import sys
# Read and process csv content into dict
def read_process_csv(csv_content):
csv_dict = {"SUPERBLOCK": [],
"GROUP": [],
"BFREE": [],
"IFREE": [],
... | true |
4f2fe0e0b8ff2035884d38cb47db7653d3edc13b | Python | dwarcher/pi3d | /ForestWalk.py | UTF-8 | 4,275 | 2.8125 | 3 | [] | no_license | # Forest walk example using pi3d module
# =====================================
# Copyright (c) 2012 - Tim Skillman
# Version 0.04 - 20Jul12
#
# grass added, new environment cube using FACES
#
# This example does not reflect the finished pi3d module in any way whatsoever!
# It merely aims to demonstrate a working conc... | true |
f91a9c944ed8fadf4351264fd0890207cf69cb5c | Python | snaiffer/TreeNote | /branch.py | UTF-8 | 1,464 | 3.484375 | 3 | [] | no_license | #!/usr/bin/env python
" A module is for realising tree structure "
from leaf import *
class Branch():
"""
A class realises tree structure with unlimited nesting
leaf module is necessary for working
"""
def __init__(self, name='branch'):
self.name = unicode(name)
self._children = []
def add(self, ... | true |
f4ff4d8a4e215207b220cf95c1b8a7dc0d5eaa93 | Python | tianyudwang/adversarial_imitation_learning | /ail/common/running_stats.py | UTF-8 | 4,500 | 3.203125 | 3 | [
"MIT"
] | permissive | from typing import Tuple
import numpy as np
import torch as th
class RunningMeanStd:
"""
Calulates the running mean and std of a data stream
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
:param epsilon: helps with arithmetic issues
:param shape: the shape of... | true |
69deed7f6291175928421c2879b7a0f4b00ca9fd | Python | julianandrews/adventofcode | /2017/d15.py | UTF-8 | 1,591 | 3.46875 | 3 | [] | no_license | from itertools import islice
from utils import read_data
FACTOR_A = 16807
FACTOR_B = 48271
DIVISOR = 2147483647
def count_matches(generator_a, generator_b, number):
mask = (1 << 16) - 1
pairs = zip(generator_a, generator_b)
return sum(
1
for (a, b) in islice(pairs, number)
if a ... | true |
fb0fd9e0e6e75172e4467eb85ae5854647590da6 | Python | finalbattle/torweb | /torweb/lib/soaplib/util.py | UTF-8 | 6,995 | 2.609375 | 3 | [] | no_license | import httplib
import datetime
import urllib
from urllib import quote
from soaplib.etimport import ElementTree
def create_relates_to_header(relatesTo,attrs={}):
'''Creates a 'relatesTo' header for async callbacks'''
relatesToElement = ElementTree.Element('{http://schemas.xmlsoap.org/ws/2003/03/addressing}Relat... | true |
4fc89c4f957e77501e8497b31e19433e057970d9 | Python | dalevale/GIW2020-21 | /practica8.py | UTF-8 | 7,670 | 3.171875 | 3 | [
"CC0-1.0"
] | permissive | """
GIW 2020-21
Práctica 07
Grupo 05
Autores: XX, YY, ZZ,
(Nombres completos de los autores) declaramos que esta solución es fruto exclusivamente
de nuestro trabajo personal. No hemos sido ayudados por ninguna otra persona ni hemos
obtenido la solución de fuentes externas, y tampoco hemos compartido nuestra solu... | true |
1962a09f135e8a27e19ad8c4a51c97a8c78bcd89 | Python | v-yunbin/dcase2020_task2_baseline | /pytorch_vae/pytorch_model.py | UTF-8 | 3,570 | 2.84375 | 3 | [
"MIT"
] | permissive | """
Class definition script of Variational AutoEncoder in PyTorch.
Copyright (C) 2020 by Akira TAMAMORI
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your o... | true |
4e271d0e2f8254eff2f10403437562dc4b004512 | Python | EfimBerson/Aristotel2.0 | /Aristotel_Writer12.py | UTF-8 | 596 | 2.96875 | 3 | [] | no_license | import Arist_Action_Gen
g = []
# g.append(Arist_Action_Gen.vebs_random(1,0,0))
# g.append(Arist_Action_Gen.vebs_random(1,1,0))
# g.append(Arist_Action_Gen.vebs_random(0,1,0))
# g.append(Arist_Action_Gen.vebs_random(0,1,1))
# g.append(Arist_Action_Gen.vebs_random(0,0,1))
#
# for i in range(len(g)):
# print(g[i])
... | true |
875a2dddf30e4dab36368ce60e7f3f13d39a9cd7 | Python | jkchandalia/codingdojo | /python_stack/python/OOP/linkedlist.py | UTF-8 | 4,317 | 4.25 | 4 | [] | no_license | class SList:
def __init__(self):
self.head = None
def add_to_front(self, val):
new_node = SLNode(val)
if self.head is not None:
current_head = self.head
new_node.next = current_head
self.head = new_node # SET the list's head TO the node we created in the... | true |
a9870e9235c4800f9ff69951d53e03d038b2bb89 | Python | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_28.py | UTF-8 | 1,629 | 4.21875 | 4 | [] | no_license | """
Exercise 28: Boolean Practice
The logic combinations you learned from the last exercise are called
"boolean" logic expressions. Boolean logic is used everywhere in
programming. It is an essential fundamental parts of computation and
knowing them very well is akin to knowing your scales in music.
... | true |
5e547d78335d36e26e148b348ccbfd3f4380cea4 | Python | lionheartStark/sword_towards_offer | /base/冒泡.py | UTF-8 | 655 | 3.765625 | 4 | [] | no_license | def mysort(a_list):
for i in range(0, len(a_list) - 1):
print("------", i)
for n in range(len(a_list) - 1 - i):
print(n, n + 1)
if a_list[n] > a_list[n + 1]:
tmp = a_list[n]
a_list[n] = a_list[n + 1]
a_list[n + 1] = tmp
retu... | true |
26f15a5d22f76e98b02a7e58e732220ea5ad8571 | Python | daviduarte/distributed_inference | /2.py | UTF-8 | 914 | 2.609375 | 3 | [] | no_license | import time
from osbrain import run_agent
from osbrain import run_nameserver
from osbrain.proxy import Proxy
# Armazena as conexões atuais
connections = {}
def process_reply(agent, message):
agent.log_info('Processed reply: %s' % message)
ns = run_nameserver("127.0.0.1:15793")
agentServer = run_agent('AgentS... | true |
55257cee3f8ad673c8df1697d1393750ffae1cea | Python | francefaraz/crypthography | /polyalpha.py | UTF-8 | 837 | 3.296875 | 3 | [] | no_license | import random
l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
print("---Sender---")
msg=input("enter message to send:")
print("--Encrypting and sending---")
enc=''
dec=''
key1=len(msg)
key=[]
for i in range(key1):
key.append(random.randint(0,25))
j=0;
for ... | true |
b2118e4450a2269ff255511d832a5da0570d9e47 | Python | albiesoft/web_crawler | /crawler.py | UTF-8 | 2,045 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
def get_page(url):
try:
import urllib.request
return str(urllib.request.urlopen(url).read())
except:
return ""
#Checks the url of the next link
def get_next_target(s):
start_link = s.find('<a href=')
if start_link == -1:
return None, 0
start_q... | true |
0b2696f3f53322b0702090ed9e579fc9d7dc61e1 | Python | dcxufpb/unidade-1-exercicio-02-python-Annehelen-ltda | /cupom_test.py | UTF-8 | 2,658 | 3.234375 | 3 | [] | no_license | import cupom;
nome_loja = "Arcos Dourados Com. de Alimentos LTDA"
logradouro = "Av. Projetada Leste"
numero = 500
complemento = "EUC F32/33/34"
bairro = "Br. Sta Genebra"
municipio = "Campinas"
estado = "SP"
cep = "13080-395"
telefone = "(19) 3756-7408"
observacao = "Loja 1317 (PDP)"
cnpj = "42.591.651/0797-34"
inscri... | true |
0edd297e665cfc4e6041ff8f7880006a531c4824 | Python | Krishnaarunangsu/XpressoDataHandling | /xpresso/ai/admin/controller/metrics/abstract_metrics.py | UTF-8 | 822 | 2.59375 | 3 | [] | no_license | """ Abstract Metrics class"""
from xpresso.ai.admin.controller.persistence.mongopersistencemanager import \
MongoPersistenceManager
from xpresso.ai.core.logging.xpr_log import XprLogger
__all__ = ["AbstractMetrics"]
__author__ = ["Naveen Sinha"]
class AbstractMetrics:
"""
It defines basic format for gene... | true |
f57b648bc19007645e1d87639edb585d6de3a75e | Python | natashanorsker/RL_snakes | /irlc/gridworld/gridworld.py | UTF-8 | 9,547 | 2.53125 | 3 | [] | no_license | """
This file may not be shared/redistributed without permission. Please read copyright notice in the git repo. If this file contains other copyright notices disregard this text.
"""
import sys
from collections import defaultdict
from gym.spaces.discrete import Discrete
from irlc.ex09.mdp import MDP
from irlc.ex09.mdp ... | true |
484217a9b1de146bc6961491b84851d8567a1657 | Python | VaghinakSTDev/ml_tree | /tree.py | UTF-8 | 6,989 | 2.625 | 3 | [] | no_license | import pandas as pd
import pickle
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
import timeit
import progressbar
import joblib
from xgboost import plot_tree
import matplotlib.pyplot as plt
import numpy as np
INPUT_COLUMNS = [
... | true |
e0e59ac1d8072a77d78b796818ed316d782dab54 | Python | guilhermemaas/guanabara-pythonworlds | /exercicios/ex026.py | UTF-8 | 484 | 4.34375 | 4 | [] | no_license | """
Faca um programa que leia uma frase pelo teclado e mostre:
Quantas vezes aparece a letra "A"
Em que posicao ela aparece pela primeira vez
Em que posicao ela aparece pela ultima vez
"""
frase = str(input('Digite uma frase qualquer: ')).upper().strip()
count_a = frase.count('A')
pos_first_a = frase.find('A') + 1
po... | true |
f8afd9a314ce82754b1161158d1458658a37c3ea | Python | allanhung/pypillar | /pypillar/utils/get_host.py | UTF-8 | 1,150 | 2.703125 | 3 | [] | no_license | #!/usr/bin/python
def parser_host(hostname, osdistribution, osver):
"""
set host attr by os version, hostname
os_ver:
Microsoft Windows Server 2012 R2 Standard: 6.3.9600.0
"""
results = {}
if '.' in hostname:
host, domain = hostname.split('.',1)
else:
host = hostnam... | true |
654d298e97bc029ed69707f970d0da3968a17457 | Python | LYttAGrt/IU_masters | /task1.py | UTF-8 | 788 | 3.3125 | 3 | [] | no_license | from datetime import datetime
cnt = {}
def decorate(function: callable):
"""
Sinmplest decorator.
:param function: object to be called.
:return: generated wrapper
"""
def wrap(*args):
'''
Wrapper for decorator. Callbacks, you are welcome!
:param args: Arguments for c... | true |
d9b4f3bff308bfc3c4bea5ce6c90f94b60532e7b | Python | abhisheksahu92/Programming | /Solutions/maximizzing_diffrence.py | UTF-8 | 350 | 3.125 | 3 | [] | no_license | def maxi(arr):
max_diff = 0
for i in range(len(arr)):
maxi = 0
mini = 0
element = arr[i]
value = abs(len([x for x in arr[i+1:len(arr)] if x < element]) - len([x for x in arr[0:i] if x > element]))
if max_diff < value:
max_diff = value
print(max_diff)
for... | true |
b8d3dd125b97142914e3ece9dc1a655123c3554a | Python | jmhobbs/pyUSB7 | /effect-bit.stream.py | UTF-8 | 2,279 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # -*- coding: utf-8 -*-
# Copyright (c) 2009 John Hobbs
# 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 use, copy, modify, ... | true |
1beb0bdb9e3180663a99c12e61591959d8171c3f | Python | liskin/dotfiles | /bin/liskin-battery-watch | UTF-8 | 2,115 | 2.640625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
from dataclasses import dataclass
import os
import time
from typing import Any
from typing import List
import notify2 # type: ignore [import]
def slurp(filename: str) -> str:
with open(filename) as f:
return f.read()
@dataclass
class SysAttrs():
path: str
def _read_att... | true |
555b7aa35629ed4b530182675555dff0ae33a8e4 | Python | krinj/kaggle-whale-id | /src/trainer/whale_trainer.py | UTF-8 | 4,795 | 2.59375 | 3 | [] | no_license |
# -*- coding: utf-8 -*-
"""
<ENTER DESCRIPTION HERE>
"""
import random
from typing import List
import numpy as np
from raid import Trainer, IDataset
from raid.data.functional.score_counter import ScoreCounter
from raid.logic.config import Config
import torch
import torch.nn.functional as F
from torch import optim
f... | true |
660156bd51edb4d20004e8cd8ac74281470f4bb2 | Python | cbilson/clef | /clef/user.py | UTF-8 | 9,460 | 2.5625 | 3 | [] | no_license | import json
from datetime import datetime, timedelta
from clef import mysql, app
class User:
def __init__(self, id, name='', email='', joined=None, average_dancability=0.0, access_token=None,
token_expiration=None, refresh_token=None, status=None):
self.id = id
self.name = name
... | true |
dfbd4a27a6597887a7fe8a5550581f166768b3a3 | Python | fvk1978/client-server-searching | /cs_sqlite.py | UTF-8 | 5,171 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
# let's create tables and indexies
statements = [
"""
CREATE TABLE if not exists books_titles (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
book_title TEXT NOT NULL
);""",
"""
CREATE TABLE if not exists chapters_titles (
id INTEGER PRIMARY KEY AUT... | true |
dfd9c664e931f174e20b79c78da4bd687fafe1de | Python | XifeiNi/LeetCode-Traversal | /python/DP/length-longest-fibonacci-subsequence.py | UTF-8 | 684 | 2.859375 | 3 | [] | no_license | class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
dp = [[0 for _ in range(len(A))] for _ in range(len(A))]
ret = 0
for i in range(2, len(A)):
left, right = 0, i - 1
while left < right:
twoSum = A[left] + A[right]
if tw... | true |
5f1a7bd38ffad30d0c7959f972d5f7f8aa2a55f3 | Python | LeeroyC710/pj | /Desktop/testing/tests/test_2.py | UTF-8 | 155 | 3.8125 | 4 | [] | no_license | def product(n):
total = 1
for i in n:
total += i
return total
cool = str(input("Enter a number to find something cool: "))
print (product(cool))
| true |
439a7728860a770138c49ce58c5ddee5f9f7d847 | Python | ironfroggy/charlie | /charlie/tasks.py | UTF-8 | 740 | 2.65625 | 3 | [] | no_license | from dataclasses import dataclass
@dataclass
class Task:
name: str
command: str
workdir: str = "."
shell: str = ""
@classmethod
def from_config(cls, cfg):
tasks = []
for section in cfg.sections():
if section.startswith('job.'):
data = {**cfg[section]... | true |
e0ac49efb0a83a281466af659bd422ef12160d8c | Python | Yun-Hsuan/ScrapeCoinMarket | /coin_market_data_base/relativetime.py | UTF-8 | 1,403 | 2.8125 | 3 | [] | no_license | import pytz
from time import mktime
from datetime import datetime, timedelta
from tzlocal import get_localzone
class RelativeTime( object ):
_platform_timezone = pytz.utc
_local_timezone = get_localzone()
def __init__(self, pytzone=None):
if pytzone:
_platform_timezone = pytzone
... | true |
09a74d533e990cda1f9dbc55fb6fb847f63422bd | Python | justnickbryan/UoL-programming-fundamentals | /CA1_Shapes.py | UTF-8 | 7,849 | 4.53125 | 5 | [] | no_license | #Nicholas Bryan - 201531951
#COMP517 - CA1 Shapes
#missing internal angle calculator function: requests user to enter 2 known angles and performs calculation to give value of missing angle
def calcMissingAngle():
print("\nMissing angle calculator\nCalculates a missing internal angle of any triangle to 2 decimal pl... | true |
e5ab82fed55e1e403bf654565b517bdde8761864 | Python | N8Brooks/virus_simulation | /animated_sim.py | UTF-8 | 6,318 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 09:49:33 2020
@author: nathan
"""
import pandas as pd
import geopandas as gpd
import numpy as np
from numba import njit
import matplotlib.pyplot as plt
import multiprocessing as mp
from tqdm import tqdm
from random import choices
from celluloid ... | true |
be56866cb46051fe4ef25a5daa18060c80b44303 | Python | Capnode/Algoloop | /compare_benchmarks.py | UTF-8 | 996 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | import sys
import json
print(f'Will compare benchmark results {sys.argv[2]} against reference {sys.argv[1]}')
referenceBenchmark = json.load(open(sys.argv[1]))
newBenchmark = json.load(open(sys.argv[2]))
failed = False
for language in ["CSharp", "Python"]:
for key, value in referenceBenchmark[language].items():
... | true |
f5adf1b1fdfa66b3069083703aa47a9816f6498e | Python | lifelikegame/mypythonstudy | /30 Digit fifth powers.py | UTF-8 | 664 | 4.125 | 4 | [] | no_license | '''
https://projecteuler.net/problem=30
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 820... | true |
fed5e5cfece7ecb2d50b18ed251521607fe40eb6 | Python | joycebrum/online-judge-problems | /UVA/10503-the-dominoes-solitaire.py | UTF-8 | 2,402 | 3.640625 | 4 | [] | no_license | class Piece:
def __init__(self, left = -1, right = -1, free = True):
self.free = free
self.left = left
self.right = right
def turn(self):
temp = self.left
self.left = self.right
self.right = temp
def __repr__(self):
if self.free:
return '... | true |
686e955e265abb293beb22cdce935d0f0744bcfd | Python | bmatejek/addax | /visualize/graph.py | UTF-8 | 920 | 3.5 | 4 | [
"MIT"
] | permissive | import networkx as nx
def VisualizeGraph(graph, output_filename):
"""
Visualize the graph using networkx and output the result in a .dot file
@param graph: the graph data structure to visualize
@param output_filename: the file to save the visualized results
"""
# different visualizations for... | true |
4b316058748bd734762a9ae9ed65cbb801002329 | Python | coaalst/fatman-enviroment-driver-service | /app/modules/gpio_interface.py | UTF-8 | 1,258 | 3.046875 | 3 | [] | no_license | id = "GPIO controller: "
# GPIO init
try:
import RPi.GPIO as GPIO
except ModuleNotFoundError:
print(id + "Error importing RPi.GPIO, switching to mock up")
pass
import time
# Mock up for testing io
class GPIO:
BCM = 1
OUT = 1
IN = 1
RISING = 1
HIGH = 1
LOW = 0
def output(pin, value):
pass
de... | true |
fdfa2d016f373e8a4d1c35dd06818d79ebc810d3 | Python | besty1993/euler_project | /p030.py | UTF-8 | 502 | 3.609375 | 4 | [] | no_license | # https://projecteuler.net/problem=30
import time
def find_special_nums(powers) :
nums = []
for num in range(0, powers*10**powers) :
digits = [int(n) for n in str(num)]
fifths = sum([n**powers for n in digits])
if len(digits) <= 1 : continue
if num == fifths :
nums.a... | true |
a9ac59f6b631c7963dc5012fd9e9d90330c73dcc | Python | NadzeyaKadakova/DS_neuroimaging | /run_QC_example.py | UTF-8 | 845 | 2.671875 | 3 | [] | no_license | import glob
from QCmovie import QCmovie
from datetime import datetime
if __name__ == '__main__':
#find all *.nii files in the 'subset_ADNI_images' subfolder of 'data'
nii_files = glob.glob('../data_lesson3/some_raw_images/*.nii')
#sort the filenames list in-place
nii_files.sort()
#get the image ... | true |
bff00aedb6abcfd60190eea4e01ca455dc5f3463 | Python | BourneYu/magi | /blogs/2020年/3月3日:Python开发NLP应用新思路:Streamlit与FastAPI双剑合璧/1.3/zhinengwenda.py | UTF-8 | 3,760 | 3.359375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
from lxml import etree
import jieba
import re
import sys,time
import os
'''
其中:
- requests库用来向搜索引擎搜索答案;
- lxml用来获取答案;
- jieba库用来提取问题以及做出问题分析
- re是处理语言的正则匹配库;
- sys以及time库用来调试输出效果
- os模块用来写入文件以搭建模式选择。
'''
# 实现逐字输出的效果
def print_one_by_one(text):
sys.stdout... | true |
f00021617958023dd02b55cba610b2f428a6c58e | Python | ysy970923/computer-vision-class | /ICV21_Assignment#4/src/prob3/train_svm.py | UTF-8 | 944 | 2.625 | 3 | [] | no_license | from sklearn import svm
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
from sklearn.pipeline import Pipeline
import copy
import os
from math import log
# make my classifier
svm_clf = svm.LinearSVC(max_iter=10000, class_weight='balanced')
# get preprocessed data(hog... | true |
f3a0d40b4f111ce0046b639191a44a3595025e48 | Python | Aigggerim/web_development | /cycle1/c3.py | UTF-8 | 104 | 3.671875 | 4 | [] | no_license | a = int(input())
b = int(input())
for i in range(a, b + 1):
if i ** 0.5 % 1 == 0:
print(i)
| true |
325240e946b3b2618766c54ab3040e6c4bfb31ab | Python | arsturges/miscellaneous | /prisoner_puzzle/get_sixes.py | UTF-8 | 836 | 3.15625 | 3 | [] | no_license | from pprint import pprint
abc_set = [1, 2, 3]
letter_array = []
for a in abc_set:
for b in abc_set:
for c in abc_set:
for d in abc_set:
for e in abc_set:
potential_set = [a, b, c, d, e]
letter_array.append(potential_set)
... | true |
6d81861b5355632fdd2e0dfd8f46c0e6fbb2d603 | Python | cirrouscm/numerical-method | /gauss-seidle.py | UTF-8 | 971 | 3.65625 | 4 | [] | no_license | #----------------------------METODE SEIDEL-----------------------------
print("--------------------- ITERASI SEIDEL ---------------------------")
def seidel(a, x ,b):
#Menentukan panjang dari matrik
n = len(a)
k = 0
# Looping itu mencari x1,x2,x3
for i in range(0, n):
d = b[i]
# untuk mengh... | true |
d1522e443537cb7207b13a148bd615bec282fc43 | Python | daniel-reich/ubiquitous-fiesta | /JgYPQrYdivmqN4KKX_3.py | UTF-8 | 401 | 2.703125 | 3 | [] | no_license |
def BMI(weight, height):
w,pork = weight.split()
h,iorm = height.split()
wconv,hconv = 2.205,39.37
if pork == 'pounds':
w = float(w)/wconv
h = float(h)/hconv
h,w = float(h),float(w)
bmi = round(w/h**2,1)
return '{} Underweight'.format(bmi) if bmi < 18.5 else '{} Normal weight'.format(bmi) if bmi ... | true |
84ed64a3096080ffb41bc0e82deef0d29a803145 | Python | DucAnh2111/VuDucAnh-C4T8 | /session6/input_number.py | UTF-8 | 115 | 4.09375 | 4 | [] | no_license | txt = input("Enter a number?")
print (txt)
if txt.isdigit():
print("A number")
else:
print("Not a number") | true |
b279bc24a4a23bb5d19b940d370b6354aca376b0 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_139/494.py | UTF-8 | 1,105 | 2.828125 | 3 | [] | no_license | from itertools import permutations
DEVICES = []
def is_conf_pass(outlets):
set_diff = list(set(outlets) - DEVICES)
return len(set_diff) == 0
def flip_switches(outlet, switches):
lst = map(int, list(outlet))
for i, switch in enumerate(switches):
if switch == 1:
lst[i] = 0 if lst[i] == 1 else 1
return ... | true |
ebf30cd90b7080961b51a2e115aa19003ddd17e0 | Python | 824zzy/Leetcode | /N_Queue/MonotonicHeap/L2_1851_Minimum_Interval_to_Include_Each_Query.py | UTF-8 | 749 | 3.03125 | 3 | [] | no_license | """ https://leetcode.com/problems/minimum-interval-to-include-each-query/
TODO: https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1186817/JavaC%2B%2BPython-Priority-Queue-Solution
"""
class Solution:
def minInterval(self, A, queries):
A = sorted(A)
pq = []
ans = {}... | true |
083f7bc20cbd303b3aea642129c2a3001bc85b22 | Python | renukadeshmukh/Leetcode_Solutions | /830_PositionsofLargeGroups.py | UTF-8 | 1,679 | 4.21875 | 4 | [] | no_license | '''
830. Positions of Large Groups
In a string S of lowercase letters, these letters form consecutive groups of the
same character.
For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx",
"z" and "yy".
Call a group large if it has 3 or more characters. We would like the starting
and ending po... | true |
2a9f8aa940873ede8302e79f82cc9614cd3b8e8d | Python | alirazamir7781/image-search-poc | /training/preparation.py | UTF-8 | 3,975 | 2.6875 | 3 | [] | no_license | import argparse
import os
import sys
import multiprocessing
import ujson
from toolz.functoolz import compose, pipe
from functools import partial
from multiprocessing import Pool
import time
import shutil
def create_sets(base_image_path, path, label,item):
image_id = item['image_id']
model_name = item[label]
... | true |
c1361fa08fef7762ea53ccf810a0dd39de5dfe85 | Python | ratulesrar3/mlpp-spring-17 | /hw3/analyze.py | UTF-8 | 8,081 | 2.875 | 3 | [] | no_license | # Building an ML Pipeline, CAPP 30254
#
# Scripts to run the magic loop to classify and evalute different models
#
# Ratul Esrar
from __future__ import division
import numpy as np
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
import time
imp... | true |
9bdcde49b1e5df1a750a8df9a91b2f2dda0aef6c | Python | wsgan001/PyFPattern | /Data Set/bug-fixing-2/a6d32eda84623305755ff46503c37d345a8d2feb-<_format_metadata>-bug.py | UTF-8 | 369 | 3.296875 | 3 | [] | no_license |
def _format_metadata(self, metadata):
'\n :param metadata: A list of dicts where each dict has keys "key" and "value"\n :return a dict with key/value pairs for each in list.\n '
new_metadata = {
}
print(metadata)
for pair in metadata:
new_metadata[pair... | true |
adf79f7b67bb4134d8e49798cb1c6e3283303724 | Python | nagreme/phac_lethbridge | /parse_id_locus.py | UTF-8 | 1,590 | 3.28125 | 3 | [] | no_license | #!/usr/bin/env python
# Written by Nadège Pulgar-Vidal
# January 23, 2017
# Purpose: Read a list of gene id/locus and parse out and format the
# different parts nicely
#----------------------------------------------------------------------
import sys
import re
#------------------------------Constants------... | true |
c03dedb2460623f2c5cb4cd7fd806852618ee570 | Python | ketanb56up/visualize_stock_market | /stock_management_app/models.py | UTF-8 | 389 | 2.78125 | 3 | [] | no_license | from django.db import models
class Stock(models.Model):
"""
Created Stock model with fields stock, close_price and date
"""
stock = models.CharField(max_length=50, verbose_name = "Stock")
close_price = models.FloatField(verbose_name = "Close Price")
date = models.CharField(max_length=50, verb... | true |
c995b1eb934b71347fbc7de63a369306d48adbb3 | Python | sa3mlk/projecteuler | /python/euler23.py | UTF-8 | 689 | 4.1875 | 4 | [] | no_license | #!/usr/bin/env python
def next_perfect_number(n = 1):
"""A perfect number is a number where all proper
divisors is equal to the number.
Yields the next perfect number from n
"""
while (True):
pn = 0
for i in range(1, (n / 2) + 1):
if n % i == 0:
pn += i
if pn > n:
break
if pn == n:
yield... | true |
e3ca1963220004edfcfad4967f32ec8f623c9f58 | Python | hemanthtv/Video-Magnification_Computer-Vision | /evm-sourcecode/code/butterworth_filter.py | UTF-8 | 3,958 | 3.1875 | 3 | [] | no_license | #..................................
#........Visualisierung 2..........
#..................................
#...Eulerian Video Magnification...
#..................................
#.. Author: Galya Pavlova..........
#..................................
from scipy.signal import butter, lfilter
import pyramid
import vid... | true |
7e506eaaaf1d567884b6a8f3e08e2ae6bd57878a | Python | Glecun/pygame-stars | /sauv/classes.py | UTF-8 | 3,201 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import time
class Vais:
#Permet de creer le vaisseau
def __init__(self):
#
self.image = pygame.image.load("image/vaisseau.png").convert_alpha()
self.position_vais = self.image.get_rect()
self.position_vais.center ... | true |
8ca9243bc8d23cf0c38fbed773e485bdb268c5dd | Python | raphaelricardo10/pywallet | /sales/product.py | UTF-8 | 463 | 3.265625 | 3 | [] | no_license | class Product:
def __init__(self, prodType: str, value: float) -> None:
self.type = prodType
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
try:
Product.validateValue(value)
except:
... | true |
b7517553d0bc5f570530a06c41885ed7c37481b9 | Python | MelodyChu/Coding-Challenges | /ordered_dict_practice.py | UTF-8 | 441 | 3.34375 | 3 | [] | no_license | from collections import OrderedDict
d = {'banana':3, 'apple':4, 'pear':1, 'orange':2}
print d.keys()
print d.items()
print d.values()
new_d = OrderedDict(sorted(d.items(), key=lambda k: k['value']))
#new_d = OrderedDict(sorted(d.items()))
print new_d
#OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
... | true |
73310421b09fe2f230c03cff0886cb4948c80ebb | Python | DFTF-PConsole/AED-Labs-Algoritmos-LEI-2020 | /Arvore Splay (TP3 B)/mainBSplay.py | UTF-8 | 14,383 | 3.203125 | 3 | [
"MIT"
] | permissive | # #### NOTAS #### V1 Abordagem: Percorre ate as folhas, insere, e depois traz-lo para a raz (splaying) | Possui Pesquisa Binaria em Arrays
# Arvore Splay
# #### BIBLIOTECAS ####
import sys
# #### CONSTANTES ####
CMD_IN_LINHAS = "LINHAS"
CMD_OUT_NULO = "-1"
CMD_IN_ASSOC = "ASSOC"
CMD_OUT_NAOENCONTRADA = "NAO ENCONTR... | true |
51529a20fd896ff2e1234d96654db4287b3d0fee | Python | rabbitxyt/leetcode | /389_Find_the_Difference.py | UTF-8 | 673 | 3.71875 | 4 | [] | no_license | # Given two strings s and t which consist of only lowercase letters.
#
# String t is generated by random shuffling string s and then add one more letter at a random position.
#
# Find the letter that was added in t.
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
... | true |
5cde7611b170d39594a23f84f7b85b4b2ec4e704 | Python | RFeroli/ytmonitor | /configurable.py | UTF-8 | 408 | 2.765625 | 3 | [] | no_license | import json
class Configurable():
def __init__(self, fields=None):
with open('config.json', 'r') as f:
self.config = json.loads(f.read()) # Loads configuration file
if isinstance(fields, list):
new_config = {}
for field in fields:
ne... | true |
066350b85ecdf665148dc17a66759abdb2dc0528 | Python | SeungKyoJin/baekjoon | /2606_graph.py | UTF-8 | 704 | 3.59375 | 4 | [] | no_license | """
2606, 바이러스
스택을 구현할 수 있나?
dfs를 구현할 수 있나?
"""
num_node = int(input())
num_edge = int(input())
graph = dict()
def dfs(graph, p):
visited = list()
stack = list()
stack.append(p)
while len(stack) != 0:
node = stack.pop()
if node not in visited:
visited.append(node)
... | true |
cbafee08f32e9685ed153f7f03d2906ec3caad39 | Python | shuipingyang-14/python_programer | /python_learn/day_8/9 shutil模块.py | UTF-8 | 2,118 | 2.875 | 3 | [] | no_license | # -*- coding:utf-8
"""
@ author: ysp
@ time: 2020/7/5 12:50
@ file: 9 shutil模块.py
@ IDE: PyCharm
@ version: python 3.8.3
"""
import shutil
# 1. 文件内容拷贝
shutil.copyfileobj(open('test.txt', 'r'), open('test1.txt', 'w'))
# 2. 文件拷贝
shutil.copyfile('test.log', 'f2.log') # 目标文件不需要存在
# 3. 拷贝权限,内容,组用户不变
shutil.c... | true |
541087d0ad23be2eb3244da9f63fd4ee3cd20018 | Python | mdamien/twitter-followers-network | /basic_stats.py | UTF-8 | 1,585 | 2.75 | 3 | [] | no_license | import json
DATA = json.load(open('followers.json'))
account = 'dam_io'
print(account, 'followers with the most followers')
data = DATA[account]
data.sort(key=lambda x: -x['followers_count'])
for x in data[:20]:
print(x['followers_count'], x['name'], x['screen_name'])
print()
print(account, 'followers with the most... | true |
9a764bbe07a24d4b0f708ad5fbb16fb383e132d2 | Python | cultlead3r/sendtext | /sendtext.py | UTF-8 | 1,958 | 2.75 | 3 | [] | no_license | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_text(email, pas, smtp, port, sms_gateway, msg_subject, msg_content):
'''Use this to send the text.
Args:
-----
email: your email address that you're sending from (str)
pas: the... | true |