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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1b4702cf57fa84154697c2db17b81407d28dadfe | Python | whirlkick/assignment8 | /my1396/ass8/calculatereturn.py | UTF-8 | 1,014 | 3.4375 | 3 | [] | no_license | '''
Created on Nov 10, 2015
@author: ds-ga-1007
'''
import numpy as np
class CalculateSingleDayReturn():
def __init__(self,positions,initial_capital,num_trials):
self.positions=positions
self.position_value=initial_capital/self.positions
self.num_trials=num_trials
def return_... | true |
b7fed3f9339b13bbe4677db4e441c25e794ec640 | Python | nju04zq/lianjia_crawler | /html_page_test.py | UTF-8 | 3,894 | 2.65625 | 3 | [] | no_license | from html_page import *
page = HtmlPage()
head = page.get_head()
head.set_title("<test page>")
body = page.get_body()
p = HtmlParagraph()
body.add_element(p)
a = HtmlAnchor()
a.set_value("google")
a.set_href("http://www.google.com")
p.add_value("<text & in paragraph>")
p.add_value("<br><b>{}</b>".format(a), escape=... | true |
c8e35c04900006e0b11e6b4169466ba391425b03 | Python | Nooder/Python-Automate-The-Boring-Stuff | /Chapter 16/TextMyself.py | UTF-8 | 683 | 3.546875 | 4 | [] | no_license | #! python3
# Chapter 16 Project - Defines a textMyself() function that texts a message
# passed to it as a string
import TwilioCredentials
from twilio.rest import Client
# Setup
accountSID = TwilioCredentials.credentials.get('sid')
authToken = TwilioCredentials.credentials.get('token')
myNumber =... | true |
acc13524018ef31adcbb7e9d7e5296242bb39889 | Python | vtkrishn/EPI | /22_Honors_class/51_Reader_Writer_Problem (With Fairness)/Writer.py | UTF-8 | 274 | 2.9375 | 3 | [
"MIT"
] | permissive | import random
class Writer(Thread):
def set(self, d, l):
self.data = d
self.lock = l
def run(self):
while True:
self.lock.write_lock()
self.data.append(random.choice([0,1,2,3,4]))
self.lock.write_unlock() | true |
e13e014fb99f4a12e435c2bee2d9c021db531c5a | Python | littlelilyjiang/two_leetcode_daybyday | /easy/num167.py | UTF-8 | 1,125 | 3.5 | 4 | [] | no_license | '''
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
def twoSum(numbers, target... | true |
8c1e8b1bb1de3b728933d9c88eb90d92e86640c3 | Python | 4workspace/Python-calisma-notlari | /1_first_app.py | UTF-8 | 391 | 3.859375 | 4 | [] | no_license | # name = "Ahmet"
# surname = "CETIN"
# age = 27
# greeting = "My name is " + name + " " + surname + " and \nI am " + str(age)
# print(greeting[::2]) # bastan sona kadar kelimelerin birini al birini alma(2 adım at her seferinde)
def get_max_num(list_num):
print('get_max_num')
def getMaxNu... | true |
3a4a311545876b58bd454915d678d0bae43a3442 | Python | hollydev/LCC_DataTool | /spikes/qtdesigner/gui.py | UTF-8 | 2,035 | 2.640625 | 3 | [] | no_license | from PyQt5 import QtWidgets
from PyQt5.QtCore import QRunnable, QThreadPool
from .gradebook_tool import Ui_MainWindow
from source.system import main
import sys
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setup... | true |
4250a181af56358d21cad05339756a01807c2796 | Python | saitcakmak/sa-algorithm | /debug.py | UTF-8 | 423 | 2.59375 | 3 | [] | no_license | from normal_runner import analytic_value_VaR
print(analytic_value_VaR(0.49748))
from normal_runner import estimate
print(estimate(0.49748, 100000, 0.5, 'CVaR', -15, 10, 4, 2))
import numpy as np
import matplotlib.pyplot as plt
x_l = np.arange(-1, 1, 0.01)
res = np.empty_like(x_l)
for i in range(len(x_l)):
out = ... | true |
6badf02373b014fe9e2df6cb0269d42c9c9c5015 | Python | maciej-bendkowski/paganini | /paganini/tests.py | UTF-8 | 18,337 | 2.984375 | 3 | [] | permissive | import unittest
from paganini.expressions import *
from paganini.specification import *
from paganini.utils import *
class SingularTuner(unittest.TestCase):
def test_singular_btrees(self):
""" Singular tuning of binary trees
B = 1 + Z * B^2."""
spec = Specification()
z, B = V... | true |
3aa1c0164ad96c0d20aa7613ab8963625855e6eb | Python | killmaster/adventofcode2017 | /2/2.py | UTF-8 | 284 | 3.078125 | 3 | [] | no_license | import itertools
with open('input.txt') as f:
lines = [[int(n) for n in line.split()] for line in f]
part1 = sum(max(line) - min(line) for line in lines)
print(part1)
part2 = sum(b//a for line in lines for a,b in itertools.combinations(sorted(line),2) if b%a==0)
print(part2)
| true |
e4397c99b79a87a8913974fa6775bdd452aa8c93 | Python | koravel/orders_generator | /tracking/DataCollector.py | UTF-8 | 416 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import abc
import util.TextConstants as tconst
class DataCollector:
def __init__(self):
self.data = dict()
@abc.abstractmethod
def get_data(self, key):
raise NotImplementedError(tconst.not_implemented_text.format("get_data"))
@abc.abstractmethod
def set_data(self, ke... | true |
f6ddd1e06f3841c88c8291dc8e54e9b746ddf40c | Python | zaalvasania/112TermProject | /gameMode.py | UTF-8 | 15,165 | 2.84375 | 3 | [] | no_license | from cmu_112_graphics import *
from renderer import Engine
from primsMaze import Maze
from tank import Tank
from enemy import Enemy
from coin import *
from PIL import Image, ImageTk
import time, math, random, copy
##### GAMEMODE.py ######
# This file is the main GameMode file that
# combines the functinoality of the r... | true |
edba01bdb053bc5726771410a6489f7ad758305c | Python | EvilNOP/Algorithms | /InsertionSort/RecusiveInsertionSort.py | UTF-8 | 589 | 3.734375 | 4 | [] | no_license | #T(n) = O(n^2)
from random import shuffle
def insertionSort(seq, currIndex):
key = seq[currIndex]
seek = currIndex - 1
while seek >= 0 and seq[seek] > key:
seek -= 1
seq[seek + 2 : currIndex + 1] = seq[seek + 1 : currIndex]
seq[seek + 1] = key
return seq
def recusionInsertionSort(seq, currIndex):... | true |
ffbd6d501bed16ff2bd9cc7b9b81991146478f58 | Python | RemcoWalsteijn/PythonCursusBlok1 | /PythonLes8/pe8_FA.py | UTF-8 | 2,188 | 3.203125 | 3 | [] | no_license | stations = ['Schagen', 'Heerhugowaard','Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', '\'s-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
def inlezen_beginstation(stations):
beginstationreis = input('Vul het begin... | true |
b7ee0f0ea8b252d3bfba8f89e7c3641697c1ff36 | Python | uday4a9/python | /programs/perfcalc3.py | UTF-8 | 551 | 3.78125 | 4 | [] | no_license | #! /usr/bin/env /usr/bin/python3
import time
def interval(func):
def inner_calc(*args):
before = time.time()
res = func(*args)
diff = "%.08f"%(time.time() - before)
name = func.__name__
print(name + "(" + str(*args) + ") =", res, "took :", diff, "secs")
return res
... | true |
ba3a04fd1663f28c90f9ffae8f3f7e2c027bd745 | Python | paulmelis/blender-julia-test | /test/callit.py | UTF-8 | 504 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | import time, gc
import numpy
from julia.api import Julia
from julia import Main
jl = Julia(compiled_modules=False)
jl.eval("""
include("fn.jl")
import Base.convert
""")
print('allocating')
print(gc.get_stats())
x = numpy.ones(200*1024*1024, 'float32')
#x = numpy.array([1,2,3,4,5,6], dtype=numpy.float32)
#print(... | true |
3232d5d2e3d1823e3db5ab8a90c201b8871b5b57 | Python | valeriaskvo/TSA_stuff | /TSA_stand_Raspberry/TSA_stand/motors/gyems/__init__.py | UTF-8 | 12,657 | 2.53125 | 3 | [] | no_license | # TODO:
# add rotation counter
# add low pass filtering of the cuirrent and velocity
# put state in dictionary
# add conversion from raw data to state
# add sensor scales
from time import perf_counter
from math import pi
class GyemsDRC:
""" This class provide interface to the Gyems BLDC motor driver over CAN so... | true |
c1610489897e0913d50f92ded8afb87088fb6230 | Python | jpsiyu/stock-analysis | /lib/business.py | UTF-8 | 4,279 | 2.953125 | 3 | [] | no_license | from lib.income_statement import IncomeStatement
from lib.balance_sheet import BalanceSheet
from lib.cashflow import Cashflow
from lib.key_ratio import KeyRatio
from lib.quote import Quote
from lib.util import log
from lib.dcf import DCF
from lib import plot_tool
import pandas as pd
class Business():
def __init__(... | true |
a13962acb35d694dadad043d609f21330b123ce9 | Python | danielzengqx/Python-practise | /CC150 5th/CH4/4.2.py | UTF-8 | 986 | 3.6875 | 4 | [] | no_license |
# Given a directed graph, design an algorithm to find out whether there is a route be- tween two nodes.
#graph = {'A': ['B', 'C'],'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C'] }
graph = {'A': ['B', 'C'], 'D': ['E'], 'E': ['F'] }
class Queue:
def __init__(self):
self.items = []
def ... | true |
9df9d8680db235d8d1042538e73ae5d61f9ba626 | Python | henriquevital00/machine-learning | /preprocessing/main.py | UTF-8 | 1,238 | 2.609375 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.p... | true |
1e2aacb9390af5bf891231de704e8d272e39a8b4 | Python | carinaghiorghita/UBB_Sem4_AI | /Assignment3/gui.py | UTF-8 | 2,753 | 2.984375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from pygame.locals import *
import pygame, time
from utils import *
from domain import *
def initPyGame(dimension):
# init the pygame
pygame.init()
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_cap... | true |
e35217b4143b3ef5d4a4998b87dc6be85b3023b7 | Python | ffedericoni/Porto-Seguro | /ff_util.py | UTF-8 | 3,139 | 3.09375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 09:24:11 2017
@author: ffedericoni
"""
print(__doc__)
import pandas as pd
from datetime import datetime
# Set skeleton_test = False if you need to chdir ..
skeleton_test = True
def read_kaggle_data(competition_name=""):
"""
Generic function... | true |
d3315b5e8f00a6e3c466c4aaae15e662f03bc703 | Python | placidworld/funtodevelop | /os_walk.py | UTF-8 | 6,682 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 22:43:08 2020
@author: heart
"""
import os
#my_dir = '/home/l6oi/IDDOC/output/'
my_dir = '/home/l6oi/IDDOC/'
# intro to os.walk
print("******************* Start Print ****************")
for root_dir_path, sub_dirs, files in os.walk(my_dir):
print(... | true |
7c0a4d1666f4cb02564356f7c9f60ae65692f62a | Python | zhester/hzpy | /modules/ecli.py | UTF-8 | 15,952 | 3.359375 | 3 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/env python
"""
Extensible Command-line Interface
=================================
Implements a relatively sophisticated CLI using the `readline` module. This
means the CLI support session-based history and command completion. It also
allows users to customize their interaction via the relatively standa... | true |
1bdae4149464fd16278b66d73f5af5b807026525 | Python | Abhi-H/Scraping-p.ip.fi | /main.py | UTF-8 | 1,114 | 2.90625 | 3 | [] | no_license | from bs4 import BeautifulSoup
import urllib2
import time
from multiprocessing import Pool
def link_generator(hash_list):
char_list=list(chr(i) for i in range(ord('A'),ord('Z')+1))+list(chr(i) for i in range(ord('a'),ord('z')+1))
for first in char_list:
for second in char_list:
for third in char_list:
for fo... | true |
255d114cfb66247556efbfbc11341ffc461e9819 | Python | jeyziel/python-studies | /pense-em-python/chapter12/12-4.py | UTF-8 | 356 | 3.609375 | 4 | [] | no_license | ##tuplas como argumentos variáveis
#printall recebe qualquer número de argumento e os exibe:
def printall(*args):
print(args)
printall(1 ,23, 4)
## o complemento de de reunir é espalhar. Se você tiver uma sequência de valores e quiser passá-la a uma função como argumentos múltiplos, pode usar o operador *.
t = ... | true |
21b11b154f7cc69b3fd26bd580205a37805198a2 | Python | Ravi5ingh/seattle-airbnb-analysis | /util.py | UTF-8 | 5,782 | 3.609375 | 4 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
def normalize_confusion_matrix(cm_df):
"""
Normalize the values in a confusion matrix to be between 0 and 1
:param corr_df: The dataframe of the conusion matrix
:return: The normalized matrix
"""
... | true |
79aea504d3cf2559ad907d70fd794a1705613dfa | Python | valentinslepukhin/FitnessInference | /flu/sequence_and_annotations/count_strains_by_year_region.py | UTF-8 | 2,785 | 2.609375 | 3 | [
"MIT"
] | permissive | ###################
# count_strains_by_year_region.py
#script that prints a table of sequence counts in different years and geographic
#regions.
###################
from StringIO import StringIO
from socket import gethostname
import sys
sys.path.append('../../prediction_src')
import predict_flu as flu
from collections ... | true |
ab3ef3294fb2a9c2fb491744d981f666e5df1f10 | Python | protrain/loesungen | /loesungen_in_python/10-vererbung/aufgabe_W_10_09_fahrtenbuch/aufgabe_W_10_09_fahrtenbuch.pyde | UTF-8 | 2,241 | 4.21875 | 4 | [
"MIT"
] | permissive | # Basisklasse für alle Fahrzeuge
class Fahrzeug(object):
# Konstruktor, der vorgibt, dass ein
# Kilometersatz angegeben werden muss
def __init__(self, kmSatz):
self.__kmSatz = kmSatz
# Getter zur Rückgabe des Kilometersatzes
def getKmSatz(self):
return self.__kmSatz
# Klasse Fahr... | true |
0d9608145683d61cc1a969f8e4c62ca8e7eb2810 | Python | dremdem/pythons_handy_stuffs | /class_backward.py | UTF-8 | 322 | 3.140625 | 3 | [
"MIT"
] | permissive | from abc import ABCMeta, abstractmethod
class A(object):
def bla(self):
self.blabla()
class B(A):
def blabla(self):
print('blabla')
b = B()
b.bla()
class C:
__metaclass__ = ABCMeta
@abstractmethod
def bong(self):
pass
# c = C()
# c.bong()
class D(C):
def bong(self):
print('bong')
d = D()
d.bong(... | true |
f39daa1b169ace4a892d7bf116429e1335dbb2d1 | Python | jonathand94/ML-Classifiers-Library | /utils.py | UTF-8 | 23,517 | 3.0625 | 3 | [] | no_license | import numpy as np
import gc
import random
from errors import DimensionalityError
import os
import pandas as pd
import pickle
import pydicom as dicom
from PIL import Image
import imageio
import tensorflow as tf
class FileManager:
"""
Class that handles saving, writing and loading of files.
... | true |
38624a18e23d2893b4ffc8de259597c594fcd153 | Python | PaulKinlan/Amplifriend | /hub/utils.py | UTF-8 | 2,267 | 3 | 3 | [] | no_license | import hashlib
import os
import random
import hmac
import logging
import urlparse
import urllib
def utf8encoded(data):
"""Encodes a string as utf-8 data and returns an ascii string.
Args:
data: The string data to encode.
Returns:
An ascii string, or None if the 'data' parameter was None.
"""
if data is Non... | true |
277dd96628c9ddb676cec33c23213c66a16d5b94 | Python | HaiyinPiao/pytorch-a2c-ppo | /core/ppo.py | UTF-8 | 3,056 | 2.609375 | 3 | [] | no_license | import torch
from torch.autograd import Variable
from logger import Logger
# Set the logger
logger = Logger('./logs') # dive in later
step=0
def to_np(x): # from tensor to numpy
return x.data.cpu().numpy()
def to_var(x): # from tensor to Variable
if torch.cuda.is_available():
x = x.cuda()
retu... | true |
195762d66bec06fad5a240178083c9a2815a67ea | Python | vdpham326/Python-Challenges | /tictactoe_input.py | UTF-8 | 246 | 3.203125 | 3 | [] | no_license | def get_row_col(string):
lst = string.split() # split string into a list of two elements
print(string[0])
print(string[1])
print(lst)
# number = int(string[1])
# this = {
# string[0]:
# }
get_row_col("A3") | true |
6d854567094eb65521928690738b1ffead02115c | Python | MatAff/arduino | /pm_snake/py_sim/plan.py | UTF-8 | 6,409 | 3.015625 | 3 | [] | no_license | from collections import deque
import cv2
import math
import numpy as np
import pandas as pd
PI = 3.14159
def deg_to_rad(deg):
return deg / 360 * 2 * PI
def sin(deg):
return math.sin(deg_to_rad(deg))
def cos(deg):
return math.cos(deg_to_rad(deg))
def points_to_deg(start, end):
# TODO: Implement ... | true |
519adf24f75d207046c7065cea6da0d3830ef892 | Python | cellistigs/Video_Pipelining | /Excel_Ethogram.py | UTF-8 | 2,187 | 2.546875 | 3 | [] | no_license | import numpy as np
import sys
import os
import joblib
import pandas as pd
from Social_Dataset_utils import filepaths,datapaths,excelpaths
if __name__ == "__main__":
folderpath = sys.argv[1]
unique_string = sys.argv[2].split('cropped_part')[0]
sheet_tag = excelpaths(folderpath)[0]
dataset_paths = datap... | true |
73fc015f18c35f15e8968add66b0656b01c096ac | Python | jlandman71/cvnd-image-captioning | /model.py | UTF-8 | 3,978 | 2.5625 | 3 | [
"MIT"
] | permissive | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import numpy as np
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters... | true |
ecc9bda147293356f9da71dc1474fc52e0196a5d | Python | ssegota/stohastic-mathematics-simulations | /prvi dio/211117/v3zad4.py | UTF-8 | 833 | 3.46875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 11:27:46 2017
@author: Student
"""
#algoritam prihvačanja i odbacivanja
# 2 razdiobe 1 znamu generirati, a jednu ne
#ova koju znamo majorizira nepoznatu
# npr generiramo uniformnu za aproksimaciju beta razdiobe
#generiramo slučajnu vrijednost
#PRIMJER
#... | true |
0a3533fd473892408f55c6e6d9246af85f577e9a | Python | psycho-pomp/CodeChef | /CHEFWORK.py | UTF-8 | 380 | 2.546875 | 3 | [] | no_license | # cook your dish he
n=int(input())
c=list(map(int,input().split()))
t=list(map(int,input().split()))
#print(c,t)
min_t,min_a,min_at=1000000,1000000,1000000
for i in range(n):
if t[i]==1:
min_t=min(c[i],min_t)
elif t[i]==2:
min_a=min(c[i],min_a)
elif t[i]==3:
min_at=min(c[i],min_at)
... | true |
dd6acc6bb1fe130016eaf16ea702d1afb5daa079 | Python | sokjunem/MIS3640 | /Exercises/session8_Exercises.py | UTF-8 | 2,175 | 3.96875 | 4 | [] | no_license | # Exercise 4_1
def price(x):
count = 0
for letter in x:
count += ord(letter)-96
return count
# print('bananas ', '$',price('bananas'))
# print('rice ', '$', price('rice'))
# print('paprika ', '$', price('paprika'))
# print('potato chips ', '$', price('potato chips'))
# print('---------------------... | true |
c63dbf9f2ce3fa2c5f4e2e80afba1abe8b6f9bb6 | Python | AlibekNamazbayev/TelegramBot | /background_codes/bot.py | UTF-8 | 5,842 | 2.5625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import logging
import telebot
from telebot import types
from datetime import datetime
from dateutil import parser
import config
from db import CXOracle
import pdb
bot = telebot.TeleBot(config.token)
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug mes... | true |
288fb74c8d92fe55dc243d2fe0c22bb21b05f954 | Python | chenqianqian613/My-Python | /exe/exe0403/decorator1.py | UTF-8 | 459 | 3.28125 | 3 | [] | no_license | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# @Author : cqq
#
import time
def yunxingrizhi(c):
def inner():
t1=time.time()
c()
t2=time.time()
print('Total time is:',t2-t1)
print('加法被执行了')
return inner
@yunxingrizhi
def jiafa():
print('请输入第一个数字')
a=int(input())... | true |
cb02071ed3a9dfe4ecc54a3ce24601798d8e8b8a | Python | dangdu259e/Design-and-Analysis-Algorithm | /w5/FindWayMatrix.py | UTF-8 | 307 | 2.9375 | 3 | [] | no_license | def getMatrix_txt(filename):
file = open(filename, 'r')
matrix = [[int(number) for number in line.split()] for line in file] # đọc file txt theo dòng và từng cột của dòng
return matrix
def find_way_matrix(matrix):
return 0
matrix = getMatrix_txt("matrix.txt")
print(matrix)
| true |
6f8c724075699f230852386032f2b7edd508d364 | Python | Socksham/DesktopFilesFromOldMac | /Final Exam Calculator/finalexamcalculator.py | UTF-8 | 406 | 3.796875 | 4 | [] | no_license | currentPercentage = input("What is your current percentage?: ")
convertedCurrentPecentage = float(currentPercentage)
print(convertedCurrentPecentage)
while True:
finalExamPercentage = input("What final grade do you want?: ")
if finalExamPercentage == "A":
firstPart = convertedCurrentPecentage*(.... | true |
9c58671ca4724e7fbe439af2455322655a841597 | Python | General-Coder/Django-Introduction | /day02/app02/views.py | UTF-8 | 2,801 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | from django.shortcuts import render
from django.http import HttpResponse
from .models import Category,Item,Classes,Students
# Create your views here.
#获取商品页面
def get_html(req):
return render(req,'item.html')
#添加商品
def create_item(req):
#解析参数
parms = req.POST
name = parms.get("i_name")
barcode =... | true |
97ec31e25047f14e81817d71644f68e2c20ee29a | Python | kyearb/ProjectEuler | /PE21-40/PE33.py | UTF-8 | 871 | 3.4375 | 3 | [] | no_license | from time import time
def curious_fraction(x,y):
result = False
xstr = list(str(x))
ystr = list(str(y))
if x%10!=0 and y%10!=0 and len(xstr)>1 and x<y:
for digit in xstr:
try:
ystr.remove(digit)
xstr.remove(digit)
except ValueError:
... | true |
0606596f86e53ffaa8a5a1be9ecc83b7f1c7b10a | Python | trexsatya/chess | /python-fp/tests/chess/chess_rules_spec.py | UTF-8 | 2,629 | 2.75 | 3 | [] | no_license | from typing import List, Tuple
from unittest import TestCase
from app.chess.ChessBoard import Piece, ChessBoard, PieceType, cellIsEmpty, diffColor, rookMoves, showPossibleMoves, \
showChessBoard
from app.chess.Color import Color
from app.chess.Position import Position, toIndex, showPosition, fromString
from app.ch... | true |
74bf153314f4c118847dcb9c485b4630d4c3c77c | Python | Elalasota/PGIS_cw1 | /PGIScw1/src/zad4.py | UTF-8 | 178 | 3.09375 | 3 | [] | no_license | def duplikaty(lista):
dupli=[]
for i in lista:
if i not in dupli:
dupli.append(i)
return dupli
lista=['a', 'b', 'c', 'a']
print duplikaty(lista)
| true |
1ffd620eaf3a162d21ef8d7cc1a616932cc2ccf2 | Python | evan01/RenewableAnalysisDevelopment | /lib/testFunctions.py | UTF-8 | 3,050 | 3.390625 | 3 | [] | no_license | # now we should have all the information we need to do the real statistical analysis
def plotTimeSeries(self, data):
data.plot()
plt.savefig("./plots/originalSeries.png")
def plotHistogram(self, data):
data.hist()
plt.savefig("./plots/histogram.png")
def plotRampVCapacity(self, data):
"""
... | true |
df1663571c7ab87b0a70091033be3e10eaaff031 | Python | qaz734913414/No-reference-Image-Quality-Assessment | /regression_network/MAE.py | UTF-8 | 331 | 2.8125 | 3 | [] | no_license | import os
import numpy
sum_error = 0.0
num = 0
with open('test_result.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip('\n')
error = line.split(':')[-1]
error_abs = abs(float(error))
sum_error += error_abs
num += 1
MAE = sum_error/num
... | true |
cc21860c6742724684c82ffdc3ecd7b9a6c0f635 | Python | fucilazo/Dragunov | /机器学习/数据科学/sample3.7_核主成分分析.py | UTF-8 | 1,045 | 3.296875 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import KernelPCA
# 假设有一组由如下代码生成的双圆环数据集
def circular_points(radius, N):
return np.array([[np.cos(2*np.pi*t/N)*radius, np.sin(2*np.pi*t/N)*radius] for t in range(N)])
N_point = 50
fake_circular_data = np.vstack([circular_points(1.0, N_p... | true |
90e96c3ce589dc656b529f5080131c4cf55e0fe7 | Python | solomoniosif/SDA_Python_Exercises | /10_ianuarie_2021/10_01_ex5.py | UTF-8 | 482 | 4.21875 | 4 | [] | no_license |
# ? 5. Write a Python function to print first n lines of a file
# ! Varianta 1
def read_n_lines(filename, n):
with open(filename) as f:
for line_no, line in enumerate(f):
if line_no < n:
print(line, end="")
read_n_lines("sample.txt",5)
# ! Varianta 2
def read_n_lines2(filena... | true |
0ed7b9c570b267c03aba14b8a73bbfb038b02552 | Python | winner134/SpamClassifier2 | /Code/spam_classification.py | UTF-8 | 2,183 | 2.84375 | 3 | [] | no_license | # Category: evaluation
# Description: Set a number of learners, split data to train and test set, learn models from train set and estimate classification accuracy on the test set
# Uses: voting.tab
# Classes: MakeRandomIndices2
# Referenced: c_performance.htm
import Orange
from Orange.classification imp... | true |
b3692e1ff4423f13852b4badc73d4bec1ab9ca29 | Python | GavinHuttley/cogent3 | /src/cogent3/parse/gff.py | UTF-8 | 4,549 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | import collections.abc as abc
import functools
import os
import typing
from cogent3.util.io import open_
OptionalCallable = typing.Optional[typing.Callable]
OptionalStrContainer = typing.Optional[typing.Union[str, typing.Sequence]]
@functools.singledispatch
def gff_parser(
f: typing.Union[str, os.PathLike, abc... | true |
d4833bb5cec22e5be933ab59b072859ff93c5a0d | Python | TaridaGeorge/sentiment-analysis-tensorflow | /predict.py | UTF-8 | 1,519 | 2.8125 | 3 | [] | no_license | import tflearn
import string
import pickle
import argparse
import numpy as nm
def convertTextToIndex(dictionary, text):
document = []
text = text.lower().encode('utf-8')
words = text.split()
for word in words:
word = word.translate(None, string.punctuation.encode('utf-8'))
if word in di... | true |
0da49994616144ec785ef5034f627506a54dc7c0 | Python | John-Quien/3D_Tic-Tac-Toe_-AI_-project | /game_org.py | UTF-8 | 6,377 | 3.78125 | 4 | [] | no_license | ## 4x4x4 3D TicTacToe ##
import time
import random
import numpy as np
def gameRules():
print("Insert Rules")
def gameStart():
print("Game Start!")
print("Who will make the first move?")
# -1 is player 2, 1 is player 1
playerFirst = eval(input("Player 1: Enter 1 | Player 2: Enter 2 | Random: Enter... | true |
4c8ef21f10298899dcb53a1690aab19aedfc4297 | Python | jiwootv/weizman_python_class | /inclass/1-4_turtle2.py | UTF-8 | 1,010 | 3.296875 | 3 | [] | no_license | from turtle import forward as 앞으로
from turtle import backward as 뒤로
from turtle import mainloop as 그대로두세요
from turtle import left as 왼쪽
from turtle import right as 오른쪽
from turtle import penup as 그만그려
from turtle import pendown as 그려
from turtle import pensize as 굵기
from turtle import speed as 속도
from turtle import pen... | true |
1afc72dceeefb8cae8e8f51c63134814f80eb8f8 | Python | CadiDadi/200afs | /week4/project2.py | UTF-8 | 2,111 | 4.9375 | 5 | [] | no_license | # Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
# Extras:
# Keep the game going until the user types “exit”
# Keep track of how many guesses the user has taken, and when the game ends, print this... | true |
af6034ffc7e2d2da0a8ae488f440d1c251338375 | Python | RisingOrange/advent-of-code-2020 | /day 11/main.py | UTF-8 | 2,877 | 3.4375 | 3 | [] | no_license | from copy import deepcopy
def apply_rules_until_stable(grid, cell_transform):
while True:
grid, stable = apply_rules_to_every_cell(grid, cell_transform)
if stable:
break
return sum([
row.count('#')
for row in grid
])
def apply_rules_to_every_cell(grid, cell_... | true |
8d66c8c0d73b589f5b22eba40cd9417d67db7c17 | Python | irab/python-gfshare | /tests/test_integration.py | UTF-8 | 661 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | import gfshare
def test_buffer_size():
assert gfshare._BUFFER_SIZE > 1
def test_roundtrip():
assert gfshare.combine(gfshare.split(10, 10, b"secret")) == b"secret"
def test_breaks():
shares = gfshare.split(10, 10, b"secret")
shares.popitem()
assert gfshare.combine(shares) != b"secret"
def tes... | true |
6c19074bab38c8a8a772657c48d4535c3622902b | Python | AhbedShawarma/pi-arduino-interface | /Raspberry Pi/server.py | UTF-8 | 1,369 | 3.46875 | 3 | [] | no_license | # imports flask server library
from flask import Flask
from flask import request
# import serial library for usb communication with the arduino
import serial
# import struct library to pack data to send over serial
import struct
# check if arduino is connected by checking each of the 2 usb ports
# if not connected, s... | true |
9c84d5c1a2c5285672d769709cfa2f457650ccc3 | Python | woofan/leetcode | /347-top-k-frequent.py | UTF-8 | 704 | 3.421875 | 3 | [] | no_license | import collections
def topKFrequent(nums, k):
res = []
a = collections.Counter(nums).most_common(k)
for i in a:
res.append(i[0])
return res
#print(topKFrequent([1,1,1,2,2,3],2))
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counter = {}
res =... | true |
093eeff7f5cebc1e372801fdc0bdf0cc0ea6bea0 | Python | Mark-Seaman/50-Tricks | /doc/python/scan-record | UTF-8 | 1,714 | 3.0625 | 3 | [] | no_license | #!/usr/bin/env python
# Save records every time a file is given on the input
from sys import stdin
from os import environ
from threading import Timer
#-----------------------------------------------------------------------------
# Save a chunk of data
# Read 1000 lines to a file
def read_data(filename):
#print... | true |
61dfaac746c0c15460f2c10b205ca30db91d5aab | Python | koonyook/email-log-instant-search | /opt/axigend/lib/reader/ztail | UTF-8 | 1,110 | 2.546875 | 3 | [] | no_license | #!/usr/bin/python -u
import datetime,time,os,os.path,string,thread
import sys
from gzip import GzipFile
base = '/exports/'
vlock = thread.allocate_lock()
def printlog(machine,dateRange):
for iDate in dateRange:
filepath=base+machine+'/'+string.replace(iDate,'-','/')+'.gz'
fp=GzipFile(filepath,'r')
rest=""
... | true |
fe6a7577ff1da868ba7ac3beddcde52fbefc2e7c | Python | ZhanruiLiang/flappybirdpy | /flappybird/sprites.py | UTF-8 | 2,512 | 2.71875 | 3 | [] | no_license | import numpy as np
from . import gllib as gl
from .effects import FadeOut
from . import config
def init():
pass
def html_color(c):
return (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16))
class BaseSprite:
angle = 0.
alpha = 1.
_needRemove = False
def __init__(self, maskColor, screenPos)... | true |
f95eb88f8b5ae743155b8d3b55389c6d8686cfe2 | Python | ravisjoshi/python_snippets | /Array/SearchInsertPosition.py | UTF-8 | 801 | 3.890625 | 4 | [] | no_license | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Input: [1,3,5,6], 5 / Output: 2
Input: [1,3,5,6], 2 / Output: 1
Input: [1,3,5,6], 7 / Output: 4
Input: [1,3,5,6]... | true |
24c05d5ce922d8c7de79efbb259e22728471edbd | Python | JaeguKim/AI_2017_spring_semester | /python_practice/hw2/numpy학습코드/indexing.py | UTF-8 | 1,486 | 3.515625 | 4 | [] | no_license | import numpy as np
x = np.arange(10) #size가 10인 배열생성
print(x[2]) #2
print(x[-2]) #8
x.shape = (2,5) #이제 x는 2치원배열이됨
print(x[1,3]) #8
print(x[1,-1]) #9
print(x[0])
x = np.arange(10) #size 10인 배열생성
print(x[2:5]) #2,3,4
print(x[1:7:2]) #1,3,5
y = np.arange(35).reshape(5,7)
print(y[1:5:2, ::3]) #1,3행에 3열 간격으로 ... | true |
2a8091d077b7d8a8ce90b1b44a05bd585b92af20 | Python | radiosd/csvDataBase | /test/testCsvItem.py | UTF-8 | 3,503 | 3.09375 | 3 | [] | no_license |
"""
Using unittest to validate code for CsvItem class
rgr04jun18
look for #!# lines where corrections are pending
"""
from __future__ import print_function
import unittest
from rgrCsvData.csvDataBase import CsvItem
TEST_KEYS = ('key1', 'key2', 'key... | true |
ea4fd15b85dc53f1f6e30344463f86b53c68465e | Python | Matthias1590/InteractiveMenu | /interactivemenu/option.py | UTF-8 | 317 | 3.3125 | 3 | [
"MIT"
] | permissive | from typing import Optional, Any
class Option:
def __init__(self, text: str, value: Optional[Any] = None) -> None:
self.__text = text
self.__value = value
@property
def value(self) -> Optional[Any]:
return self.__value
def __repr__(self) -> str:
return self.__text
| true |
6f2d1acb1f5b8668e09e6f8e2d39c66fd75644ae | Python | SynedraAcus/indirectris | /gravity.py | UTF-8 | 18,594 | 3.234375 | 3 | [] | no_license | """
Game classes
"""
from bear_hug.bear_utilities import copy_shape
from bear_hug.event import BearEvent
from bear_hug.widgets import Widget, Listener, Layout
from collections import namedtuple
from math import sqrt
import random
Gravcell = namedtuple('Gravcell', ('ax', 'ay'))
class GravityField:
"""
A grav... | true |
091f24a5480ecabba8e400d526a62802a5b3b837 | Python | Shailesh9926/py-sudoku | /generate-sudoku.py | UTF-8 | 3,978 | 3.59375 | 4 | [] | no_license | #Advaitha S,1st year CSE,PESU-EC
import random
#========================================================
# Function checks if the number is in the row
#========================================================
def checkRow(testVal, row, grid):
return bool(testVal in grid[row])
#=========================... | true |
2ddb8e4443c1aae0b8827ab4513934ea8c3e2297 | Python | erinata/lecture_svm_2020 | /use_svm_circle.py | UTF-8 | 467 | 2.640625 | 3 | [] | no_license | import kfold_template
from matplotlib import pyplot as plt
from sklearn.datasets import make_circles
from sklearn import svm
data, target = make_circles(n_samples = 500, noise = 0.12)
plt.scatter(data[:,0], data[:,1], c=target)
plt.savefig("plot.png")
r2_scores, accuracy_scores, confusion_matrices = kfold_template... | true |
a79bd61fc4095ca3fd310e92d12c5075f745a654 | Python | tomfookes/CS310 | /graph_generalization.py | UTF-8 | 2,812 | 3.09375 | 3 | [] | no_license | from scipy import *
from pylab import *
import numpy as np
import networkx as nx
import random
###########
#Create a list of all possible partitons of the graph (O(2^n) - will take legit forever for big graphs... needs work)
###########
def all_partitions(G):
array = nx.nodes(G)
n = nx.number_of_nodes(G)
p... | true |
96abaddf90da78bbe1ba171e33acf44ce9673392 | Python | davibarbosam/listarecuperacao | /teste_retangulo.py | UTF-8 | 727 | 2.90625 | 3 | [] | no_license | from retangulo import Retangulo
#receber do usuarios as medidas
lado_a = int(input("Informe a medida do lado A do local:"))
lado_b = int(input("Informe a medida do lado B do local:"))
lado_a_piso = int(input("Informe a medida do lado A do piso:"))
lado_b_piso = int(input("Informe a medida do lado B do piso:"))
sala... | true |
c6598b71d39d09b7693cde68dfa92554ffbe4b7b | Python | miyashiiii/othello_board_recognition | /hough.py | UTF-8 | 771 | 2.90625 | 3 | [] | no_license | import cv2
import numpy as np
img = cv2.imread("test/IMG_9932.jpg")
def get_mask_by_bounds(img):
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lowerb = (43, 69, 42)
upperb = (87, 255, 255)
mask = cv2.inRange(img_hsv, lowerb, upperb)
return mask
mask = get_mask_by_bounds(img)
mask = cv2.bitwis... | true |
aabb1c6f0ae6537eb42667bd12fcad37b43f665c | Python | DanielCortild/Google-KickStart | /2020/2020H-1.py | UTF-8 | 212 | 2.90625 | 3 | [] | no_license | """
Google Kick Start - Round H 2020 - Q1 [SOLVED]
Daniel Cortild - 15/11/2020
"""
for T in range(int(input())):
N, K, S = map(int, input().split())
sol = min(K+N, N+2*(K-S))
print("Case #{}: {}".format(T+1, sol)) | true |
b90252d884378f63300cd627422a4d858db3870d | Python | 2yongbum/python-examples | /dict.py | UTF-8 | 210 | 3.03125 | 3 | [] | no_license | from collections.abc import Mapping
def update_dict(d1, d2):
if all((isinstance(d, Mapping) for d in (d1, d2))):
for k, v in d2.items():
d1[k] = update_dict(d1.get(k), v)
return d1
return d2
| true |
1465be6d57c84176a4a9096db8abd44f249e3d65 | Python | ddugue/stake | /tests/testParams.py | UTF-8 | 8,402 | 3.140625 | 3 | [
"BSD-3-Clause"
] | permissive | import unittest
import argparse
import params
class TestParamArg(unittest.TestCase):
"""Test the params decorators"""
def setUp(self):
self.cls = type('X', (object,), dict(a=1))
params.ARGPARSE_PARAMETERS = set()
def test_params(self):
"""Ensure that the decorator param create a P... | true |
2066d4be96b910dddb196122dea595e6bf919ddd | Python | SteveImmanuel/modern-cryptography | /crypt/gui/components/configuration_box/edit_with_button.py | UTF-8 | 861 | 2.8125 | 3 | [] | no_license | from PyQt5.QtWidgets import QWidget, QLineEdit, QSizePolicy, QHBoxLayout, QPushButton
class EditWithButton(QWidget):
def __init__(self, text_placeholder: str, text_btn: str, parent: QWidget = None):
super().__init__(parent)
self.text_placeholder = text_placeholder
self.text_btn = text_btn
... | true |
9cc1933ede025b2de289cf609a2d8eba4f66ff9e | Python | sernst/Trackway-Gait-Analysis | /tracksim/limb.py | UTF-8 | 4,749 | 3.21875 | 3 | [
"MIT"
] | permissive | import json
import typing
LEFT_PES = 'left_pes'
RIGHT_PES = 'right_pes'
LEFT_MANUS = 'left_manus'
RIGHT_MANUS = 'right_manus'
# The keys for each of the limbs
KEYS = [LEFT_PES, RIGHT_PES, LEFT_MANUS, RIGHT_MANUS]
SHORT_KEYS = ['lp', 'rp', 'lm', 'rm']
# Map between short-format and long-format keys for each limb
LIMB... | true |
631061d602065016b41fa0ebbfac4fa78ad9f5bb | Python | maheshmasale/pythonCoding | /Marketo/deduplicatorJSON.py | UTF-8 | 1,557 | 3.078125 | 3 | [] | no_license | import json
import time
class deduplicator(object):
def __init__(self,dataFilePath):
self.data = {"leads" : self.deduplicateIt(self.parseJSON((self.readFromFile(dataFilePath)))["leads"])}
print(self.data)
def deduplicateIt(self,dataArr):
print(len(dataArr))
dictData = {}
... | true |
b9fdcbe5ce689b8f00364b000114f036b2073f09 | Python | timothyxchen/VacaEase | /calculate_distance.py | UTF-8 | 4,882 | 2.953125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import urllib
import json
import datetime
import re
def request_data_from_url(url):
success = False
while success is False:
try:
response = urllib.request.urlopen(url)
# print("text: ", response)
... | true |
135df6d94b1c4e496f4e2628620b250a16dd9d38 | Python | bseales/HierarchicalClustering | /hierarchical_clustering.py | UTF-8 | 3,138 | 3.4375 | 3 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import pdb
file = ""
xValues = []
yValues = []
groups = []
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "[" + str(self.x) + ", " + str(self.y) + "]"
def ... | true |
78db6a55c386c12b414d51da14ee654bbd1854fa | Python | joyc/python-book-test | /corepython2/Ch15/retest.py | UTF-8 | 266 | 2.796875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
# m = re.match('foo', 'seafood') # 使用match() 查不到
# if m is not None: m.group()
# print m.group()
n = re.search('foo', 'seafood') # 改用search()
if n is not None: n.group()
print n.group()
| true |
0177b7e6c16241c8dc4fb48dd386486d56f19674 | Python | lixiangchun/multi-dendrix | /multi_dendrix/subtypes/subtype_specific_genes.py | UTF-8 | 13,688 | 3.125 | 3 | [] | no_license | #!/usr/bin/python
# Load required modules
# Try and load scipy's fisher's exact test function
try:
import scipy.stats
def fisher_exact(tbl):
odds, pval = scipy.stats.fisher_exact(tbl)
return pval
except ImportError:
try:
from fisher import pvalue ... | true |
4644bed9a63fd6e42d09855d130900943c6224ca | Python | Guan-Ling/20210125 | /5-C.py | UTF-8 | 180 | 3.703125 | 4 | [] | no_license | # Given a string, delete all its characters whose indices are divisible by 3.
# 移除整除三個字
s=input()
l=len(s)
d=""
for i in range(l):
if i%3!=0:
d=d+s[i]
print(d) | true |
fa737f328458ce0e9dd58827dab39292ddf0afb7 | Python | veneethreddy/450-DSA-Questions | /Python/Arrays/Three way partitioning.py | UTF-8 | 2,217 | 3.5625 | 4 | [] | no_license |
class Solution:
#Function to partition the array around the range such
#that array is divided into three parts.
def threeWayPartition(self, arr, a, b):
# code here
n=len(arr)
l=0
h=n-1
i=0
while(i<=h):
if arr[i]<a:
a... | true |
7521ed74b834bab0b7b210ae774df8b948055117 | Python | shinv1234/Algorithms | /Python3/dynamic_programming/fibonacci.py | UTF-8 | 536 | 3.359375 | 3 | [] | no_license | # Fibonacci
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
def fib_dp(n):
fib_val = [0,1]
if n < 2:
return fib_val[n]
for x in range(2,n+1):
fib_val.append(fib_val[x-1] + fib_val[x-2])
return fib_val[n]
def fib_dp2(n): # Why cannot execute..;;
... | true |
92b44f4f5a2e3394bb49879af07158cea2ffc442 | Python | JEHoctor/Kaggle-Santas-Workshop-Tour-2019 | /santaspkg/simple_scheduler.py | UTF-8 | 10,723 | 2.96875 | 3 | [] | no_license | # adapted from https://www.kaggle.com/dan3dewey/santa-s-simple-scheduler
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from santaspkg.cost_function import soft_cost_function as cost_function
from santaspkg.refinement import refinement_pass, refine_until_convergence
from santaspkg.dataset impor... | true |
9f1cbc4922e96aa85f6f596b73f827812e8503cb | Python | Ihyatt/coderbyte_challenge | /swapcase.py | UTF-8 | 805 | 3.734375 | 4 | [] | no_license | import string
def swap_case(strin):
"""take the str parameter and swap the case of each character.
For example: if str is "Hello World" the output should be hELLO wORLD.
Let numbers and symbols stay the way they are.
Example::
>>> swap_case("Hello-LOL")
'hELLO-lol'
>>> swap_case("Sup DUDE!!?")
'sUP dude!!?'
... | true |
dcf4156b86d81f511e24f0ae1cab898929c37921 | Python | Jeffz615/daifu | /daifu.py | UTF-8 | 1,401 | 3.421875 | 3 | [
"MIT"
] | permissive | # -*- coding:utf-8 -*-
daifu = '歪比巴卜'
decode_table = dict((daifu[i], i) for i in range(4))
print(decode_table)
encode_table = dict((val, key) for key, val in decode_table.items())
print(encode_table)
def daifu_encode(plain: bytes, encoding: str = 'utf-8') -> bytes:
cipher = ''
# print(list(plain))
for tw... | true |
bb2006563347cc585cbd5e1c278f7b7447491e34 | Python | cuiyekang/BM_Learning | /docs/python/course3/lz_5.py | UTF-8 | 11,327 | 3.5 | 4 | [] | no_license | import pandas as pd
import numpy as np
# df =pd.read_csv("./docs/python/course3/data/learn_pandas.csv")
# # print(df.columns)
# df = df[df.columns[:7]]
# print(df.head(2))
# print(df.tail(3))
# print(df.info())
# print(df.describe())
# df_demo = df[["Height","Weight"]]
# print(df_demo.mean())
# print(df_demo.max())
... | true |
808b893076a3b15b4b19e62d6c63f9f9e6a77341 | Python | aleksamarusic/EESTechChallengeFirstRound2017 | /hackathon - Pavlovic/classify.py | UTF-8 | 1,047 | 2.59375 | 3 | [] | no_license | import pickle
from featureExtractor import ekstractFeatures as ef
class Forest:
def __init__(self):
self.forest = pickle.load( open("forest.p", "rb") )
def classify(self, features):
return self.forest.predict([features])
class SGD:
def __init__(self):
self.sgd = pickle.load( open("SGD.p", "rb") )
def clas... | true |
559e17facaadc0f71d8fbdfd3817d73f2bd0acdf | Python | Catarina607/Python-Lessons | /5_40.py | UTF-8 | 522 | 3.5 | 4 | [] | no_license |
cost_factory = float(input(' COST FACTORY U$S: '))
if cost_factory < 12.000:
value = cost_factory + (cost_factory * (5/100))
print(f'TOTAL COST US$: {value}')
elif cost_factory == 12.000 or cost_factory <= 25.000:
value = cost_factory + (cost_factory + (10/100)) + (cost_factory *(15/100))
pr... | true |
bde535b8c7e321d2bc5f0582e984c82200383a25 | Python | qianrongping/python_xuexi | /Python_基础/python_for.py | UTF-8 | 1,171 | 4.34375 | 4 | [] | no_license | """
《代码题》
2、
2.使用 for 循环遍历字符串 "ILoveYou",并打印每一个字符当字符串为 "e" 的时候终止循环:
"""
# i = "ILoveYou"
# for n in i:
# if n == 'e':
# break
# print(n)
"""
《代码题》
4. 编写代码模拟用户登陆。要求:用户名为 python,密码 123456,如果输入正确,打印“欢迎光临”,程序结束,
如果输入错误,提示用户输入错误并重新输入(使用while循环即可)
while True:
accounts = input('请输入账号:')
passws = inp... | true |
9bf2992cb7e74a738e33229c1de3d461b33f0ebb | Python | OpenSourceIronman/Limonada | /Limonada-Backend/RPi/GPIO.py | UTF-8 | 419 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
"""
"""
BOARD = 1
OUT = 1
IN = 0
HIGH = 1
LOW = 0
def setmode(a):
print(a)
def setup(a, b):
print(a)
def output(pin, state):
print("Simulated: ", state, "output on pin /#", pin)
def input(pin):
state = LOW
print("Simulated: ", state, "sensed on input pin /#", pin)
def cleanup():... | true |
6c34a9caba98f7a2c266b0c6f546135c203e447e | Python | nsmith0310/Programming-Challenges | /Python 3/LeetCode/lc954.py | UTF-8 | 751 | 2.984375 | 3 | [] | no_license | class Solution:
def canReorderDoubled(self, A: List[int]) -> bool:
A.sort()
i = 0
while i<len(A)//2:
if A[i]<=0:
try:
if A[i]%2==0:
ind = A.index(A[i]//2)
del A[ind]
del A... | true |
be1a6d60f96aa0250659f2a1f069456b6dfdb444 | Python | sizzlelab/Arki | /MestaDB/scripts/test_content_post_multipart.py | UTF-8 | 9,940 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import sys
import os
import httplib
import random
import string
import datetime
import hmac
import base64
import hashlib
CRLF = '\r\n'
BUFFER_SIZE = 32*1024
class Handler:
"""Base class for all multipart handlers."""
def __init__(self):
self.length = 0
self.data = '... | true |
872b132cddebce986b234a88d635849b84c5abd9 | Python | pavelkomarov/big-holes-in-big-data | /bigholes/HoleFinder.py | UTF-8 | 12,962 | 3.046875 | 3 | [] | no_license | import numpy
from itertools import product
from pickle import dump
from types import MethodType
from datetime import datetime
from multiprocessing import cpu_count
from joblib import Parallel, delayed
from .HyperRectangle import HyperRectangle
## This class implements a monte-carlo-based polynomial-time algorithm for ... | true |
0946051bbb1252db26f122773dc8d6767a3c79a8 | Python | Emmersynthies/CIT228 | /Chapter4/stats.py | UTF-8 | 273 | 3.734375 | 4 | [] | no_license | import random
number = random.randrange(10,100)
numList = list(range(number))
print(numList)
print("Largest number: ", max(numList))
print("Smallest number: ", min(numList))
print("Total numbers: ", sum(numList))
print("The average number: ", sum(numList)/len(numList))
| true |