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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
849a2fdf44397c065660f4aade3876157bc151b9 | Python | PraderioM/GamePlatform | /backend/games/common/models/game.py | UTF-8 | 4,849 | 2.703125 | 3 | [] | no_license | import abc
import asyncpg
import json
from random import shuffle
from typing import Dict, List, Optional
from .game_component import GameComponent
from .play import Play
from .player import Player
class Game(GameComponent):
def __init__(self, current_player_index: int,
play_list: List[Play], pla... | true |
093ea03d92d9d774665cd2979e23c66da9f05968 | Python | kongzhidea/leetcode | /Number Complement.py | UTF-8 | 307 | 2.640625 | 3 | [] | no_license | class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
bx = bin(num)
r = ["0","b"]
for i in xrange(2,len(bx)):
r.append( "0" if bx[i] == "1" else "1")
bx = "".join(r)
return int(bx,2)
| true |
7eaa163d63b43cf819083a1b513400dbe10b6c76 | Python | dalong2018/PythonDemo | /biaoqingbao/kk.py | UTF-8 | 615 | 3.203125 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
#Generate a random number, you can refer your data values also
data = np.random.rand(4,2)
rows = list('1234') #rows categories
columns = list('MF') #column categories
fig,ax=plt.subplots()
#Advance color controls
ax.pcolor(data,cmap=plt.cm.Reds,edgecolors='k')
ax.set_x... | true |
8cd83465a977d5e097b01c80d61d907234555b1c | Python | hairuo55/TTS-frontend | /src/text_normalizer/car_number.py | UTF-8 | 1,490 | 3.515625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
@Descripttion:
@Author: Markus
@Date: 2020-04-16 14:07:51
@LastEditors: Markus
@LastEditTime: 2020-04-16 15:44:10
"""
import re
from src.text_normalizer.digit import digit_normalize
SHORT_PAUSE_SYMBOL = " " # 短停顿文本标志
LONG_PAUSE_SYMBOL = " " # 长廷顿文本标志
class CarNumber:
def __init__(s... | true |
71cb93c4b91b4b2cceae396e559fd844d856f3d6 | Python | Openwarfare/PyXbee | /pyxbee_src/pyxbee/datatypes.py | UTF-8 | 3,331 | 2.9375 | 3 | [] | no_license | #TODO:These types need to be reworked so they make more sense and are easier to use.
#the current implementation is clumsy and need to be refined. Think about moving
#the validators into the type and only storing the value in the type. Right now the
#value is stored in the type and or the InputField value which is we... | true |
3fbc16c21fbb0aa892d070f9c52cef481610349e | Python | reconstruir/bes | /lib/bes/text/line_continuation_merger.py | UTF-8 | 4,182 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.system.log import log
from ..system.check import check
from .text_line import text_line
class _state(object):
def __init__(self, parser):
self.name = self.__class__.__name__[1:]
log.add_logging(self, tag = ... | true |
018ef0025a77f0f251ebf0c5e1006d45dfad79ca | Python | SMS-NED16/crash-course-python | /python_work/chapter_10/exercises/10_5_programming_poll.py | UTF-8 | 564 | 3.6875 | 4 | [] | no_license | """
Asks users to enter their resaons for liking programming
Stores responses in a file called 'responses.txt'
"""
filename = "text_files/responses.txt"
entry_flag = True
while entry_flag:
print("Welcome to our programming survey. Enter 'q' to quit at any time.")
user_response = input("Why do you like programming?... | true |
af581ee8c424cd64be7252a647376ccd980ecd64 | Python | hglad/easygan | /easygan/nets/CGen.py | UTF-8 | 2,547 | 2.75 | 3 | [] | no_license | import torch.nn as nn
import torch
class CGen(nn.Module):
def __init__(self, n_classes=26, c=64):
super(CGen, self).__init__()
"""
Generates 90 x 160 x 3 image using labels (h, w, c)
"""
self.embed = nn.Sequential(
nn.Embedding(n_classes, 50),
nn.L... | true |
9769ef32fe53a03e7e3b855079f25c2f7d7944ff | Python | mitmedialab/sherlock-project | /tests/test_helpers.py | UTF-8 | 1,308 | 3.03125 | 3 | [
"MIT"
] | permissive | from unittest import TestCase
from sherlock.features.helpers import literal_eval_as_str, keys_to_csv
class Test(TestCase):
def test_literal_eval_as_str(self):
s1 = "['Krista Construction Ltd.', None, None, None, \"L'Expert de Parcs J. Aubin Inc.\", 'Lari, Construction', 0.89]"
result = literal_ev... | true |
a562facf57fc473cd928d40891c093c567f7ec2f | Python | TheBFR/AutomateBoring | /listLoop.py | UTF-8 | 1,045 | 3.8125 | 4 | [] | no_license | myList = [1,2,3,4,5]
for i in range(len(myList)):
print (myList[i])
print ("1 is in list myList in index slot",myList.index(1))
# if you do this and there are repeats then it will just return index of first occurrence
print(myList)
myList.append(6)
print(myList)
myList.insert(2,15)
print(myList)
myList.remo... | true |
53b1e4d417128d0c7282c23278af38658ce84259 | Python | Jordi-Ab/Dissertation | /1D/FFT/1dFFT_main.py | UTF-8 | 1,907 | 3.28125 | 3 | [] | no_license |
# coding: utf-8
from math import *
import numpy as np
from scipy.integrate import ode
from scipy.fftpack import fft
import FiringRate as fr
import ConnectivityKernel as ck
import NeuralFieldFFT as nf
import matplotlib.pyplot as pt
import warnings
warnings.simplefilter("ignore")
# Spatial Grid
nx = (2**10)-1 # Number... | true |
8630abed2511888ac398537c308f36a2ae6a8a61 | Python | TaRyu/fx | /exam/data_features.py | UTF-8 | 3,527 | 2.78125 | 3 | [] | no_license | """此程序提取了特征值和目标值。时间尺度为24个交易日。"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
import numpy as np
FX_LIST = ['EURUSD', 'USDJPY', 'GBPUSD']
FILE_PREX = '../../../data/fx'
NUM_PIX = 24 * 24
SCALE = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def ... | true |
43bd989f78c86ad99ceec5beaa575bbcfaeae45c | Python | hyunseok4384/Data | /tmp/Placeholder.py | UTF-8 | 242 | 2.65625 | 3 | [] | no_license | import tensorflow as tf
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b
sess = tf.Session()
print(sess.run(adder_node, feed_dict = {a:3, b:4.5}))
print(sess.run(adder_node, feed_dict = {a:[1,3], b:[2,4]}))
| true |
c94dde3d0cb307853554114b8ee9f9c3706e9013 | Python | sudhanshu-jha/Scrapers | /Product-Info-Crawler/product_info_crawler/spiders/olx.py | UTF-8 | 2,324 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request
import re
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
raw_html.encode('ascii','ignore')
cleantext = re.sub(cleanr, '', raw_html)
cleantex... | true |
66e29ac4046f865c82d790732fe674884af92dc4 | Python | heonmono/JustDoIT | /Programming/Algorithm/FastCampus/DP_DC.py | UTF-8 | 1,227 | 4.09375 | 4 | [] | no_license | # 동적 계획법 & 분할 정복(Divide and Conquer)
'''
동적 계획법(Dynamic Programming
작은 문제 해결 후 , 큰 부분을 해결하여 알고리즘만드는 것
최하위 해답 구한 후 저장하여 상위 문제 해결
Memoizaition 기법 - 이전 계산 값 저장하여 다시 계산하지 않아 빠르게됨
분할 정복(Divide and Conquer)
문제를 나누어 합병하여 문제의 답을 얻는 방식
하양식 접근법으로, 아래로 내려가면서 하위 해답 구현 - 재귀함수 사용
문제를 잘게 쪼갤때 부분 문제는 서로 중복되지 않음 ex) 병합정렬 퀵정렬
... | true |
83a66e83f8dbd8fba0e2cd3af33d297e5b96013e | Python | leejjoon/mpl_toolkits.agg_filter | /mpl_toolkits/agg_filter.py | UTF-8 | 5,004 | 2.640625 | 3 | [] | no_license | import numpy as np
def smooth1d(x, window_len):
# copied from http://www.scipy.org/Cookbook/SignalSmooth
s=np.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]]
w = np.hanning(window_len)
y=np.convolve(w/w.sum(),s,mode='same')
return y[window_len-1:-window_len+1]
def smooth2d(A, sigma=3... | true |
5fe8fb90d314190b7b5042218ac50b84e9e5c4e1 | Python | CyberPunkRavi/semi-supervised-bayesian-classifier | /classifier.py | UTF-8 | 9,062 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 14:04:38 2018
@author: Alexandre Boyker
"""
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
from helper import plot_confusion_matrix
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
class NaiveBayesSemiSupervis... | true |
1408afb90cb1ff056d640762cbc27a010426775d | Python | ej2/pixelpuncher | /pixelpuncher/player/utils/avatar.py | UTF-8 | 2,052 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | import random
from django.db.models import Q
from pixelpuncher.player.models import AvatarLayer, PlayerAvatar
from annoying.functions import get_object_or_None
def get_unlocked_layers_by_type(player, layer_type):
ids = player.layers.filter(layer__layer_type=layer_type).values_list('layer__id', flat=True)
lay... | true |
5863183924cfca3fe4e04b80ba2303b8eec0701f | Python | fabricST/Learn_python3 | /Home_Work_5/H_W5_P1_1.py | UTF-8 | 1,617 | 4.71875 | 5 | [] | no_license | # Person (два свойства: 1. теперь full_name пусть будет свойством, а не функцией (одно поле, мы ожидаем - тип строка и
# состоит из двух слов «имя фамилия»), а свойств name и surname нету, 2. год рождения).
# Реализовать методы, которые:
# • выделяет только имя из full_name
# • выделяет только фамилию из full_name;
#... | true |
6359cf4632b5072b64c08639e0e2dd3618c6da7f | Python | t7ahaa00/Parkissa-projekti | /Computer_vision/AWS/awsFindSlots.py | UTF-8 | 1,147 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 11:44:14 2020
@author: Antti
"""
import json
from Freeslot import Freeslot
from io import BytesIO
def checkFreeSlots(cars, slotsFilePath, s3Session, bucket):
slots=[]
free_slots = []
busy_slots=[]
s3 = s3Session.resource("s3")
bucket =... | true |
ba00d28af4b4b762c381f5a7ef5c0c0bf76d321e | Python | nguyennhatminh-mgr/MC-Assignment1 | /initial/src/test/ParserSuite.py | UTF-8 | 33,223 | 3.046875 | 3 | [] | no_license | import unittest
from TestUtils import TestParser
class ParserSuite(unittest.TestCase):
def test_simple_program(self):
"""Simple program: int main() {} """
input = """int main() {}"""
expect = "successful"
self.assertTrue(TestParser.checkParser(input,expect,281))
def test_more_c... | true |
39ed958788340ea3385ed61e23a9f115b29c628d | Python | thejonathanvancetrance/Alfalfa | /API.py | UTF-8 | 41,161 | 3.125 | 3 | [
"MIT"
] | permissive | ######
#imports
######
# general
import statistics
import datetime
from sklearn.externals import joblib # save and load models
import random
# data manipulation and exploration
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
## machine learning stuff
# preprocessing
from sklear... | true |
7cd4282c58dc99b65c308f5353fe45b79a84a64a | Python | asdf2014/algorithm | /Codes/gracekoo/49_group-anagrams.py | UTF-8 | 454 | 3.46875 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
# @Time: 2020/2/20 00:01
# @Author: GraceKoo
# @File: 49_group-anagrams.py
# @Desc:https://leetcode-cn.com/problems/group-anagrams/
import collections
class Solution:
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(so... | true |
e99e582b478f2097a4acce8d0fc5c9d837cb422f | Python | Udit107710/CompetitiveCoding | /Codeforces/Contest1294/D.py | UTF-8 | 157 | 2.6875 | 3 | [] | no_license | from sys import stdin
t, x = map(int, stdin.readline())
arr = []
for _ in range(t):
arr.append(int(stdin.readline()))
new_arr = sorted(arr)
| true |
fcf163325a6a444010b58657e5ded7c45a23a08f | Python | mo-oq/tkseem | /tkseem/test.py | UTF-8 | 390 | 3.03125 | 3 | [
"MIT"
] | permissive | from .util import remove_tashkeel
import unittest
class TestUnit(unittest.TestCase):
def test_tashkeel(self):
self.assertEqual(remove_tashkeel("مِكَرٍّ مِفَرٍّ مُقبِلٍ مُدبِرٍ مَعًا")
, "مكر مفر مقبل مدبر معا", "Remove Tashkeel is not working")
unittest.main(argv=['first-arg-is-ign... | true |
0a6d9ecdb48d0db8b1101db135463416644e2bbe | Python | HerMelin84/165 | /week2/wordcounter.py | UTF-8 | 276 | 2.875 | 3 | [] | no_license | from sys import argv
def word_counter():
for i in argv[1:]:
with open(i) as f:
lc = 0
for c,line in enumerate(f):
for line in line.split():
lc += 1
print i +": " + str(lc)
word_counter()
| true |
ea28363d770f1263b51bf2ae3d0b679fa54b72e9 | Python | houyinhu/AID1812 | /pythonNet/sock_attr.py | UTF-8 | 452 | 2.96875 | 3 | [] | no_license | from socket import *
s = socket()
#对套接字设置为立即重用端口
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
print(s.getsockopt(SOL_SOCKET,SO_REUSEADDR))
print(s.family) #地址类型
print(s.type) #套接字类型
s.bind(('0.0.0.1',8888))
print(s.getsockname())#获取绑定的addr
print(s.fileno()) #获取文件描述符
s.listen(3)
c,addr = s.accept()
print(c.getpeern... | true |
a5e02a5deda11cfbf6e00255c3eeb4c0245a2c16 | Python | BilllYang/Alphacat_bot | /fsm.py | UTF-8 | 5,458 | 2.875 | 3 | [] | no_license | from transitions.extensions import GraphMachine
class TocMachine(GraphMachine):
def __init__(self, **machine_configs):
self.machine = GraphMachine(
model = self,
**machine_configs
)
def is_going_to_start_state(self,update):
text = update.message.text
retu... | true |
4843a8e0d1b827040f5c21c39cdc2e59137b8ad4 | Python | AdamJSoftware/iti1120 | /assignments/A4/pt2/a4_Q3_300166171.py | UTF-8 | 864 | 3.78125 | 4 | [] | no_license | # ITI1120 Assignment 4 - PT 2 -2
# Adam Jasniewicz 300166171
def longest_run(array):
'''
array -> array of floats
Returns the length of the longest run
'''
last_run = None;
run_lengths = []
same_run = False
if len(array) != 0:
for run in array:
if run == last_run:
... | true |
985e6e2e8224c22dd49e9f1673dcb2ce3d2956c6 | Python | Cloudbeast/NYU_Python | /chartype.py | UTF-8 | 301 | 4.25 | 4 | [] | no_license | print("Enter a character: ")
s = input()
result = "a digit."
if s.isalpha():
if s.isupper():
result= "an upper case letter."
else:
result="a lower case letter."
elif s.isdigit()== False:
result="a non-alphanumeric character."
print(s, " is ", result, sep="")
| true |
cd3725178e6e441e69220df3793d755e1b780f2d | Python | mrudula-pb/Python_Code | /CS62/calculate_MeanMedianRange.py | UTF-8 | 1,102 | 4.46875 | 4 | [] | no_license |
#Part 4: Define a function to calculate the mean, median, and range (range = max-min) of a
# given list of numbers
# #hint: use the 'statistics' library for mean and median import statistics my_list = [1,3,5,4,2,6,8,4,8,9,11]
import statistics
class Solution:
def calculate_MeanMedianRange(self, lst):
# Me... | true |
dee74de934b998b5cfcc8a35c707409fdbdd831a | Python | schneiderfelipe/python-warrior | /pythonwarrior/abilities/explode.py | UTF-8 | 704 | 3.015625 | 3 | [
"MIT"
] | permissive | from pythonwarrior.abilities.base import AbilityBase
class Explode(AbilityBase):
def description(self):
return("Kills you and all surrounding units."
" You probably don't want to do this intentionally.")
def perform(self):
if self._unit.position:
self._unit.say("exp... | true |
6b77b3bd9f1763f29c2abbb0fb90638f639aa93b | Python | arupiot/UDMI-dummy | /Interface.py | UTF-8 | 3,728 | 2.703125 | 3 | [
"MIT"
] | permissive | import curses
from curses.textpad import Textbox, rectangle
from curses import wrapper
from time import sleep
import threading
SPACE_CHAR = 32
TITLE_ROW = 0
AUTOSEND_INFO_ROW = 3
MESSAGE_INFO_ROW = 4
KEYMAP_START_ROW = 5
SENDING_ROW = 8
TOPIC_INFO_START_ROW = 13
BROKER_INFO_START_ROW = 14
EXIT_START_ROW = 16
class In... | true |
4c532d2b44cf83117862b1af98de3ce4dac54219 | Python | j0k/algopractice | /qsort/qs2.py | UTF-8 | 5,383 | 2.71875 | 3 | [] | no_license | # 19.06.2017
A = [1,2,3,4,5,6,7,8,4,44,44,3,33,1,1,-1]
def qsort(a):
return a if len(a)<= 1 else \
qsort(filter( lambda x: x <= a[0], a[1:])) + \
[a[0]] + \
qsort(filter( lambda x: x > a[0], a[1:]))
# myLang
# qsort(a): a if len(a)<= 1 else qsort( a( # <= a[0] ) ),a[0],qsort( a( # > a[0... | true |
db0c2c01568eac5defcacda1b174455e44c9729a | Python | Divisekara/Python-Codes-First-sem | /PA1/PA1 2015/pa1-19-2015.py | UTF-8 | 577 | 3.578125 | 4 | [] | no_license | def five_check(L):
u=0
d=0
for i in range(0,4):
diff=L[i]-L[i+1]
if diff<0:
u+=1
elif diff>0:
d+=1
if u==4:
return "upward"
elif d==4:
return "downward"
else:
return "unpredictable"
while True:
try:
L=map(int,r... | true |
272208357731dcdaaed993fdaa4348c4aea3d6ae | Python | HiPERCAM/hipercam | /hipercam/scripts/makeflat.py | UTF-8 | 18,744 | 2.671875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import sys
import os
import tempfile
import signal
import numpy as np
from trm import cline
from trm.cline import Cline
import hipercam as hcam
from hipercam import utils, spooler
__all__ = [
"makeflat",
]
####################################################
#
# makeflat -- makes flat fields from a set of fram... | true |
ad22cc995f67c82ab97d4e572311f56be8756113 | Python | ladysilverberg/IN1000 | /Oblig 2/egenoppgave.py | UTF-8 | 2,149 | 3.65625 | 4 | [] | no_license | # Oppgave:
# Lag et quiz-program som stiller spørsmål til brukeren, sjekker om de er
# riktige og teller poeng.
def still_sporsmaal(tekst):
if type(tekst) == str:
print("---------------------------")
print(tekst)
return input()
else:
print("Sporsmaalet er ikke en streng-variabel... | true |
d5dcf19a5cda95c3277cb1f23d93f0fccad685ed | Python | juntakahashi777/PersonalWebpage | /server.py | UTF-8 | 849 | 2.5625 | 3 | [] | no_license | from flask import *
app = Flask(__name__)
import os
import json
@app.route("/delete")
def delete_url():
jsonFile = open("myWebsites.json", "r");
data = json.load(jsonFile);
index = request.args.get('index');
data["links_1"].pop(int(index)-1);
jsonFile = open("myWebsites.json", "w");
json.dump(data, jsonFile);
... | true |
6278262bade9f0eb966089c8546e27003676a5e0 | Python | samuelsandoval1/CSSI-2019 | /Python/make-a-short-story/mystory.py | UTF-8 | 382 | 3.28125 | 3 | [] | no_license | print "MAD LIBS"
noun1 = raw_input("Enter a noun: ")
adjective1 = raw_input("Enter an adjective: ")
noun2 = raw_input("Enter a noun: ")
noun3 = raw_input("Enter a noun: ")
verb1 = raw_input("Enter a verb ending in -ingx: ")
print ("The " + noun1 + " hopped over a " + adjective1 + noun2 +". Then the " +
noun3 + "de... | true |
6bd16d725bc615d9279eda923b5f5db4c416468e | Python | BaymaxBei/data-structure | /str/find_largest_substr.py | UTF-8 | 759 | 3.578125 | 4 | [] | no_license |
'''
找到字符串中的最大不重复子串,返回长度
'''
def find_longest_unrepeat_substr(string):
max_len = 0
start_index = 0
num_dict = {}
index_dict = {}
for i, s in enumerate(string):
s_num = num_dict.get(s, 0)
if s_num>0:
s_index = index_dict[s]
for j in range(start_index, s_inde... | true |
ad4b42d4d5c050b8cba325e17e017bfee49a6cd5 | Python | haroldhyun/Algorithm | /Machine Learning/k-means.py | UTF-8 | 1,589 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 17:45:52 2021
@author: Harold
"""
import numpy as np
def km_assignment_step(data, Mu):
""" Compute K-Means assignment step
Args:
data: a NxD matrix for the data points
Mu: a DxK matrix for the cluster means locations
... | true |
c802304debff7ecf34d0b84b313898b37c245484 | Python | rchenhyy/whatever | /iter/my_iterator.py | UTF-8 | 349 | 3.765625 | 4 | [] | no_license | class MyIterator:
def __init__(self, start, end):
self._next = start
self._end = end
def __iter__(self):
return self
def next(self):
if self._next > self._end:
raise StopIteration()
n = self._next
self._next += 1
return n
for i in MyIte... | true |
9d37237e048025389ab9add585fcd8969b28aba7 | Python | santigo171/learning-python | /loops/potency2.py | UTF-8 | 435 | 4.0625 | 4 | [] | no_license | # ciclo while
def run(number, limit):
potency = 0
result = number ** potency
while result <= limit:
print(str(number) + "^" + str(potency) +
" = " + str(result))
potency = potency + 1
result = number ** potency
if __name__ == "__main__":
number = int(input("Qué n... | true |
60315d32f887dad49689121b2350d25729fbdb48 | Python | elados93/AI_Ex1 | /BFS.py | UTF-8 | 1,170 | 3.53125 | 4 | [] | no_license | from TilePuzzleLogic import backtracking
class BFS_Seaerch(object):
"""
BFS_Seaerch using to search level by level in a given graph.
The search method using the logic given in the constructor.
"""
def __init__(self, logic):
self._logic = logic
def search(self, init_state):
... | true |
34993894bb9026746701ae562257c5e4c9b81030 | Python | reywridyll/Soteria | /HaarAnalyser.py | UTF-8 | 2,805 | 2.640625 | 3 | [] | no_license | #- import the necessary packages -#
import numpy as np
import cv2
# Load video
video = cv2.VideoCapture(f'data/distance_test.mp4')
# Load cascade
body_cascade = cv2.CascadeClassifier('haar/cascade.xml')
# Configure blob detection
params = cv2.SimpleBlobDetector_Params()
# Change thresholds
params.minThreshold = 20... | true |
e5ebcef20cb0a046c1f4cfa86276e043b11fd39c | Python | DineshNadar95/FE-520 | /Assignment-2/Temp.py | UTF-8 | 416 | 3.25 | 3 | [] | no_license | # def is_palindrome(x,y):
# # add your code here
# print(x)
def count_char(x):
count = 0
dict1 = {}
for i in x:
if i in dict1:
count = dict1[i]
count = count + 1
dict1[i] = count
else:
dict1[i] = 1
return dict1
... | true |
a4cba11c1e63734363deaac1bb1047b4a0007782 | Python | dduong42/ud120-projects | /naive_bayes/nb_author_id.py | UTF-8 | 844 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python
"""
this is the code to accompany the Lesson 1 (Naive Bayes) mini-project
use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import os.path
import sys
from time import time
BASE = os.path.dirname(os.path.d... | true |
2745f8d77c81d803424fa5904367e7728d5a7f86 | Python | iCodeIN/algorithms-9 | /solutions/Dynamic Programming/UniquePathsInGrid.py | UTF-8 | 1,142 | 3.25 | 3 | [] | no_license | ## Website:: Interviewbit
## Link:: https://www.interviewbit.com/problems/unique-paths-in-a-grid/
## Topic:: Dynamic Programming
## Sub-topic::
## Difficulty:: Easy
## Approach:: f(i, j) = f(i-1, j) + f(i, j-1)
## Time complexity:: O(N^2)
## Space complexity:: O(N)
## Notes::
## Bookmarked:: No
class Solution:
# ... | true |
c4ceda67c10ab551545ef1ec46954f0375952abc | Python | usop7/Python_OOP_Projects | /Lectures/1031/annotation.py | UTF-8 | 123 | 2.71875 | 3 | [] | no_license | # it's not enforced. it's just for developers communication.
def add(num1: int, num2: int) -> int:
return num1 + num2
| true |
7a93e5e9a68014df3d2586a723a189f1f76388a6 | Python | cmquintanilla/escuelas-database | /Evaluacion01/functionsCE.py | UTF-8 | 4,271 | 3.453125 | 3 | [
"Apache-2.0"
] | permissive | import mongoDB as MongoDB
def welcome():
print(120 * '*')
print("* Welcome to Evaluacion01, this program was created for learning purposes and it's a CRUD for School Center Management *")
print("* For this scenario we are using MongoDB and ATLAS for the persistence of the Data", 35 * ' ', '*')
print(1... | true |
134cfc5b2e6e7596235cb917c01a80bd38756a99 | Python | HarshitaSingh97/FetchGoogleTrends | /PygTrends.py | UTF-8 | 6,095 | 2.5625 | 3 | [] | no_license | from pytrends.request import TrendReq
from datetime import datetime
from dateutil.relativedelta import relativedelta
import pandas as pd, requests
class fetchtrends:
latlng="0,0"
def __init__(self,keywords,latitude=None,longitude=None,time=None):
self.keywords = keywords#['asthma','air']... | true |
2bd77734dde340cc4d52f1e42b3935e390e94ced | Python | hidoos/learn-python | /practise/small.py | UTF-8 | 109 | 3.109375 | 3 | [] | no_license | def small(*args):
sum = 0
for i in args:
sum += i
return sum
print small(1,2,3,4,5,10)
| true |
9ce2c1cc2089488e1a32286d6385904e3329b2e2 | Python | aarondizele/python | /learning.py | UTF-8 | 607 | 3.34375 | 3 | [] | no_license | import sys
# d = {'a': 'Maman', 'b': 'Papa', 'c':'Grand Father', 'd': 'Grand Mother', 'e': 'Son', 'f': 'Daughter'}
# for k in sorted(d.keys()):
# print('Key '+k.upper()+' -> '+d[k])
# print(d.items()[0])
def File(filename):
f = open(filename, 'rU')
for line in f:
a = line.split()
... | true |
635440fa976f5ef5bf9060974e87f2920ea48738 | Python | jfarid27/mcmc-NeuralNetworks | /titanicKaggle.py | UTF-8 | 1,252 | 2.921875 | 3 | [] | no_license | import procedures.crossValidate as cV
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import procedures.neuralNetworks as NN
##Defaults
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
target = "Survived"
class Titanic():
def dataClean(self):
data = pd.read_csv(".... | true |
a5af7b264c97b0e0ee14296d5461216bd3288021 | Python | Ritapanda9009/htrc-feature-reader | /htrc_features/transformations.py | UTF-8 | 1,639 | 2.6875 | 3 | [] | no_license | import numpy as np
def chunk_to_wem(chunk_tl, model, vocab=None, stop=True, log=True, min_ncount=10):
''' Take a file that has ['token', 'count'] data and convert to a WEM vector'''
if 'token' in chunk_tl.columns and not 'token' in chunk_tl.index.names:
chunk_tl = chunk_tl.set_index('token')[['cou... | true |
8d33d0e9b842f8fb5deb6147c080f159dffbf9e5 | Python | mellykath/CodingChallenges | /unit_converter.py | UTF-8 | 542 | 4.03125 | 4 | [] | no_license |
type_of_unit_being_entered = input("Enter type of unit being converted ie celsius, farenheit")
type_of_unit_being_converted_to = input("Enter type of unit to convert to")
value_of_input = input("Enter value")
if type_of_unit_being_entered == "celsius" and type_of_unit_being_converted_to == "farenheit":
value_of_... | true |
9c365a3a57f2d21e8ff93f487c6c16fccf7c3d9b | Python | mcneel/rhino-developer-samples | /rhinocommon/snippets/from_rhinocommon/py/ex_addlayer.py | UTF-8 | 1,460 | 3.109375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | import Rhino
import scriptcontext
import System.Guid, System.Drawing.Color
def AddLayer():
# Cook up an unused layer name
unused_name = scriptcontext.doc.Layers.GetUnusedLayerName(False)
# Prompt the user to enter a layer name
gs = Rhino.Input.Custom.GetString()
gs.SetCommandPrompt("Name of layer ... | true |
24876d25612203b05d6e21e6d893217a27a47718 | Python | Ayu-99/python2 | /session22(a).py | UTF-8 | 1,062 | 3.296875 | 3 | [] | no_license | # Asynchronous -> Parallel(May Lead to mixed output)
# Synchronous -> When there are multiple threads and they are accessing the same shared object, then we need
# synchronisation
import threading
import time
# Lock Object
lock = threading.Lock()
class Printer:
def printDocuments(self, docName, times):
l... | true |
cd6ace2300b75f43b07860fd84070d17944ed0f8 | Python | iChaos26/DP-Study | /Observer/Observer.py | UTF-8 | 299 | 2.890625 | 3 | [] | no_license | class Subject:
def __init__(self):
self.__observers = []
def register(self, observer):
self.__observers.append(observer)
def notifyAll(self, *args, **kwargs):
for observer in self.__observers:
observer.notify(self, *args, **kwargs)
| true |
9d16b6db58ec2f3c9312a0b4d47f90ec13d7c7f6 | Python | mola1129/atcoder | /contest/abc157/D.py | UTF-8 | 337 | 2.921875 | 3 | [
"MIT"
] | permissive | n, m, k = map(int, input().split())
friend = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
friend[a - 1].append(b - 1)
friend[b - 1].append(a - 1)
block = [[] for _ in range(n)]
for _ in range(k):
c, d = map(int, input().split())
block[c - 1].append(d - 1)
block[d - ... | true |
b95eaa738c17ae8de5223cbe5b88f05bb799e22b | Python | muhammedameen/Inf_Sec_RUG | /set1/exercise3.py | UTF-8 | 275 | 3.375 | 3 | [] | no_license | import sys
from string import ascii_lowercase as ALPHABET
def shift(message, offset):
trans = str.maketrans(ALPHABET, ALPHABET[offset:] + ALPHABET[:offset])
return message.lower().translate(trans)
print(shift(input("Input message you would like encrypted:\n"), 19)) | true |
3e9c01dd8348d4d0697c2ff6f4aa4f8636f680ef | Python | dabingsun/MS-DHCP | /Experiments/UNSWNB15/LSTM/LSTM10.py | UTF-8 | 7,081 | 2.6875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 08:12:12 2019
@author: dabing
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import time as run_time
from sklearn.metrics import confusion_matrix
from loadData import trainFeatures,trainLabels_10,testFeatures,testLabels_10 ... | true |
0de3b86e5d107b279cdef04ef23bb769473137b8 | Python | ahmadrezare2/Summer-2021-Pre-Django | /Max,Min.py | UTF-8 | 256 | 3.75 | 4 | [] | no_license | list=[]
x1=int(input("Enter your first number: "))
x2=int(input("Enter your second number: "))
x3=int(input("Enter your third number: "))
list.append(x1),list.append((x2)),list.append((x3))
list.sort()
print("max is: ",list[-1])
print("min is: ",list[0])
| true |
ab77e6bfd0490f15efd6b3180561775914c73941 | Python | lance-shi/TextEditorPython | /mainMenu.py | UTF-8 | 1,766 | 3.09375 | 3 | [] | no_license | from tkinter import *
from tkinter import filedialog
class MainMenuPanel:
def __init__(self, root, txtEdit):
self.root = root
self.txtEdit = txtEdit
self.mainMenu = Menu()
self.root.config(menu=self.mainMenu)
fileMenu = Menu()
self.mainMenu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(... | true |
2db8679736a0ed8948dc374237b31a2a86a5258c | Python | jpltechlimited/Edukatronic | /0007/armToChessBoardInterface.py | UTF-8 | 3,989 | 2.828125 | 3 | [] | no_license | from roboarm import Arm
import time
class ArmToChessBoardInterface:
def __init__(self):
self.arm = Arm()
self.vendor = 0x1267
self.bmRequestType = 0x40
self.bRequest = 6
self.wValue = 0x100
self.wIndex = 0
self.sleep_time = 1
self.BASE_RIGHT = 1,
... | true |
ad759c35865c55c62274e4b79e6a874220ef1835 | Python | Payalkumari25/GUI | /tempCodeRunnerFile.py | UTF-8 | 142 | 2.75 | 3 | [] | no_license | top.title("2nd window")
img = ImageTk.PhotoImage(Image.open("D:/Tkinter/images/pink.png"))
my_label = Label(top,image=img).pack()
| true |
6362e79bc00f6be4b6fb17a62bfd4b22d3bbc988 | Python | hbzhang/computervisionclass | /imageprocessing/elipse.py | UTF-8 | 1,290 | 2.9375 | 3 | [] | no_license |
from skimage import data, color, img_as_ubyte
from skimage.feature import canny
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter
import matplotlib.pyplot as plt
from skimage import io
# Load picture, convert to grayscale and detect edges
#image_rgb = io.imread('cup.png')
image_r... | true |
bba1d012d7a2c543eb01c7f75fc5c1dc47615234 | Python | didwns7347/algotest | /알고리즘문제/1699번 제곱수의 합.py | UTF-8 | 220 | 3.03125 | 3 | [] | no_license | import sys
n=sys.stdin.readline().strip()
n=int(n)
dp=[0]*(n+1)
for i in range(1,n+1):
dp[i]=i
j=1
while j*j<=i:
if dp[i] > dp[i-j*j]+1:
dp[i] = dp[i-j*j]+1
j += 1
print(dp[n])
| true |
5a6dd998b6f92ca2ca9b557a208d78a6b7d0f4b3 | Python | TKfong/CMPE200-Enigma | /enigma.py | UTF-8 | 6,843 | 3.015625 | 3 | [] | no_license | #! /usr/bin/env python3
import sys
from easygui import *
class Enigma:
# Constructor/Initialize Enigma machine
def __init__(self, set1, set2, set3):
self.numcycles = 0
self.rotors = []
# Settings for the machine
# We locked in only 3 rotors
self.rotorsettings = [("III", set3),
("II",... | true |
bb7dfbf9dcfb19894ec4946a9e5bcffa6276b5db | Python | tasosval/flask-simpleldap | /tests/conftest.py | UTF-8 | 933 | 2.71875 | 3 | [
"MIT"
] | permissive | import pytest
from flask import Flask
from flask_simpleldap import LDAP
from config import BaseConfig
@pytest.fixture(scope='class')
def app(request):
'''A Flask application object with an automatically pushed context
It is also configured by the BaseConfig object
The scope for this is class, so we don't ... | true |
cec3f58d2993869bae6db6df12c527b9c175efa8 | Python | Deeshant2234/comm | /coding/codes/conv/Prev_stage.py | UTF-8 | 1,262 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 7 08:51:42 2017
@author: hemanth
"""
#Starts from the current decoded state, takes input as minimum distance to
#reach that state and previous state And returns previous state and decoded
#information bit corresponding to that state.
import numpy as np
def prev_stage(... | true |
b9d23de8f6ff2827787afd433cb958c8b2fd0145 | Python | RunSi/South_Asia_Programmability | /funcs.py | UTF-8 | 103 | 2.96875 | 3 | [] | no_license | def add(num1, num2):
result = num1 + num2
return result
def say_hello():
print("Hello!")
| true |
b345226d47ad4faeaff87aa532c0d8da3d81da82 | Python | FastStonewkx/SpiderPython | /Code/requests_repo/RegularExp/sub2.py | UTF-8 | 273 | 2.875 | 3 | [] | no_license | import re
html = open("example.html", 'r', encoding='UTF-8')
try:
file_text = html.read()
# print(file_text)
result = re.findall('<li.*?>\s*?(<a.*?>)?(\w+)(</a>)?\s*?</li>', file_text, re.S)
for res in result:
print(res[1])
finally:
html.close() | true |
e90d8b71761be3642fa653865e432b521bc8dec7 | Python | Ben-Baert/Exercism | /python/sublist/sublist.py | UTF-8 | 513 | 3.390625 | 3 | [] | no_license | SUBLIST = 1
SUPERLIST = 2
EQUAL = 3
UNEQUAL = 4
def is_sublist(lst1, lst2):
if not lst1 or any(lst1 == lst2[i:i+len(lst1)] for i in range(len(lst2))):
return True
return False
def is_superlist(lst1, lst2):
return is_sublist(lst2, lst1)
def check_lists(lst1, lst2):
if lst1 == lst2:
ret... | true |
770339eb3c8822bea339733ce6713319cf3f32a0 | Python | 18F/snap-api-prototype | /snap_financial_factors/deductions/medical_expenses_deduction.py | UTF-8 | 3,914 | 3.140625 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | from snap_financial_factors.deductions.deduction_result import DeductionResult
class MedicalExpensesDeduction:
'''
Calculates medical expenses deduction for households that include a member
who is over 60 years old, blind, or disabled.
'''
def __init__(self,
household_includes_el... | true |
b277f65bd0fcf7f0351caf35b52e560833c9dbbe | Python | SalimRR/- | /5_2.py | UTF-8 | 455 | 4.09375 | 4 | [] | no_license | a = int()
b = int()
def maximal(a, b):
"""Напишите целочисленные значения a и b"""
help(maximal)
a = int(input('Введите целое число для а: '))
b = int(input('Введите целое число для b: '))
if a > b:
print('max = ', a)
elif b>a:
print('max = ', b)
else:
pri... | true |
40661169d7affd5e9b8d790362f6c8265e21ff75 | Python | Nyapy/TIL | /04_algorithm/18day/0906/(2819)격자판의숫자이어 붙이기.py | UTF-8 | 770 | 3 | 3 | [] | no_license | def dfs(x, y, k, n):
global cnt
if k == 7:
if visit[n] != tc:
cnt += 1
visit[n] = tc
return
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= 4 or ny < 0 or ny >= 4: continue
dfs(nx, ny, k + 1, n * 10 + data[nx][ny])... | true |
5eee1c88d77e2bf4db286328b4c2a5f53a420e7b | Python | BalajiShivakumar/Python | /FGame.py | UTF-8 | 72 | 3.421875 | 3 | [] | no_license | numbers = [5, 2, 5, 2, 2]
for output in numbers:
print("x" * output) | true |
869ed0e9b729a8676890b80b95990c49765829b0 | Python | wufanyou/WRL-Agriculture-Vision | /utils/losses/hybird.py | UTF-8 | 3,067 | 2.5625 | 3 | [
"MIT"
] | permissive | import torch.nn as nn
from torch import Tensor
from typing import Optional
from .lovasz_loss import CustomizeLovaszLoss, LovaszLoss
from .binary_cross_entropy import (
MaskBinaryCrossEntropyIgnoreIndex,
MaskBinaryCrossEntropy,
)
from .dice_loss import CustomizeDiceLoss
from .jaccard import CustomiseJaccardLoss
... | true |
8f17fdbeef89f5a5c60dbf0f0f0014f097aecb56 | Python | mayra1228/LearnSpider | /Demo9.py | UTF-8 | 738 | 2.921875 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time : 2018/9/26 下午5:21
# @Author : mayra.zhao
# @File : Demo9.py
import re
# 字符集的匹配
# a = re.match(r'[0-9]',"123456")
# print a.group()
#from typing import Match
# . 表示任一字符,除了\n
# a = re.match(r'...','123')
# print a.group()
a = re.match(r'[0-8]?[0-9]','95')
print a.g... | true |
f09e455e36b78e4a15c3fe5797fe651f3fc95fce | Python | vippermanu/new_mal_domain_profile | /fig_sys_4_22now/fig_sys_4_22 -now/models/detect_results.py | UTF-8 | 11,655 | 2.640625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from Base import Base
class QueryDetectResut(Base):
"""
第三方接口检测域名恶意性结果查询类
"""
def __init__(self):
Base.__init__(self)
@staticmethod
def extract_maltype(single_result,default_type):
"""
提取安全类... | true |
608d17df7bae73e3f6d84734bedb86552b31209e | Python | cameronpepe/cs-3600-projects | /Project+4b/Project 4b/cpepe3_project4b/Testing.py | UTF-8 | 3,633 | 2.703125 | 3 | [] | no_license | from NeuralNetUtil import buildExamplesFromCarData,buildExamplesFromPenData, buildExamplesFromXorData
from NeuralNet import buildNeuralNet
import cPickle
from math import pow, sqrt
import sys
import getopt
def average(argList):
return sum(argList)/float(len(argList))
def stDeviation(argList):
mean = average(... | true |
809a56b96fda9c78d9b91fb1e931543c67a88b69 | Python | vimarshc/SVGedit | /myarea.py | UTF-8 | 2,051 | 3.09375 | 3 | [] | no_license | def curvy(l):
q = l.split()
list = abs(q)
return list
def areacal(l):
q = l.split()
list = abs(q)
ar = 0
for x in list:
ar = ar + area(x[0],x[1],x[3],x[4],x[5],x[6],x[7],x[8])
return ar*(-1)
def area(x0,y0,x1,y1,x2,y2,x3,y3):
area = (3.0/10.0)*y1*x0 -... | true |
709a5540b99e26e7fb1f3a4e0859aad01ac592b9 | Python | nhardy/etude-01 | /main.py | UTF-8 | 5,601 | 3.84375 | 4 | [] | no_license | #!/usr/bin/env python3
"""
Etude 1: Ants on a Plane
Authors: Kimberley Louw, Nathan Hardy
Simulation of creatures related to Langton's Ant.
"""
import re
import sys
# Mathematical convention of directional step to coordinate
_DIRECTIONS = {
'N': (0, 1),
'E': (1, 0),
'S': (0, -1),
'W': (-1, 0),
}
# O... | true |
9a165730486ed2037ee753eb62431c4586769c14 | Python | jubaer145/jina | /jina/jaml.py | UTF-8 | 8,560 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | import collections
import os
import re
from types import SimpleNamespace
from typing import Dict, Any
import yaml
from yaml import MappingNode
from yaml.composer import Composer
from yaml.constructor import ConstructorError, FullConstructor
from yaml.parser import Parser
from yaml.reader import Reader
from yaml.resolv... | true |
40be1aaee875dc1389c6435d6152d6e4f6a16333 | Python | AlPus108/Python_lessons | /Generators/3_generator_functions.py | UTF-8 | 21,728 | 3.640625 | 4 | [
"MIT"
] | permissive | # ГЕНЕРАТОРЫ
# Генераторы, это итераторы. При помощи генераторов мы можем перебирать какой-то iyerable
# Не каждый итератор является генератором.
# Но, все генераторы являются итераторами.
# Генераторы могут быть созданы при помощи ф-и generator
# Так же, генераторы могут быть созданы при помощи generator expressions (... | true |
4d4a379d90ff7d9a0664384ba11068dff0bbff8f | Python | dgrzan/MarketAnalysis | /Project2/project2.py | UTF-8 | 2,452 | 3.046875 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import random
from matplotlib.backends.backend_pdf import PdfPages
from scipy import stats
import math
from scipy.special import factorial
from scipy.optimize import curve_fit
def poisson(k,lamb):
return (lamb**k/factorial(k)) * np.exp(-lamb)
if __name__ == "__ma... | true |
b4c63c94e828515b809719fb8f2f263f5685375c | Python | stang84/Debug | /jupyter-image-display-error/rename.py | UTF-8 | 386 | 3.1875 | 3 | [] | no_license | import os
import glob
ext = input("Enter file extension type: ")
while not ext[0].isalpha():
ext = input("Enter file extension type after the '.': ")
cap = ext[0].isupper()
n = len(ext)
if cap:
ext = ext.lower()
else:
ext = ext.upper()
files = glob.glob('*.'+ ext)
for file in files:
print(file, 'con... | true |
b4e93311b5d410c4625e4374d3963bd363ad90c0 | Python | pbuzzo/Craigslist-Scraper | /scraper.py | UTF-8 | 5,535 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given at least one webpage,
search for certain price points and products availability routinely.
"""
from bs4 import BeautifulSoup
import requests
# import schedule
import time
from datetime import datetime
import logging
import argparse
import sys
import signal
__... | true |
bd75b49f0b1f036a1a975dece9b37d906a71de45 | Python | DiamondHusky/CrawlerDemo | /02DataStorage/mongo_demo/demo1.py | UTF-8 | 994 | 2.796875 | 3 | [] | no_license |
import pymongo
# 获取连接mongodb的对象
client = pymongo.MongoClient("127.0.0.1",port=27017)
# 获取数据库(如果没有zhihu数据库,也可以)
# db = client.wade
db = client['admin']
db.authenticate('sa', 'sa')
# 获取数据库中的表(qa也可以不存在)
collection = db.qa
# 写入数据
# collection.insert({"username":"靓仔"})
collection.insert_many([
{
"userna... | true |
a971b0b7d1f1c8dae84b7e3b34dbe9f6053a4be7 | Python | Rutrle/The-Self-Taught-Programmer-by-Althoff | /chapter_6/ch_6_challenge_5.py | UTF-8 | 352 | 3.78125 | 4 | [] | no_license |
given_list = ["The", "fox", "jumped", "over", "the", "fence", "."]
created_string = " ".join(given_list)
#not needed, but general solution to these types of problems
while " ." in created_string:
rest = created_string[created_string.index('.'):]
created_string = created_string[:created_string.index('.')-... | true |
b4d3267a45ab0c1cb43266580168ee404df56fb7 | Python | WweiL/LeetCode | /93-restore_IP_addr.py | UTF-8 | 693 | 2.765625 | 3 | [] | no_license | class Solution:
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
if len(s) > 12:
return []
ans = []
self.addr("", ans, 4, s, 0)
return ans
def addr(self, tmp, ans, numBlock, s, i):
n = len(s)
... | true |
938f870aaba3f9f61388a3c337501e6111d42868 | Python | laurenriddle/The-Family-Dictionary-practice-python-bk1-ch5 | /family_dict.py | UTF-8 | 718 | 4.875 | 5 | [] | no_license | # Define a dictionary that contains information about several members of your family.
my_family = {
"sister": {
"name": "Krista",
"age": 42
},
"mother": {
"name": "Cathie",
"age": 70
},
"father": {
"name": "James",
"age": 75
}
}
# Using a dictiona... | true |
09c5c60793a285b26c7c353f8887ab88f36f1de2 | Python | zinderud/ysa | /sklearn/breast-cancer.py | UTF-8 | 787 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive |
import numpy as np
from sklearn.preprocessing import Imputer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import pandas as pd
veri = pd.read_csv("data.data")
veri=veri.replace('?', -222, inplace='true')
veri=veri.drop(['id'], axis=1)
y = veri.benormal
x = veri.drop(... | true |
92f4e9a1718e129e581de6542cd2275286f5fe33 | Python | uhmppi1/RL_Edu1 | /lecture/lab6/cartPoleNN.py | UTF-8 | 3,383 | 2.625 | 3 | [] | no_license | import numpy as np
import tensorflow as tf
import gym
import matplotlib.pyplot as plt
env = gym.make('CartPole-v0')
input_size = env.observation_space.shape[0]
layer1_size = 10
layer2_size = 10
output_size = env.action_space.n
#learning_rate = 1e-1 # counts per episode: 9.5085
learning_rate = 1e-2 # counts per epis... | true |
870fddb371579f6cf5821541c33880df41be5327 | Python | melodyyyang/practice | /app/id_generator.py | UTF-8 | 134 | 2.578125 | 3 | [] | no_license | class IdGenerator():
def __init__(self):
self._id = 0
def next(self):
self._id += 1
return self._id
| true |
b1dae475a34de880906c27ae5ef4b44b9a4b4f28 | Python | Rogerwlk/Information-Retrieval-Search-Engine | /P2/P2/query_static.py | UTF-8 | 11,137 | 2.84375 | 3 | [
"MIT"
] | permissive | import re, html, nltk, os, argparse, time
from w3lib.html import replace_entities
from nltk.stem.porter import PorterStemmer
from math import log
from math import sqrt
from collections import Counter
# global variable
idx_table = {}
docu_table = {}
stop_words = set()
def dotAcronym(match):
temp = match.... | true |
36ea02dc6997960bd94e33ada00d24606ab8d8d6 | Python | UCMHSProgramming16-17/final-project-jbrual | /Pokemon.py | UTF-8 | 2,372 | 3.515625 | 4 | [] | no_license | # Q: What are the stats of a given type of Pokemon?
# Import the appropriate modules.
import csv, requests, operator, pandas as pd, numpy as np
from bokeh.plotting import figure, output_file, save
from bokeh.charts import Bar, output_file, save
from bokeh.palettes import Accent4 as pal
# Reach the API by building its ... | true |
21b57f4ce2736ce33da95beac78acebf28ed26fa | Python | abackes19/portfolio | /wallfollowing.py | UTF-8 | 989 | 2.796875 | 3 | [] | no_license | # welcome to wall following !
# using analog and digital sensors, it will follow a wall
import setup
import RoboPiLib as RPL
import time
now = time.time()
future = now
motorL = 0
motorR = 2
right = 19
front = 16
left = 17
analogL = 1
rgo = 2000
lgo = 1000
# ^ setup
RPL.servoWrite(motorR, rgo)
RPL.servoWrite(mot... | true |
45c38c233238ed44fc9f248636756686e65cc0bb | Python | ilya144/tweets_webservice | /application/maind.py | UTF-8 | 1,125 | 2.8125 | 3 | [] | no_license | from idbclient import Database
from iparser import TweetParser
from flask import Flask, render_template
from threading import Thread
import time
app = Flask(__name__)
class ParserThread(Thread):
def __init__(self, parser_tweet: TweetParser):
Thread.__init__(self)
self.parser_tweet = par... | true |