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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
92312205c049ffaf0bd7c4b93e7ba091a7c72d4b | Python | sahaavi/AI-Algorithms | /graph_traversal_algorithms.py | UTF-8 | 4,940 | 2.546875 | 3 | [
"MIT"
] | permissive | graph = {
"Arad": {"Zerind": 75, "Timisoara": 118, "Sibiu": 140},
"Zerind": {"Arad": 75, "Oradea": 71},
"Oradea": {"Zerind": 71, "Sibiu": 151},
"Timisoara": {"Arad": 118, "Lugoj": 111},
"Lugoj": {"Timisoara": 111, "Mehadia": 70},
"Mehadia": {"Lugoj": 70, "Dobreta": 75},
"Dobreta": {"M... | true |
9bb9c1954d1a1046514371984a72ea846228c65f | Python | aeozge/CodecademyProjects | /areacalculator.py | UTF-8 | 707 | 4.28125 | 4 | [] | no_license | """This program calculates the area of circle, triangle and rectangle."""
from math import pi
print("The program is running :)")
option = input("Enter C for Circle or T for Triangle or R for Rectangle")
if option == 'C':
radius = float(input("Enter radius :"))
area = pi * radius**2
print (("The area of circle: %f"... | true |
a6b632d6125722eb858567e26e97e96b7d3da186 | Python | lym20220107/pyphlan | /excel.py | UTF-8 | 537 | 2.65625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
#Author: Duy Tin Truong (duytin.truong@unitn.it)
# at CIBIO, University of Trento, Italy
from openpyxl import Workbook
from openpyxl import load_workbook
import os
def table2xlsx(table, ofn, mode = 'write'):
if mode == 'append' and os.path.exists(ofn):
workbook = load_workbook(ofn)
... | true |
0f45054456cc84a6c7e17d2bace59ab1dbcc9597 | Python | XrXr/RapidPygame | /rapidpg/types/player.py | UTF-8 | 1,404 | 3.125 | 3 | [
"MIT"
] | permissive | # Rapid Pygame
# https://github.com/XrXr/RapidPygame
# License: MIT
from .animation import Animated, Animation
from pygame.rect import Rect
class Player(Animated):
"""
An instance is compatible with the level manager. Note that if
:func:`rapidpg.levelmgr.collision.Level.update` is not used, a player
... | true |
9807a86d435965dc48d64661a26812ad25d3a83f | Python | MarwanAhmed20/BFS-and-DFS-multiagent- | /multiagent.py | UTF-8 | 15,785 | 2.671875 | 3 | [] | no_license | import simpleguitk as simplegui
# Constants
HEIGHT = 400
WIDTH = 500
NODE_SPACE_ALLOWANCE = 20
EDGE_COLOR = "Yellow"
EDGE_SIZE = 2
NODE_LABEL_COLOR = "White"
NODE_COLOR = "white"
NODE_MARK_COLOR = "Green"
# Global variables
start = 0
goal = 0
placeNodes = True
setNodesRelation = False
draw_relations ... | true |
3b0a3865299625984d800d78fbea7be9b0e03b0f | Python | avcordaro/animated-reinforcement-learning | /tests/integration/agents/test_agent_policy_iter_with_env.py | UTF-8 | 1,387 | 2.796875 | 3 | [] | no_license | import pytest
import sys
sys.path.extend([".", "..", "../..", "../../.."])
from model.agent_policy_iter import AgentPolicyIter
from model.environment_frozenlake import FrozenLake
@pytest.fixture(scope="module")
def agent():
pytest.env = FrozenLake(False)
pytest.agent = AgentPolicyIter(pytest.env, gamma=0.9)
... | true |
0f4bb59ac2285b8a34b4b150a4c14e5984f93d40 | Python | yannikschaelte/SSA | /ssa/output.py | UTF-8 | 2,514 | 3.046875 | 3 | [
"MIT"
] | permissive | from abc import ABC, abstractmethod
import numpy as np
class Output(ABC):
@abstractmethod
def __init__(self):
super().__init__()
self.t_max = None
def create_empty(self):
return Output()
def initialize(self, t0, x0, t_max):
self.t_max = t_max
def finalize(self):
... | true |
1f0a7e0903b8a71bc8f7154f7631d3b3d753cbf1 | Python | zhlee0824/LearnPython | /Learn_diction.py | UTF-8 | 338 | 3.40625 | 3 | [] | no_license |
student = {"name":"Jimmy", "age":35, "course":["History", "CompSci"]}
student["phone"] ="555-5555"
student.update({"name":"John", "age":36})
print(student.get("phone", "Not Found"))
#del student["age"]
print(student)
print(student.pop("course"))
print(student.items())
for key, value in student.items():
print("D... | true |
5c6ecd6d7f3771db4ab2b5db3d79ff4b3109aeab | Python | farzmas/FairNet | /Fairness Perception/codes/data_loader.py | UTF-8 | 1,137 | 2.65625 | 3 | [] | no_license | import networkx as nx
import pandas as pd
import numpy as np
def W_gen(adj, y):
k1 = adj.dot(y)
k0 = adj.dot(1-y)
W = np.zeros(adj.shape)
n = adj.shape[0]
for i in range(n):
if y[i] == 1 and k1[i] > 0:
for j in range(n):
if adj[i,j] == 1:
W[i,... | true |
bfd72379a3f152b3fc17d876ea4060148a278263 | Python | diegogonzalezmaneyro/car-charge-handler | /charge_point/save_rfid.py | UTF-8 | 175 | 2.75 | 3 | [] | no_license | import time
rfid = str(input("ingrese RFID tag:"))
line_to_save = '{};{}\n'.format(rfid,time.time())
with open('rfid_inputs.txt', 'a') as file:
file.write(line_to_save)
| true |
86578081d6f108abcd47b9d03f9db91776be57de | Python | Shadat-tonmoy/DeepLearningNanoDegreeUdacity | /NeuralNetworks/projects/SentimentAnalysis/NLTK/01.Intro.py | UTF-8 | 729 | 3.953125 | 4 | [] | no_license | from nltk.tokenize import word_tokenize,sent_tokenize
'''
Stuff can be done with NLTK
01. Tokenizing - Word Tokenizer : Separates by works, Sentence Tokenizer : Separates by Sentences
02. Corpora - Body of text like Medical Journals, Presidential Speeches
03. Lexicons - Words and their meaning
Meaning can be diff... | true |
4cb313d545c72940577bb3718cc95021335c49e6 | Python | ericl1ericl/Notre-Dame | /cse40647/hw1/elayne-hw1-4-2.py | UTF-8 | 2,099 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env python2.7
# Eric Layne
# CSE40647
# hw1-4-2
import csv
import numpy as np
from scipy import stats
import pandas as pd
from sklearn.decomposition import TruncatedSVD
import matplotlib.pyplot as plt
score1 = [None]*150
score2 = [None]*150
score3 = [None]*150
score4 = [None]*150
genres = [None]*150
with... | true |
f502c4fe9368f47bd170104ab8530ceccd2fabe4 | Python | theRainMaster/Python | /Demo-itmo/mod_4_Input_Output/json_person.py | UTF-8 | 682 | 2.90625 | 3 | [] | no_license | import json
filename = 'person.json'
info = {
"ФИО": "Иванов Иван Петрович",
"Рейтинг": {
"Знания": 90,
"Умения": 85,
"Навыки": 80
},
"Возможности": ["Аккуратность", "Стрессоустойчивость"],
"Возраст": 35.5,
"Хобби": None
}
# Запись структуры в файл в JSON-формате
with ... | true |
d8af6df9b360c5d2c136bcd16dd325d145214ca1 | Python | tofis/human4d_dataset | /importers/offsets.py | UTF-8 | 233 | 2.671875 | 3 | [
"MIT"
] | permissive | def load_rgbd_skip(filename, folder):
f = open(filename)
f_lines = f.readlines()
skip = 0
for line in f_lines:
if (folder in line):
skip = int(line.split('\t')[1])
break
return skip | true |
9af02b78164438c35e036689910d9952bae95b08 | Python | foliant-docs/foliant | /foliant/config/path.py | UTF-8 | 1,195 | 2.578125 | 3 | [
"MIT"
] | permissive | from pathlib import Path
from yaml import add_constructor
from foliant.config.base import BaseParser
class Parser(BaseParser):
def _resolve_path_tag(self, _, node) -> str:
'''Convert value after ``!path`` to an existing, absolute Posix path.
Relative paths are relative to the project path.
... | true |
830f56c050b9b72ec8129d519641fe4f280237db | Python | Audarya07/Daily-Flash-Codes | /Week2/Day5/Solutions/Python/prog1.py | UTF-8 | 81 | 3.5 | 4 | [] | no_license | for i in range(1,101):
if i%3==0 or i%5==0:
print(i,end=" ")
print()
| true |
6187e22714dabe44b65e07a24419d8bccfa08e4d | Python | MohanSha/PyTaskAutomation | /youtubecrawl.py | UTF-8 | 5,109 | 2.734375 | 3 | [
"MIT"
] | permissive | from __future__ import unicode_literals
import requests
from bs4 import BeautifulSoup
import youtube_dl
"""Deinition of MyLogger class used by youtube-dl to print the message status"""
class MyLogger(object):
"""docstring for MyLogger"""
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self,... | true |
56eaef5fc054f127d3f155f86c119e5a65f04672 | Python | feinglong/PythonVideoPoker | /scripts_poker/gain.py | UTF-8 | 5,637 | 3.140625 | 3 | [] | no_license | import pandas as pd
from machine import *
# Décomposition des cartes de la main du joueur
def decompose_jeu(tirage):
dic = {}
indices = range(len(tirage))
valeur =[]
couleur= []
for i,x in zip(indices, tirage):
dic[i] = x.split('-')
for x in dic:
valeur.append(dic[x][0])
... | true |
b30512ce969975e8a9ec020eff198d421d671431 | Python | niteshkumar0205/predictiing-billboad-hits-using-spotify-data-deploy | /app.py | UTF-8 | 1,610 | 2.859375 | 3 | [] | no_license | import streamlit as st
from PIL import Image
import pickle
import numpy as np
pickle_in = open("forest_model1.pkl", "rb")
model = pickle.load(pickle_in)
def main():
img=Image.open('Billboard_Hot_100.jpg')
img=img.resize((267,176))
st.image(img, use_column_width=False)
st.title("BillBoard Hit Predictor... | true |
ce6f32167074e9c9bdaa4e6bfc8f99cbdbb4e378 | Python | nightlan1015297/Algrothims | /[Dynamic_Programing]Coin_Change.py | UTF-8 | 1,028 | 3.625 | 4 | [] | no_license | """
Question Discribe:
You have m types of coins available in infinite quantities
where the value of each coins is given in the array S=[S0,... Sm-1]
Can you determine number of ways of making change for n units using
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
def Coin_Chan... | true |
8519f362d59f4a4e1baba52bac4cf13959694083 | Python | Aasthaengg/IBMdataset | /Python_codes/p03048/s612886121.py | UTF-8 | 235 | 2.828125 | 3 | [] | no_license | r,g,b,n = map(int,input().split())
ans = 0
for i in range(n+1):
for j in range(n+1):
tmp = (r*i)+(g*j)
if tmp > n:
break
else:
if (n-tmp)%b == 0:
ans += 1
print(ans) | true |
dd739b158e1f33647e30e71a6007c14d7815647c | Python | Tb243/Tempbase | /src/database/model/model.py | UTF-8 | 469 | 2.53125 | 3 | [] | no_license | from database.database import ActiveDatabase
from datetime import datetime
class Model:
def __init__(self, debug=False):
self.debug = debug
def query(self, query, args, fetch=False):
if self.debug:
print("DB: " + query)
ActiveDatabase.cursor.execute(query, args)
ActiveDatabase.connection.commit()
if ... | true |
157687ac93b09f1d7099b79aacf651bd20e523e6 | Python | lingyongyan/bootstrapnet | /core/graph.py | UTF-8 | 7,081 | 2.71875 | 3 | [] | no_license | # coding=UTF-8
"""
@Description:
@Author: Lingyong Yan
@Date: 2019-07-24 01:00:10
@LastEditTime: 2019-08-28 08:20:17
@LastEditors: Lingyong Yan
@Python release: 3.7
@Notes:
"""
import torch
import numpy as np
import math
PAD = '<pad>'
class BootGraph(object):
def __init__(self, vocab_e, vocab_p):
self.vo... | true |
3f2eb5bcd746028624fbf7a1b75bf563bb1c8c78 | Python | rafaelperazzo/programacao-web | /moodledata/vpl_data/133/usersdata/162/41056/submittedfiles/al15.py | UTF-8 | 97 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
for i in range(1000,10000,1):
i1=i//100
i2=i%100
print(i1+i2) | true |
6fbae5ba1b2890eb07fc5fd7c7babf33883bbdfa | Python | dalejandroM/PROYECTO-ELECTRONICAPP | /ventanaOhm.py | UTF-8 | 2,792 | 2.78125 | 3 | [] | no_license | import sys
from PyQt5.QtWidgets import QDialog, QApplication, QMessageBox
from ventanaui import *
from leyde import *
def error(texto):
msg = QMessageBox()
msg.setWindowTitle("Error")
msg.setText(texto)
x = msg.exec_()
class leyohm(QDialog):
def __init__(self):
super... | true |
14344c531c7376d4973e4fb323bfc37e25d234ad | Python | sivanagireddyb/python | /exceptraise.py | UTF-8 | 332 | 3.234375 | 3 | [] | no_license | #!/usr/bin/python
def function(level):
if level<1:
raise Exception(level)
#this code below is not excecuted
#if we raise exception
else:
print ("its tru so exception not raised")
return level
try:
i=function(-10)
# i=function(6)
print("level", i)
except Exception as e:
print("error in level arg" ,... | true |
5392a3d066c7c478ec7d332e960d7ab8b4180dff | Python | hanpengwang/ProjectEuler | /6 (Sum square difference).py | UTF-8 | 218 | 3 | 3 | [] | no_license | def squareDiff(l):
from functools import reduce
sumSquare = sum([num**2 for num in l])
squareSum = ((l[0] + l[-1]) * len(l) / 2 )**2
return squareSum - sumSquare
print(squareDiff([i for i in range(101)][1:]))
| true |
549e780b23cdafedb6b1d829c73ba9e808cbd16c | Python | LissanKoirala/Games-Python | /Decision maker.py | UTF-8 | 727 | 3.78125 | 4 | [] | no_license | # Creator : Lissan Koirala
# Date of Creation : 09/03/2019
import random
import time
print("DECISION MAKER")
print("THIS IS THE FINAL ANSWER, YOU HAVE TO ACCEPT THIS!")
time.sleep(1)
print("Computer Thinking...")
time.sleep(0.5)
print("In 3...")
time.sleep(1)
print("In 2...")
time.sleep(1)
print("In ... | true |
4574976a47b279d3f683a0488c8d2a926fd37942 | Python | bridgesra/active-manifold-icml2019-code | /src/functions/testing_plotting_functions.py | UTF-8 | 11,007 | 2.578125 | 3 | [] | no_license | import csv, os, sys
import numpy as np
import csv, os, sys
import time
import math
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
sys.path.insert(0, 'src')
import functions.ground.base_am_fxns as bf #anthonys base functions
import functions.fast_funcs as ff #mikis optimized base/ma... | true |
26e105e4a5f8b89a00a6fe07fe02994df92a3031 | Python | MGDas/tasks | /arabic_roman_number.py | UTF-8 | 881 | 4.15625 | 4 | [] | no_license | """
Задача:
На вводе подаётся строка, содержащая натуральное число n, 0 < n < 4000
(пример: 1950
На выходе строка, содержащая число, закодированное в римской системе счисления.
Ответ:
Мы делаем таблицу соответствий арабских и римских чисел.
Идя по таблице этих соответствий мы уменьшая арабское число и увел... | true |
2f7235710d02c9eab184e469b04b4ccd953c7139 | Python | CodeSteak/untypy | /untypy/impl/dummy_delayed.py | UTF-8 | 1,093 | 2.515625 | 3 | [
"MIT"
] | permissive | from typing import Any, Optional
from untypy.error import UntypyTypeError
from untypy.interfaces import TypeChecker, CreationContext, TypeCheckerFactory, ExecutionContext
class DummyDelayedType:
"""
This class is used for raising delayed type checking errors.
"""
pass
class DummyDelayedFactory(Type... | true |
c1c66fc5d3adbc72387b19efa237d05a6fb32ed7 | Python | logan-lach/Algos | /DP/zeroes_ones.py | UTF-8 | 284 | 3.21875 | 3 | [] | no_license | def countBinarySubstrings(s: str) -> int:
"""
About maximizing the number of 0's to the left of the breakpoint, and the number of ones to the right of the breakpoint
:param s:
:return:
"""
one_tracker = [0] * len(s) + 1
for i in range(len(s)):
| true |
899b41f0cf4ff61a9acf11a88b73f899a98cd248 | Python | rschlaefli/17hs-bsc-thesis-clean | /code/02_MODELLING/models/ModelHelpers.py | UTF-8 | 20,377 | 2.75 | 3 | [] | no_license | import os
import pathlib
import numpy as np
import pandas as pd
import time
import pickle
import arrow as ar
from pymongo import MongoClient
from sklearn import preprocessing
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Embedding, Flatten, LSTM, Conv1D, MaxPooling1D
from ker... | true |
82d1d51d0e345fc1a9ba908123f2ec46929f1b59 | Python | haidarknightfury/PythonBeginnings | /100Days/Day10- Automate Boring Stuffs/orderfiles.py | UTF-8 | 721 | 3.328125 | 3 | [] | no_license | import shutil, os, sys
def moveFiles(destFolder, extension):
"""
method to move files in a directory with a specific extensions to a destFolder
"""
if destFolder not in os.listdir():
os.mkdir(destFolder)
for fileName in os.listdir():
if fileName.lower().endswith(extension):
... | true |
2ff9bc07bc1740c0a6d7a367044b6a1705ef8f31 | Python | mozayed/Network_Automation | /configure_routers.py | UTF-8 | 1,889 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python
from getpass import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException
#getting username and password for SSH connection to the devices
user... | true |
0ebe2179a967423d8f4a2cd2e0809837490c44a4 | Python | kfrancischen/leetcode | /python/140_word-break-II/wordBreakII.py | UTF-8 | 1,150 | 3.1875 | 3 | [] | no_license | from collections import defaultdict
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
if not wordDict:
return []
dp = defaultdict(list)
maxLen = max(len(w) for w in wor... | true |
2dfd8f7214b0b521d2e92ccc1ddbe65896f2dbff | Python | dinesh121991/DinProgram | /Python/inheritance_oop.py | UTF-8 | 1,312 | 3.890625 | 4 | [] | no_license | #!/bin/python
import random
class Card:
""" Card class object with
object attributes: rank, suit
class attributes : rank_names, suit_names """
rank_names = [None,"1","2","3","4","5","6","7","8","9","10",
"Jack","Queen","King"];
suit_names = ["club","spade","diamond","heart"];
def __init__(self, rank = 1, sui... | true |
f16726ef221d6834d4fee158f2b5c82b5bb2ec83 | Python | monkrobot/test_project | /Coursera/MFTI Python course/Week_5.py | UTF-8 | 593 | 2.71875 | 3 | [] | no_license | #import time
#import os
#
#pid = os.getpid()
#
#while True:
# print(pid, time.time())
# time.sleep(2)
#import time
#import os
#
#pid = os.fork()
#
#if pid == 0:
# while True:
# print("child:", os.getpid())
# time.sleep(5)
#else:
# print("parent:", os.getpid())
# os.wait()
import socket
so... | true |
3b2bcfd993bbc564a0ee40e214a583e603073ccc | Python | kartik-soni1707/Image-Processing | /Hough Tansformation.py | UTF-8 | 447 | 2.59375 | 3 | [] | no_license | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img=cv.imread('40.jpg')
img=cv.resize(img,(512,512))
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
edge=cv.Canny(gray,150,250,apertureSize=3)
lines= cv.HoughLinesP(edge,1,np.pi/180,100,minLineLength=100,maxLineGap=10)
for l in lines:
x1,y1,x2,y2=l[0... | true |
973b078eac18a3a6e6c96df1c6569d8a7db75f32 | Python | deven96/sage-py | /sage/core/utils.pyi | UTF-8 | 32,201 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | """sage.core.utils - Consist of utility class for the `sage` API.
@author
Victor I. Afolabi
Artificial Intelligence & Software Engineer.
Email: javafolabi@gmail.com | victor.afolabi@zephyrtel.com
GitHub: https://github.com/victor-iyiola
@project
File: utils.pyi
Created on 28 Januar... | true |
7ffc1ba77fa26195d6005fc4f6170599d73f75ba | Python | walker8088/flython | /imu.py | UTF-8 | 2,115 | 2.671875 | 3 | [] | no_license | import math, time
from algorithm import *
class IMU(object):
def __init__(self, gyro_accel, compass):
self.gyro_accel = gyro_accel
self.compass = compass
self.pitch = 0.0
self.roll = 0.0
self.yaw = 0.0
self.quad_fusion = QuadFusion()
self.dc... | true |
24d1622b8291bba7ed0a2123c44971eba15135db | Python | LathanDevers/daniels_bd1 | /misc/Tests.py | UTF-8 | 1,968 | 2.640625 | 3 | [] | no_license | #TESTS
from Main import *
def tests():
print("SELECT TESTS")
SPJRUD2sqlite3('myDB.db', Select(Attr('A1'), Const('Charles'), Rel('R1')))
SPJRUD2sqlite3('myDB.db', Select(Attr('A2'), Attr('A3'), Rel('R1')))
SPJRUD2sqlite3('myDB.db', Select(Attr('A1'), Attr('A2'), Rel('R2')))
SPJRUD2sqlite3('myD... | true |
c27103282e46a8ffb68ac4452997be9d70f245cc | Python | RenanRibeiroDaSilva/Meu-Aprendizado-Python | /Exercicios/Ex102.py | UTF-8 | 2,142 | 4.78125 | 5 | [
"MIT"
] | permissive | """ Ex - 102 - Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que
indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será
mostrado ou não na tela o processo de cálculo do fatorial.
"""
# Como... | true |
2fd44daa84c1e5daa9d40bc387d13594343d3632 | Python | meliatiya24/Python_Code | /Lawas/Python/prima.py | UTF-8 | 341 | 3.140625 | 3 | [] | no_license | a=int(input())
if a>1:
for i in range (2,a):
print(i)
if (a % i)==0:
print("bukan")
break
else:
print("iya")
break
print("===================")
print("no4")
b=int(input("masukkan angka"))
for i in range (b):
if i%2==0:
... | true |
2993cc0527f53670e2b7bb5f4f4693bfbd96c00e | Python | HolkerDev/PyScripts | /sort_images_by_filename.py | UTF-8 | 2,103 | 3 | 3 | [] | no_license | import os
RAW_DATA_DIR = '/Users/holker/University/Diploma/Processing/images' # path where raw non-sorted images are located
MIN_AGE = 12 # minimum age for sorting
# parse filenames and sort files by gender
def sort_genders():
for filename in os.listdir(RAW_DATA_DIR):
if filename != 'female' \
... | true |
c9c5f068e033474ce16307e159f52e1ed7a567f4 | Python | xudshen/forest | /forest/forest_source.py | UTF-8 | 2,920 | 2.640625 | 3 | [
"MIT"
] | permissive | __author__ = 'xudshen@hotmail.com'
from enum import Enum
import requests
from lxml import etree
from bs4 import BeautifulSoup
from selenium import webdriver
from forest.forest_factory import ForestAbsFactory
from forest.logger import ForestError
class HttpMethod(Enum):
GET = 0
POST = 1
@classmethod
... | true |
d5e2e77ba0c73f660f5bfc84f5e9f1e00ccb2b13 | Python | Randika97/AI-Collection-Neural-Networks- | /Neural networks/single_LayeredNn.py | UTF-8 | 1,408 | 3.5625 | 4 | [] | no_license | from numpy import array, exp, random, dot
class NeuralNetwork:
def __init__(self):
self.synaptic_weights = 2*random.random((3, 1))-1
# Sigmoid
def __sigmoid__(self,x):
return 1/(1+exp(-x))
# Sigmoid rate of change
def __sigmoid_derivative__(self, x):
return x*(1 - x)
... | true |
b491d88d314d1cd99d62188994af05f984905af5 | Python | NONameToo/qiushiSpider | /qiushiSpider.py | UTF-8 | 5,407 | 3.203125 | 3 | [] | no_license | # coding:utf-8
# 使用多线程爬虫
from threading import Thread,Lock
from queue import Queue
from lxml import etree
# 爬取数据类
class Spiders(Thread):
def __init__(self, crawl, page_queue):
super().__init__()
self.crawl = crawl
self.page_queue = page_queue
def run(self):
print('启动%s线程' % ... | true |
f1af4da1850733842464734151a5830a1bc60a32 | Python | eeng321/python-study | /sort_dictionary_values.py | UTF-8 | 220 | 3.5625 | 4 | [] | no_license | # sort values in dictionary
d = {"Pierre": 42, "Anne": 33, "Zoe": 24}
#sorted_d = sorted(d.items(), key=lambda x: x[1])
sorted_d = sorted((value, key) for (key,value) in d.items())
print(list(d.items()))
print(sorted_d) | true |
463701a0e2b4c2189f6bd304237e6ae187154ba3 | Python | delafields/Algos-Datastructs | /Algorithms/searching/sorted_matrix.py | UTF-8 | 2,386 | 4.40625 | 4 | [] | no_license | '''
Search a sorted matrix for an item
Constraints
Items in each row are sorted
Items in each column are sorted
Sorted in ascending order
The matrix is a rectangle, not jagged
The matrix is not necessarily squared
The output should be a tuple (row, col)
The item isn't definitely in the matr... | true |
370c24648686c0054ddf7fa38b7a3192ec8512ae | Python | tomdmaher/python-dev | /python_lab_2/variables.py | UTF-8 | 665 | 4.125 | 4 | [] | no_license | ##
# This program computes the volume (in litres) of a six-pack of soda
# cans, the total volume of a six-pack and a two-litre bottle and price.
#
# Litres in a 12-ounce can and a two-litre bottle.
CAN_VOLUME = 0.355
BOTTLE_VOLUME = 2.0
# Number of cans per pack.
cansPerPack = 6
# Calculate total volume in the cans.... | true |
8c95da1c91ddc382a685eec05c65694fdde3816b | Python | xiaohua123-ss/python | /加法运算器.py | UTF-8 | 736 | 3.609375 | 4 | [] | no_license | def add(a, b):
c = a + b
print('the answer is {}'.format(c))
print('this is addtion and you can inpur q to quit')
while True:
a = input('the first')
while a != 'q':
try:
a = float(a)
except ValueError:
print('you should input a number')
a = input('... | true |
943fa5d5aabe456aeafeb99824b7d01ae9294be1 | Python | smoitra87/pareto-hmm | /ParetoHMM/gen_align.py | UTF-8 | 1,593 | 2.515625 | 3 | [] | no_license | """
Generate the aligns
"""
from Bio import SeqIO,AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_protein
map1htm = 'data/PF00509_full_1htm_map.fasta'
full1htm = 'data/PF00509_full.fasta'
full1htm_filt = 'data/full_1htm.fasta'
map1aay = 'data/1aay_full.map'
full1... | true |
335924d2e3fecd4085539cba3b2361a697cb46f7 | Python | mrlvsb/kelvin | /evaluator/script.py | UTF-8 | 1,577 | 2.5625 | 3 | [
"MIT"
] | permissive | import importlib.util
import contextlib
import traceback
import os
import sys
import io
@contextlib.contextmanager
def change_cwd(new_cwd):
current = os.getcwd()
os.chdir(new_cwd)
try:
yield
finally:
os.chdir(current)
class Script:
def __init__(self, task_path, meta, output_fn, fil... | true |
c8e452fead2f2bdf3f42c6b4fcc8373ce29d75fc | Python | Mindengine76/comp120-tinkering-audio | /AUDIOPEERREVIEW/ShotObject.py | UTF-8 | 4,571 | 3.125 | 3 | [] | no_license | import pygame
import random
import math
from enemyPlayer import Enemy
pygame.mixer.init()
pygame.init()
#display size
display_width = 1000
display_height = 600
FPS = 30
#calls a surface (window) called gameDisplay where I will run the game
gameDisplay = pygame.display.set_mode((display_width, display... | true |
bea021be1c0e58c671f5c11c99f85a1ecc75a910 | Python | yangjiao91/python | /InKsyun/put_data.py | UTF-8 | 1,493 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python
#coding: utf-8
import sys
import os
import redis
import random
import subprocess
import multiprocessing
import time
import datetime
import pdb
def set(host=None, num=1, key_len=8, value_len=1024):
pool = redis.ConnectionPool(host=host, port=6379,socket_timeout=10)
r = redis.Redis(connect... | true |
3ddd5c406a2677baf8b3564f41e75a007a6c337b | Python | tczencka/Screenplay | /json_parser.py | UTF-8 | 1,062 | 2.71875 | 3 | [] | no_license |
# coding: utf-8
import json
from bs4 import BeautifulSoup
from urllib import request
import sys
with open(sys.argv[1]) as data_file:
data = json.load(data_file)
with open('all_name_script.txt','w') as out:
for movie in data:
url = movie['link'].replace(' ','%20')
name = movie['na... | true |
ce82252d92919fc6c7dbdccb6c13bbdc17e7931e | Python | uejun/JVFR | /dynamo.py | UTF-8 | 1,143 | 2.890625 | 3 | [] | no_license | import boto3
from jins_entity import GlassProduct
class DynamoClient:
def __init__(self):
self.dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1')
self.table = self.dynamodb.Table("jvfr_glass")
self.color_table = self.dynamodb.Table("jvfr_color")
if self.table == N... | true |
6b2b9b64f74d27a9fe63b67a634f62d693ded62a | Python | Raptors65/python-scripts | /MyScripts/Math/a_magic_triangle.py | UTF-8 | 517 | 3.484375 | 3 | [] | no_license | from itertools import permutations
remaining_numbers = (4, 5, 6, 7, 8, 9)
vertices = (1, 2, 3)
for permutation in permutations(remaining_numbers):
for vertex1 in range(1, len(remaining_numbers) - 1):
for vertex2 in range(vertex1 + 1, len(remaining_numbers)):
if (sum(permutation[:vertex1]) + vertices[0] + verti... | true |
376bc9b5c9663ed64472d734b169ebf1fe7fd0bb | Python | UNMECE231Sp2020/PythonStackAndQueue | /queue.py | UTF-8 | 2,136 | 4.1875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
@author: Francisco Viramontes
Description:
A simple stack class
"""
#Syntax for creating a stack class
class Queue:
#This doubles as a unparameterized default constructor and a parameterized
# default constructor
def __init__(self, init_value=None):
self.size_ = ... | true |
5a71351c928af10cc2ec9a43dd8971d62393389a | Python | TUIHackfridays/tuise-bot | /commands/ai_puzzle_solver/state_space_search/node.py | UTF-8 | 677 | 3.078125 | 3 | [] | no_license | class Node:
def __init__(self, state, operator = None, predecessor = None):
self.state = state
self.operator = operator
self.predecessor = predecessor
if predecessor is None:
self.prof=0
self.cost=0
else:
self.prof = predecessor.prof + 1
... | true |
4ef9f0704d7f09b58a439b42ac02cbab10cceece | Python | Sayadevi/Dream_chaser | /ml.py | UTF-8 | 79 | 3.3125 | 3 | [] | no_license | n1=int(input())
for i in range(1,n1+1):
f1=n1*i
print(f1,end=" ")
| true |
c4440ad3f933b96ee3739fd84d5358858f259837 | Python | larissarmp/Corretor | /Corretor-master/core/morfologico.py | UTF-8 | 4,125 | 3.09375 | 3 | [] | no_license | '''
Analisador morfológico
'''
import json
from pathlib import Path
from typing import List
import nltk.tokenize
from core.palavra import Palavra
DIR = Path(__file__).resolve().parent
MAXIMO_DICAS = 5
DICIONARIO: List[Palavra]
def _getDicionario() -> List[Palavra]:
dicionario = []
objArr ... | true |
ee2a5462b628693d7a96fe48353f7d3b04f2b338 | Python | garvsgit/CSE1001_python | /FAT2.py | UTF-8 | 1,146 | 3.265625 | 3 | [] | no_license | n = int(input())
hl = []
vl = []
allLines = []
stairs = []
for i in range(n):
xstart,ystart = int(input()), int(input())
xend, yend = int(input()), int(input())
line=[(xstart,ystart),(xend,yend)]
allLines.append(line)
if ystart==yend:
hl.append(line)
elif xstart==xend:
vl.append(... | true |
44786a363dfe667644c97f840abfb9eeab119b96 | Python | Saloni399/Leetcode-Solutions | /Sort Integers by The Number of 1 Bits.py | UTF-8 | 615 | 3.125 | 3 | [] | no_license | class Solution(object):
def sortByBits(self, arr: list[int]) -> list[int]:
def count_bit(num):
count = 0
while num > 0:
num, rem = divmod(num, 2)
if rem == 1:
count += 1
return count
new_list = [(count_bit(num)... | true |
e3d8a7d1c21ba95fced75d1e0f527c583bc555f7 | Python | azalpy/Financial-report-acquisition-and-data-processing-with-Python | /zhihu_04_mask_stock.py | UTF-8 | 3,930 | 2.671875 | 3 | [] | no_license | import xlrd #(excel read)来读取Excel文件
import xlwt #(excel write)来生成Excel文件
workbook = xlwt.Workbook() # 新建一个工作簿
sheet = workbook.add_sheet("sheet_name") # 在工作簿中新建一个表格
def write_excel_xls(path,value,inum):
index = len(value) # 获取需要写入数据的行数
# print("index is",index)
for num in range(0, index):
sheet.w... | true |
f36efd826df7b3e10d32696ea58cb54cb7f398f8 | Python | wenyichuan/-python | /tts.py | UTF-8 | 2,229 | 3.5 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 31 10:32:12 2018
@author: 温一川
"""
import pygame
def chinese_to_pinyin(x):
y = ''
dic = {}
with open("unicode_py.txt") as f:
for i in f.readlines():
dic[i.split()[0]] = i.split()[1]
for i in x:
i = str(i.encode('unicode_escape')... | true |
fdbee2f5dd14f1e157c8078754e57a57a5e43f0c | Python | jjjjj19980806/adl-hw3 | /postprocess.py | UTF-8 | 978 | 2.578125 | 3 | [] | no_license | import json, jsonlines
import logging
from pathlib import Path
from argparse import ArgumentParser
logging.basicConfig(
format="[%(levelname)s] %(message)s",
level=logging.INFO
)
def main(args):
preds = args.raw_preds.read_text().split('\n')
texts = jsonlines.open(args.input)
text_ids = [text['i... | true |
2a6224ab7baf2c18c25f01f5fcf049e4e79ed03a | Python | aanto07/networkingLab | /Programs/Expt 10/tcpserver.py | UTF-8 | 350 | 3.15625 | 3 | [] | no_license | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Created Socket ")
port= 8080
s.bind(('',port))
print("Binding Socket to ",port)
s.listen(5)
while True:
c,addr=s.accept()
message=c.recv(1024)
print(message)
print ('Got Connection from',addr)
print('Thanks for connectin... | true |
778a26d842769382975cf027d0855c7a69b4e429 | Python | AyaEbata/dailyLearningReportScraping | /dailyLearningReportScraping/daily_report.py | UTF-8 | 2,005 | 2.828125 | 3 | [] | no_license | from bs4 import BeautifulSoup
from dailyLearningReportScraping.account import Account
class DailyReport(object):
def __init__(self, session):
self.__session = session
def login(self):
res = self.__session.post("https://member.toraiz.jp/toraiz/auth/login", data=Account().get_login_info())
... | true |
777d4b2bf93287e5a6a48ad54348e746b05b161e | Python | arboj/arbogast-capstone | /Code/capstone_twitter_search.py | UTF-8 | 2,595 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 10:40:16 2021
@author: Arbo
"""
import os
import pandas as pd
import snscrape.modules.twitter as sntwitter
code_dir = os.getcwd()
parent_dir = os.path.dirname(code_dir)
data_dir = os.path.join(parent_dir,"Data")
tweet_dir = os.path.join(parent_di... | true |
c438d2499510de309b0386ad75fc221a39f0d01d | Python | hyu1834/Static-Variable-Scope-Analyzer-for-Python-Programming-Language | /test/test5.py | UTF-8 | 526 | 3.953125 | 4 | [
"Apache-2.0"
] | permissive | def sumOfOdds(range):
sum_odd = 0
index = 1
while(index <= range):
if(index % 2 == 1):
sum_odd += index
index += 1
return sum_odd
def productOfPowersOf2(exp1, exp2):
if(exp1 < 0):
return
product = 1
while(exp1 <= exp2):
exp1 += 1
return product
def printAsterisks(amount):
if(amount < 0):
retur... | true |
b1e0faed0d317a537ce524a4b95175a305b26e8b | Python | sakuragasaki46/coriplus | /app/filters.py | UTF-8 | 1,928 | 2.828125 | 3 | [
"MIT"
] | permissive | '''
Filter functions used in the website templates.
'''
from flask import Markup
import html, datetime, re, time
from .utils import tokenize
from . import app
@app.template_filter()
def human_date(date):
timestamp = date.timestamp()
today = int(time.time())
offset = today - timestamp
if offset <= 1:
... | true |
2dc9e3e61b78e6132fabf60d48a4572b8b7d668d | Python | ForemanAqua/PythonFiles | /Практика/Рівень B/11 завдання''.py | UTF-8 | 574 | 3.359375 | 3 | [] | no_license | import datetime
def printTimeStamp(name):
print("Автор програми: " + name)
print("Час компіляції: " + str(datetime.datetime.now()),"\n")
printTimeStamp("Valeriy Neroznak")
n=2
age = int((input())
def isb(n):
for i in range(5):
def sd():
if age<3:
вартість=0
... | true |
d5fbd26dd99cd7460ba9193aa09bab2f947a367f | Python | Joel-Flores/ejercicios_python | /5.Ejercicios_de_diccionarios/Ejercicio_4.py | UTF-8 | 1,059 | 4.1875 | 4 | [] | no_license | '''Ejercicio 4.
Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes.'''
def run():
meses = {1:'enero', 2:'febrero', 3:'marzo', 4:'abril', 5:'mayo', 6:'junio', 7:'julio', 8:'agosto', 9:'septiembre', 10... | true |
c227056a09424676e8887860e2b64c731af8a760 | Python | V1r61l/RPiDataAcquisition | /Sensor_Logger.py | UTF-8 | 1,451 | 3.328125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
import os
import time
import glob
import Sensors_Repository as rep
from sense_hat import SenseHat
# global variables - intervals between readings
SECONDS_60=60
MINUTES_45=45 * SECONDS_60
MINUTES_60=60 * SECONDS_60
# initialize the sense HAT Add-On
sense = SenseHat()
# created the database and the u... | true |
17f1895d04688e58c9d871f5d256aa2d6d922c9d | Python | nithinv13/Training-Project1 | /News_Aggregator/news/image_parser.py | UTF-8 | 229 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | import urllib
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib.urlopen('http://edition.cnn.com/travel/article/sports-car-with-wings-icon-a5/index.html'))
for img in soup.find_all("img", src=True):
print(img["src"]) | true |
3644eb259757c3cada4053994827dc47d8d68264 | Python | OPL94/Python-IT-Course | /exercise.py | UTF-8 | 3,890 | 3.953125 | 4 | [] | no_license | #Exercise 1
# print('''Bob
# ST1001
# bob@gmail.com''')
#Exercise 2
# print("%d + %d = %d" % (14,7,14+7))
# print("%d * %d = %d" % (14,7,14*7))
# print("%d - %d = %d" % (14,7,14-7))
# print("%d / %d = %d" % (14,7,14//7))
#Exercise 3
# for x in range(1,6):
# print("\t" * (x-1) + str(x))
#Exercise 4... | true |
b020beb72fcf6ec8f51f597b521cc64e374bd2a2 | Python | shaduk/Clustering-Algorithms | /code/hadoop/kmeansmap.py | UTF-8 | 918 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env python
import sys
import math
def euc_dis(x, m):
dis = 0
for i in range(len(x)):
dis = dis + math.sqrt(math.pow(float(x[i]) - float(m[i]), 2))
return dis
def get_nearest_cluster(centroid, x):
closestTo = -1
mindist = sys.maxint
for j in range(0, len(centroid)):
euc_distance = euc_dis(centroid... | true |
acb76e0ae4e2693289c1c604ae43f60ebfa2e261 | Python | qw4990/blog | /pytorch_learning/models/lstm.py | UTF-8 | 2,167 | 3.4375 | 3 | [] | no_license | # https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html
lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3
inputs = [torch.randn(1, 3) for _ in range(5)] # make a sequence of length 5
# initialize the hidden state.
hidden = (torch.randn(1, 1, 3),
torch.randn(1, 1, 3))
for i in input... | true |
2fe9e5c8a06aeb31662a2abb1b1cdec117808e3a | Python | VlifeAutoTest/AutoTestVlife | /library/mylog/log.py | UTF-8 | 3,929 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
from logging.handlers import TimedRotatingFileHandler
import threading
from library import configuration
import os
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foregro... | true |
a178fec6d3052da7e2aa0a7f626a6a987d353983 | Python | pychthonic/calculus | /page7ex6.py | UTF-8 | 560 | 3.453125 | 3 | [] | no_license | import numpy, sympy
def predict_CO2_scientific_american(year):
t = year - 1960
return .018*(t**2)+.7*t+316.2
def predict_CO2_2010(year):
t = year - 1960
return 1.68*t+303.5
if __name__ == '__main__':
scientific_american_prediction = predict_CO2_scientific_american(2035)
linear_model_predicti... | true |
52a5c12dc6426e9e5605cec9ee3f9176351c532a | Python | GoingMyWay/LeetCode | /122-best-time-to-buy-and-sell-stock-ii/solution.py | UTF-8 | 360 | 3.625 | 4 | [] | no_license | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit, i, length = 0, 1, len(prices)
while i < length:
if prices[i] > prices[i-1]:
max_profit += prices[i] - prices[i-1]
i += ... | true |
a2de1e8264092b3ea495654df4c009dfd3a456f0 | Python | isabella232/scipy-central-rescue | /sphinx-files/rst-files/Data/code/2011/11/000031/using_pronys_metho_to_fit_a_sum_of_exponentials.py | UTF-8 | 1,132 | 3.015625 | 3 | [
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | # License: Creative Commons Zero (almost public domain) http://scpyce.org/cc0
import scipy.linalg as la
import numpy as np
def expfit(deg,x1,h,y):
#Build matrix
A=la.hankel(y[:-deg],y[-deg-1:])
a=-A[:,:deg]
b= A[:,deg]
#Solve it
s=la.lstsq(a,b)[0]
#Solve polynomial
p=np.... | true |
e641734b8e98dddae37ce66707d580d178f0fee8 | Python | dns43/symbll | /flatten.py | UTF-8 | 1,597 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python
base_type_sizes = {
'pointer': 8, # PANDA only works on 64-bit hosts anyway
'unsigned long': 8,
'unsigned int': 4,
'unsigned short': 2,
'unsigned char': 1,
'signed long': 8,
'signed int': 4,
'signed short': 2,
'signed char': 1,
'long': 8,
'int... | true |
9fe4e88a119ccfa4b0f540f69e1f1e6bce44a696 | Python | akmci/PythonABC | /CreatingVariables.py | UTF-8 | 850 | 3.890625 | 4 | [] | no_license | #!/usr/bin/python
#! : Shebang
# /usr/bin/python : Absolute path to the python software
" Comments in Python :"
# 1. Single Line : #, '', "", ''' ''' & """ """
# 2. Multi Line : ''' ''' & """ """
'''
Rule of Creating Variables in Python
1. A-Z
2. a-z
3. 0-9
4. _
5. A-Za-z
6. A-Za-z0-9
7. A-Za-z0-9_
Note: ... | true |
958a75ab50cf92aa3f4243c6b47edba3f8c0b023 | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4140/codes/1593_1802.py | UTF-8 | 127 | 2.890625 | 3 | [] | no_license | balrog=int(input());
d1=int(input());
d2=int(input());
from math import *
dano=int(sqrt(5*d1)+pi**(d2/3));
print(balrog-dano)
| true |
ea392681547c6101f9d81b3c00abf9a36233bae3 | Python | bshrram/Graduation-Project---Omnidirectional-Conveyor-Table | /control_system/table.py | UTF-8 | 5,273 | 3.25 | 3 | [
"MIT"
] | permissive | from cell import Cell
from common import *
import math
row = 4
col = 10
class Table:
"""Table class that contains cells
Attributes:
None
"""
def __init__(self, cells):
"""Initialize variables used by Table class
Args:
cells: list of cells objects
"""
... | true |
cc8b1be1fc6b2b0aa7fd76d25192f7a3afe9928a | Python | elytae1907/71180391---Grup-A | /Tugas Video 5 Elyta.py | UTF-8 | 1,159 | 3.9375 | 4 | [] | no_license | # Elyta Edenia
# 71180391
# Universitas Kristen Duta Wacana
# Problem
# Ika adalah siswi salah satu SMA di Yogyakarta. Dia adalah siswi yang malas terutama ketika mata pelajaran matematika. Salah satu hal yang paling tidak disukai adalah tentang mencari faktor dari sebuah angka. Sebagai teman yang baik, ... | true |
3ff74422eeb8ef8c2cf7256477fea20400712b22 | Python | charly-blanche-t/XPathway | /Pathway_Significance/statistics_final_v3.py | UTF-8 | 3,660 | 3.046875 | 3 | [] | no_license |
#!/usr/bin/env python
"""
This class compute statistics from aor the induced green graph
"""
__author__ = """ Blanche Temate"""
__date__ = "$Date: 8-15-2014 $"
__credits__ = """"""
__revision__ = "$Revision: 1 $"
# Copyright (C) 2014 by
# TCB
# All rights reserved.
# BSD license.
import networkx as nx
i... | true |
8bc6bfab8e587ae5048265714777855a525f21fb | Python | prompt-toolkit/python-prompt-toolkit | /examples/prompts/swap-light-and-dark-colors.py | UTF-8 | 2,016 | 3.40625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
"""
Demonstration of swapping light/dark colors in prompt_toolkit using the
`swap_light_and_dark_colors` parameter.
Notice that this doesn't swap foreground and background like "reverse" does. It
turns light green into dark green and the other way around. Foreground and
background are independent... | true |
386cb01d4f5178d7910208eec15cf4e89c7e16d8 | Python | timotej-orcic/SIAP-2018 | /lexical_classification.py | UTF-8 | 940 | 3 | 3 | [] | no_license | import json
import os
from os import listdir
dirPath = 'TweetScraper\\TweetScraper\\Data\\'
smileyTweets = []
sadTweets = []
for city in os.listdir(dirPath):
if city != 'WEATHER DATA':
for filename in os.listdir(dirPath + city):
filePath = dirPath + city + '\\' + filename
... | true |
13c3960c39a483607ed16487f130ec075ee791bf | Python | Aguniec/Beginners_projects | /Rock-Paper-Scissors game.py | UTF-8 | 671 | 4.21875 | 4 | [] | no_license | """
Make a two-player Rock-Paper-Scissors game.
"""
while True:
print("Please pick one : rock, scissors, paper")
game_dictionary = {"rock": 1, "scissors": 2, "paper": 3}
player1, player2 = input("Player 1:"), input("Player 2:")
difference = game_dictionary.get(player1) - game_dictionary.get(player2)
... | true |
83f85b7a6b5ae49f9d0726d45d50411f13e84ea5 | Python | J14032016/LeetCode-Python | /tests/algorithms/p0069_sqrt_test.py | UTF-8 | 257 | 2.890625 | 3 | [] | no_license | import unittest
from leetcode.algorithms.p0069_sqrt import Solution
class TestSqrt(unittest.TestCase):
def test_sqrt(self):
solution = Solution()
self.assertEqual(2, solution.mySqrt(4))
self.assertEqual(2, solution.mySqrt(8))
| true |
2b16f2d847b069fe07efac104229e796e9f954db | Python | vbukovska/SoftUni | /Python_fundamentals/More_exercises/world_tour.py | UTF-8 | 1,215 | 3.828125 | 4 | [] | no_license | stops = input()
def add_stop(string, index, substring):
if 0 <= index <= len(string):
string = string[:index] + string_to_add + string[index:]
return string
def remove_stop(string, index_1, index_2):
if 0 <= index_1 <= index_2 <= len(string) - 1:
string = string[:index_1] + string[index_... | true |
43ec2ec39e1f8d80bc7d22befa474eb16f8ea348 | Python | mattharkness/sixthdev | /@gone/sixthday/test/testActor.py | UTF-8 | 1,796 | 2.84375 | 3 | [] | no_license | """
testActor.py - unit tests for Actor.py
"""
__ver__="$Id$"
import unittest
import weblib
class ActorTestCase(unittest.TestCase):
def setUp(self):
if hasattr(weblib, "request"):
self._REQ = weblib.request
def tearDown(self):
if hasattr(self, "_REQ"):
weblib.request... | true |
1164a0eff796bae4482cfddeb9264cbbc4142d98 | Python | AK-1121/code_extraction | /python/python_18850.py | UTF-8 | 165 | 3.03125 | 3 | [] | no_license | # Can you please tell me how can I convert this date string to total seconds in python?
import time
answer = time.mktime(time.strptime(string, '%Y-%m-%d %H:%M:%S'))
| true |
bb09efa7911640ba577d601d63b46c7668f82180 | Python | meetparikh7/mini-ftp-sync | /commands.py | UTF-8 | 1,068 | 2.5625 | 3 | [] | no_license | import json
import math
import os
import time
import util
# Support ls, ls -l
def ls(base_dir, long=False):
toret = []
files = os.listdir(base_dir)
if not long:
toret = files
else:
for f in files:
details = util.file_details(os.path.join(base_dir, f))
# details["... | true |
9cebf0b495173b757f7d5ed3547416a294069cf4 | Python | pracaas/AIML-and-LSA-Based-Customer-Care-Service | /quesanswer.py | UTF-8 | 1,636 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 11:48:25 2018
@author: prakash
"""
from nltk.tokenize import sent_tokenize
addrs ="/Users/prakash/Google Drive/live/Study/WRC/MSCK III sem/Projects/Project Files/FAQ.txt"
def sent_token(addrs):
print(addrs)
with open(addrs, 'r') as i... | true |
8e85ee56f90bdb0d623cf1cb772dc12fd42aae50 | Python | nicolecpeoples/python-basics | /strings.py | UTF-8 | 214 | 3.390625 | 3 | [] | no_license | """
Built in functions
.capitalize()
.format()
.lower()
.upper()
.swapcase()
.find()
.replace()
"""
first_name = "nicole"
last_name = "peoples"
print "Your name is {} {}".format(first_name, last_name).upper()
| true |