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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2ff442a9ccf66ba152b9664c8c2353ec7ff19386 | Python | heidonomm/mhopRL | /scripts/create_constrained_training_data.py | UTF-8 | 1,778 | 3.09375 | 3 | [] | no_license | import json
from collections import defaultdict
# file_to_read_from = "toy_data/verb_only/training_data.txt"
# file_to_write_to = "toy_data/verb_only/constrained_training_data.txt"
"""
get counts of predicates based on previous constrained dataset
"""
with open("toy_data/constrained_training_data.txt", "r") as i... | true |
4f66705e24864ceaef28e8d51b1124cdf837ac94 | Python | shreyjj/RockPaperScissors | /RPS.py | UTF-8 | 1,002 | 3.828125 | 4 | [] | no_license | import random
tracers = {"scissors":1, "paper":2, "rock":3, "lizard":4, "spock":5}
Number = 0
choice_names = ["scissors", "paper", "rock", "lizard", "spock"]
choice_numbers = [1,2,3,4,5]
odd = ("1,3,5")
even = ("2,4,6")
user_choice=input("Pick either rock, paper, scissors lizard or spock")
if user_choice not in choic... | true |
337570ff24ddabf7c3c9e6f16f0ef7a0ac8a2d6f | Python | DarisaLLC/python-code | /deep-learning/keras-functional/utils.py | UTF-8 | 381 | 2.71875 | 3 | [] | no_license | from scipy.io import loadmat
import os
# loads utk face images/labels from .mat file and returns python lists
def load_data(mat_path):
d = loadmat(mat_path)
return d["images"], d["genders"][0], d["ages"][0], d["ethnicities"][0], d["img_size"][0, 0]
# makes directory, catching exceptions
def mk_dir(dir):
t... | true |
14e4ba3d22b4f87b31c5b3319289b1ff826e0072 | Python | markelov-alex/py-sockets | /napalm/socket/test/test_parser.py | UTF-8 | 6,239 | 2.5625 | 3 | [] | no_license | from unittest import TestCase
from napalm.socket.parser import CommandParser
class TestCommandParser(TestCase):
def setUp(self):
super().setUp()
self.parser = CommandParser()
def test_parse_room_code(self):
game_id, game_variation, game_type, room_type = CommandParser.parse_room_code... | true |
d528884c48defecc949942d010c6077c107507f6 | Python | kokorinosoba/contests | /AtCoder/ABC2/ABC259/C.py | UTF-8 | 214 | 2.953125 | 3 | [] | no_license | s=input()
t=input()
ans="Yes"
if set(s) != set(t):
print("No")
exit(0)
for c in set(s):
sc=s.count(c)
tc=t.count(c)
if sc != tc:
if sc > tc:
ans="No"
break
if sc < 2:
ans="No"
break
print(ans)
| true |
6da176a4cf7f111aed92bd7e79981e597d69ef83 | Python | ViniciusTrajano/Projeto-P1_LP1 | /projeto/tela inicial.py | UTF-8 | 1,839 | 3 | 3 | [] | no_license | import pygame
import sys
from pygame.locals import *
largura, altura = 800 , 500
relogio = pygame.time.Clock()
branco=(255,255,255)
preto=(0,0,0)
vermelho=(255,0,0)
verde=(0,255,0)
azul=(0,0,255)
tela = pygame.display.set_mode((largura,altura))
def tela_inicial(cor):
baner = pygame.image.load('image... | true |
f4aa33f872bbd34356a5a7bad748e77f823ba923 | Python | catboost/catboost | /contrib/python/Pygments/py3/pygments/lexers/whiley.py | UTF-8 | 4,018 | 2.671875 | 3 | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | """
pygments.lexers.whiley
~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Whiley language.
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups, words
from pygments.token import Comment, Keyword, Name... | true |
63a51fecf4d3e169bfd8e8ba5eee8b64665511b8 | Python | AranGarcia/Cookie | /text-normalizer/run.py | UTF-8 | 1,685 | 3.34375 | 3 | [] | no_license | #!/usr/bin/env python3
"""
Text normalizing script.
The input is any of the files stored in the Shepard repository, as they need to be preprocessed
before any information extraction or ETL processes can be performed upon them. This script will
do the following:
1) Stop-words filtering
Removal of common words that... | true |
3584e8bc29933de885a7a10f68fde75f0a57cfe6 | Python | RaulAstudillo06/astudillo_raul_orie6125 | /hw2/problem3/my_search.py | UTF-8 | 907 | 3.921875 | 4 | [] | no_license | import numpy as np
from binary_search import binary_search
def my_search(arr, item):
"""
Searches a number in an array that has the form described in problem 3.
:param arr: list of numbers as described in problem 3.
:param item: number to be searched.
"""
l = 0
r = len(arr) -1
... | true |
08eed0d3c9681eaedaf0690728ef7d72319da9ec | Python | nikitaboyko/HOG-SVM-Python3-object-detector | /gather_annotations.py | UTF-8 | 3,336 | 2.8125 | 3 | [] | no_license | import numpy as np
import cv2
import argparse
from imutils.paths import list_images
import os
from tqdm import tqdm
class BoxSelector(object):
def __init__(self, image, window_name,color=(0,0,255)):
#store image and an original copy
self.image = image
self.orig = image.copy()
#capt... | true |
68d668f5cb045b5455e65ac540d89e9c621a8ba8 | Python | id774/sandbox | /python/cycle.py | UTF-8 | 135 | 3.1875 | 3 | [] | no_license | from itertools import cycle
import numpy as np
c = cycle('ABCDEFGH')
lis = np.arange(0, 100)
for i, c in zip(lis, c):
print(i, c)
| true |
35f33dc9329e2acbe32d95f5b04eeede714cbbd7 | Python | gragragrao/training_deeplearning | /univ_homework/mnist_recog2.py | UTF-8 | 6,256 | 2.9375 | 3 | [] | no_license | def homework(train_X, train_y, test_X):
rng = np.random.RandomState(1234)
random_state = 42
class Autoencoder:
def __init__(self, vis_dim, hid_dim, W, function=lambda x: x):
self.W = W
self.a = tf.Variable(np.zeros(vis_dim).astype('float32'), name='a')
self.b = t... | true |
26139c1e8caeb1a74bacc4deba0c7c1020dfab5c | Python | KirstChat/how-till-spake-norn-irish | /app.py | UTF-8 | 8,081 | 2.65625 | 3 | [] | no_license | import os
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__name__)
ap... | true |
d83e594e01234ac5929fc8204c85c9754323f7ce | Python | mikedim/RSA-ElGamal-Demo | /elgAlice.py | UTF-8 | 1,093 | 3.375 | 3 | [] | no_license | ######Alice ElGamal######
import support
print("------WELCOME ALICE: ElGamal Encryption------")
print("Generating keys, this may take a few seconds")
#Generate large prime n
#paremeter=num of digits
n=support.primegen(20)
#Alice randomly choose generator g and secret key a
g=support.getprimroot(n)
a=int(supp... | true |
064fdceeab268355f55f737dce9b60213fecf0ed | Python | hjlevy/picar | /test scripts/wait_test_multip.py | UTF-8 | 1,057 | 3.40625 | 3 | [] | no_license | ### This code breaks a wait statement in a function,
### and recognizes if esc is pressed everything should be stopped
### It uses multiprocessing to simultaneously run a function collecting data and performing a straight movement
#note: doesn't work :(
import multiprocessing
from threading import Event
# import ke... | true |
4d3b6e0303cd790876fce7f68638ff37f7f4f3cb | Python | Jack0427/python_basic | /FileTest/read.py | UTF-8 | 645 | 3.765625 | 4 | [] | no_license | # 文件一定要存在 中文的話要使用utf-8
f = open('text.txt', encoding="utf-8")
# a = f.read() 效率差
# b = f.readline() 一次只讀取一行 下次執行會讀取下一行 會標記指針 使用f.close() f.seek(0) 可以清除指針 在運行會從第一行開始
# c = f.readlines() 回傳list 若文件很大內存會爆炸
# for line in f:
# print(line, end='.')
# for line in f:
# print(line, end='.') # 文件打開後就會標記指針 指針已經到最後就不會再次讀取... | true |
e8a4562207c8c209493d1d730766a1ee72881ea3 | Python | gkantsidis/Utils | /PL/Python/CG/Productivity/Documents/PDF/split.py | UTF-8 | 2,510 | 3.578125 | 4 | [
"Apache-2.0"
] | permissive | """
Split a PDF file into multiple files
"""
import argparse
import os
import sys
from typing import List, NamedTuple
from csv import DictReader
from pathlib import Path
from PyPDF3 import PdfFileWriter, PdfFileReader
Chapter = NamedTuple('Chapter',
[
('name', str),
... | true |
6722156e356e8bbdad1fec6c6446152d83044b19 | Python | SSymbol/homework3 | /cluster.py | UTF-8 | 2,382 | 2.828125 | 3 | [] | no_license |
#coding=utf-8
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.cluster import KMeans, MeanShift, MiniBatchKMeans
from sklearn.metrics import classification_report
from sklearn import preprocessing
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
... | true |
a953a91c57945f395e9fe948bcb5df3f60b51a7e | Python | ianrecke/covid_vaccine_progress_bot | /.github/utils/EuropeanUnion.py | UTF-8 | 2,157 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | # Standard
import argparse
import os
import sys
import pandas as pd
# =============================================================================
# Constants
# =============================================================================
COUNTRIES = [
"Austria",
"Belgium",
"Bulgaria",
"Croatia",
... | true |
6f644c10c64a1caf840c54d240214344754309f1 | Python | shihyuanwang/Social_Media_Sentiment_Analysis_for_Ridesharing_Companies | /TweetSentiment.py | UTF-8 | 8,071 | 2.609375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 05:17:55 2020
@author: Shih-Yuan Wang
"""
## import the libraries
import tweepy, codecs, os, sys, csv
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer
## fill in Twitter credentials
consumer_key = ''
consumer_secret = ''
access_token ... | true |
9905708e9b777b28430ed4ca36915c2b3aa73155 | Python | gbriones1/python-training | /basic/zoo/zoo.py | UTF-8 | 2,347 | 3.734375 | 4 | [] | no_license | class Life(object):
YEAR = 2010
BEINGS = []
@classmethod
def time_passes(cls, years):
for being in cls.BEINGS:
being.grow_up(years)
cls.YEAR += years
class Animal(object):
def __init__(self, age):
self.age = age
Life.BEINGS.append(self)
def recieve_name(self, name):
self.name =... | true |
193e25642576c83f998b5a0c552692df6f2464df | Python | Aasthaengg/IBMdataset | /Python_codes/p03078/s338892211.py | UTF-8 | 748 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python3
import heapq
def main():
x, y, z, k = map(int, input().split())
a = list(reversed(sorted(map(int, input().split()))))
b = list(reversed(sorted(map(int, input().split()))))
c = list(reversed(sorted(map(int, input().split()))))
q = [(-a[0] - b[0] - c[0], 0, 0, 0)]
queued =... | true |
a5574f9d6f2f93d33955a2eb1a917bae492d94bc | Python | skarone/PipeL | /install/serial/clientsManager.py | UTF-8 | 1,735 | 2.828125 | 3 | [] | no_license | import sqlite3 as lite
import sys
import os
class ClientsManager(object):
"""handle sql database of the clients"""
def __init__(self, path = 'D:/test.db'):
self._path = path
def create(self):
"""create clients table"""
con = lite.connect( self._path )
with con:
cur = con.cursor()
cur.execute( '''CREA... | true |
b74e9ff7b0da2e446eb8b4eb501b2476ef675bb6 | Python | eric-r-xu/klaviyo-weather-app | /async_api_and_email_service.py | UTF-8 | 2,264 | 2.734375 | 3 | [
"MIT"
] | permissive | import asyncio
import aiohttp
import aiosmtplib
# ... other imports remain the same
# Async fetch function using aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
# Modify api_and_email_task to be an async function
async def api_and_email_task(se... | true |
787eca9e3219e214f015bee642b85d78ee88aace | Python | HOIg3r/LINFO1101-Intro-a-la-progra | /Exercices INGI/Session 6/Q Représentation de tableau.py | UTF-8 | 462 | 3.265625 | 3 | [] | no_license | def table(filename_in, filename_out, width):
with open(filename_in,'r') as file_in:
file_in_line = []
for line in file_in:
file_in_line.append(line.strip())
with open(filename_out,'w') as file_out:
file_out.write("+" + "-"*(width+2) + "+\n")
for line in file_in... | true |
6c883e75e808538d678c7cbdf9acf65de00070d3 | Python | vadrevu-thanuja/list1 | /List2.py | UTF-8 | 108 | 3.125 | 3 | [] | no_license | List2=[12,14,-95,3]
num=0
while(num<len(list2)):
if List2[num]>=0:
print(List2[num],end=" ")
num+=1
| true |
48a6084ae713374465bebc4e8e295b1fb8435694 | Python | jiceR/france-ioi | /python/bornes.py | UTF-8 | 125 | 3.65625 | 4 | [] | no_license |
borneX = int(input());
borneY = int(input());
if borneX > borneY:
print(borneX - borneY);
else:
print(borneY - borneX); | true |
c8a0f714be360ceb5fc13e3fdeeed625344ce00d | Python | Milittle/learning_of_python | /com/mizeshuang/functional_programming/higher_order_function.py | UTF-8 | 1,092 | 4.78125 | 5 | [] | no_license | # 用实际的代码进行阐述
# 变量可以指向函数,这里使用自带函数abs进行测试
f = abs
b = f(-1)
print(b)
# 这说明一个现象就是,函数名也可以赋值给一个变量,调用这个变量和调用函数的功能是一致的
# 函数名也是变量
# 如果把abs指向其他变量,那么会发生什么呢?
#abs = 10
print(abs(-1))# 那么他就会报错,因为现在abs是一个int型变量
# 注:由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,
# 要用import builtins; builtins.abs = 10。
# 传入函数
# 既然变量可以指... | true |
a591310a8bfcced6bb51d80ffcbd409093d14b6c | Python | atiselsts/feature-group-selection | /feature-selection/ml_state.py | UTF-8 | 8,062 | 2.546875 | 3 | [] | no_license | import os
import numpy as np
import copy
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import ShuffleSplit, KFold
from sklearn.metrics import f1_score
import sys
sys.path.append("..")
sys.path.append("../energy-model")
import utils
import energy_model
from ml_config import *
class... | true |
8266e2f0cbe4219caabd148100479da7b182a5ca | Python | EmersonBraun/python-excercices | /cursoemvideo/ex033.py | UTF-8 | 372 | 4.375 | 4 | [] | no_license | # Faça um programa que leia três números
# e mostre qual é o maior e qual é o menor
num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite o segundo número: '))
num3 = float(input('Digite o terceiro número: '))
numeros = [num1, num2, num3]
numeros = sorted(numeros)
print('O maior número é {} e o... | true |
4a20388623e6fa823998c377d0aa8337e9a085c4 | Python | r4gus/Sichere_Programmierung | /Praktikum1/SP-P1-Sobott-Sugar/Code/mcrypt.py | UTF-8 | 833 | 3.65625 | 4 | [] | no_license | def gcd(a, b):
"""
Calculates the greatest common divisor of a and b.
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def mul_inverse(n, m):
"""
Calculates the multiplicative inverse n^-1 of n (mod m).
def: n * n^(-1) = 1 (mod m)
Returns: n^-1 e [0,1,2..m... | true |
e74e295fd6629aa5f50a4a7076ac887f3f8bc84a | Python | RosaGeorge31/C34 | /C34/DSA/lab5/prg1.py | UTF-8 | 6,445 | 2.953125 | 3 | [] | no_license | class TreeNode:
def __init__(self):
self.parent= None
self.left = None
self.right = None
self.val = None
self.ht = 1
class AVLTree:
def __init__(self):
self.root = TreeNode()
def insert(self,key):
if self.ro... | true |
560d60a5649371ac90346c97471231c037840bc1 | Python | Saifur43/iWeather | /crawler.py | UTF-8 | 714 | 2.90625 | 3 | [] | no_license | from bs4 import BeautifulSoup
import requests
import urllib
def get(city_name):
url = "https://www.timeanddate.com/weather/bangladesh/" + city_name
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
name_box = soup.find('div', attrs={'class': 'h2'})
name = name_box.text.strip... | true |
a201115019fd10aeb9a839f93ef4c06e888bbc64 | Python | xiongmao2015/yiyao | /proxy_pool/kuaidaili.py | UTF-8 | 2,051 | 2.53125 | 3 | [] | no_license | # coding: utf-8
import time
import random
from datetime import datetime
import requests
from lxml import etree
from proxy_log.logs import logs
class Proxy(object):
def __init__(self):
self.ha_url = 'http://www.kuaidaili.com/free/inha/{page}/' # 1,2,3
self.tr_url = 'http://www.kuaidaili.com/fre... | true |
46f6880fc9ae36b75274b862c2c8cb8e94f0a158 | Python | ArthurBernard/Fynance | /fynance/backtest/plot_tools.py | UTF-8 | 7,071 | 2.84375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# coding: utf-8
""" Functions to plot backtest. """
# Built-in packages
# External packages
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
# Internal packages
from fynance.features.money_management import iso_vol
from fynance.features.metrics import drawdown, ro... | true |
3dff2834412b59502b9aed75f181b137427a8cbe | Python | Kyefer/baba-is-ai | /Levels.py | UTF-8 | 6,588 | 2.6875 | 3 | [] | no_license |
import os
from tkinter import Tk, Label, Entry, Button, Menu, Listbox, Frame
import tkinter.filedialog as fd
import numpy as np
from Game import Entity, Level, Object, Modifier, Link
levels = []
def level00():
level = Level("00", 33, 18)
level.setup_entities({
(11, 6): Entity.NOUN(O... | true |
afddeedb0eea3b9badb84b0662ce1028b868e191 | Python | maschlr/thesis_simulation | /weatherdata.py | UTF-8 | 5,742 | 3.125 | 3 | [] | no_license | # Script to read the weater data supported the Universidad de Piura in some ugly format
import sqlite3
import csv
import os
import re
from numpy import array, floor
class weatherData(object):
def __init__(self):
self.data = []
self.listOfFiles=[]
self.year = None
def setYear(self, year... | true |
3659bde2bbc0f7a317a2ad2117f0712ca6981db4 | Python | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/51_v2/miller.py | UTF-8 | 940 | 3.28125 | 3 | [] | no_license | from datetime import datetime
# https://pythonclock.org/
PY2_DEATH_DT = datetime(year=2020, month=1, day=1)
BITE_CREATED_DT = datetime.strptime('2018-02-26 23:24:04', '%Y-%m-%d %H:%M:%S')
def py2_earth_hours_left(start_date=BITE_CREATED_DT):
"""Return how many hours, rounded to 2 decimals, Python 2 has
le... | true |
2fdd469cdbe71552c2b6a5005c4debef222222bf | Python | almaudoh/mlsequential | /Seq2Seq/trainer.py | UTF-8 | 3,389 | 2.78125 | 3 | [] | no_license | import torch
class Trainer(object):
def __init__(self, optimizer=None, criterion=None):
self.optimizer = optimizer
self.criterion = criterion
self.stats = {
'epoch': [],
'loss': [],
'gradient_flow': [],
}
def fit(self, model, X, Y, epochs=1... | true |
5747b6198e1d9515ef9e18abbbff150cb82cbfb0 | Python | igordejanovic/parglare | /tests/func/regressions/test_issue31_glr_drop_parses_on_lexical_ambiguity.py | UTF-8 | 752 | 2.890625 | 3 | [
"MIT",
"Python-2.0"
] | permissive | from parglare import Grammar, GLRParser
def test_issue31_glr_drop_parses_on_lexical_ambiguity():
grammar = """
model: element+;
element: title
| table_with_note
| table_with_title;
table_with_title: table_title table_with_note;
table_with_note: table note*;
terminals
... | true |
5d36c31abe62d3bc24967d257bd7acde33fa81c8 | Python | matthew-lowe/RoboJosh | /extensions/info_commands.py | UTF-8 | 2,325 | 2.859375 | 3 | [] | no_license | import datetime
import discord
from discord.ext import commands
class InfoCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Displays the avatar
@commands.command(help="Show the avatar of a user", usage=";avatar [user]")
async def avatar(self, ctx, target=None):
utils = self.bot.get_cog("Utils... | true |
2facfbae9aa0223b17d2b76947635d3b855c3c9e | Python | aalepere/IRB | /app.py | UTF-8 | 730 | 3.1875 | 3 | [] | no_license | """ Streamlit app for portfolio analysis and capital requirements """
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
st.title("Credit risk portfolio analysis and capital requirements")
@st.cache
def load_portfolio():
"""
Load portfolio data
"""
data = pd.read_csv("tes... | true |
1b986e1d64ff843a33f1ae2567176b5229b06a28 | Python | m9ra/bot-trading | /bot_trading/core/exceptions.py | UTF-8 | 352 | 3.109375 | 3 | [] | no_license | class TradeEntryNotAvailableException(Exception):
def __init__(self, pair: str, timestamp: float = None, entry_index: int = None):
super().__init__(f"Requested entry is not available for {pair} at {entry_index} on {timestamp}")
class PortfolioUpdateException(Exception):
def __init__(self, message):
... | true |
963d777487d1182b235e0f8000154f32c699ebef | Python | zjkang/PythonPractice | /soccer/*** footballDB.py | UTF-8 | 6,974 | 3.125 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
import sys
from types import *
def create_schemas():
country = [u"西班牙", u"英格兰", u"德国", u"意大利", u"法国"]
level = [u"超级", u"甲级", u"乙级"]
country_level = []
for c in country:
for l in level:
country_level.append(c + '_' + l)
... | true |
f6b3a9b4cce5d128c344e7c30f11b1379a0b9a0a | Python | lukevs/charity-explorer | /utils.py | UTF-8 | 104 | 3.296875 | 3 | [] | no_license | def batch(xs, batch_size):
for i in range(0, len(xs), batch_size):
yield xs[i:i+batch_size]
| true |
55382a5a6283a88e6e8d0e5222bcb96f9d6b473f | Python | XomakNet/teambuilder | /experiments/experiment4/preferences_clustering.py | UTF-8 | 15,802 | 3 | 3 | [] | no_license | from math import ceil
from typing import List
from typing import Set
from experiments.experiment5.balancer import Balancer
from models.user import User
__author__ = 'Xomak'
class PreferencesClustering:
DEBUG = False
def __init__(self, users: Set[User], teams_number: int, need_balance: bool=True):
"... | true |
cef6bfe882a1b5ee0ff90002817811cad8aafd44 | Python | alex-thibodeau/QB_Nebulae_V2 | /Code/nebulae/nconfig.py | UTF-8 | 373 | 2.640625 | 3 | [
"MIT"
] | permissive | import ConfigParser
class NConfig:
def __init__(self):
self.config = ConfigParser.SafeConfigParser()
self.config.read("./nebulae.opt")
def getValue(self,section,var,defvalue):
try:
val = self.config.get(section,var)
print "config " + section + ":"+ var + "=" + str(val)
... | true |
5390b4a844b43ba75664952cd1b998f9cd5576a8 | Python | bb13135811/Introducing_Python | /Chpater4/About None.py | UTF-8 | 420 | 3.859375 | 4 | [
"MIT"
] | permissive | thing = None
if thing:
print("There's something")
else:
print("Empty")
#區分None與False
if thing is None:
print("It's nothing")
else:
print("It's something")
def is_none(thing):
if thing is None:
print("It's None")
elif thing:
print("It's True")
else:
print("It's False... | true |
ac5845ffd2a9e26a1e9899408169c8911b749bb0 | Python | chandankuiry/datastructure | /fibonaccia.py | UTF-8 | 376 | 3.40625 | 3 | [] | no_license |
def fib2(n): # return Fibonacci series up to n
"""this is my codewrithin"""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
print result #here we give "print" option so it show result if we give "return option then it don't show resul
if __name__ =... | true |
3c5ed526a3b68eabed2cb48899be6f8f65544a2a | Python | 0equals2/self-study | /파이썬 기본 실습/소수구하기.py | UTF-8 | 558 | 3.890625 | 4 | [] | no_license | #2부터 100까지 numbers 리스트에 넣기
numbers=[]
for i in range(2,100,1):
numbers.append(i)
prime=[] #소수를 저장할 리스트
for i in numbers:
am_i_prime=True #일단 i 가 소수라고 가정
#i가 소수인지 판단하기 위해, 자기보다 작은 수로 나누어 떨어지는지 검사
#소수가 아니면 am_i_prime=false
for j in range(2,i,1):
if i%j==0:
am_i_prime=False
... | true |
40514b67de526d7b21dcfac20384d1c3159b8049 | Python | osushkov/gym_simple | /tabular_qlearner.py | UTF-8 | 2,980 | 2.953125 | 3 | [] | no_license |
import agent
import math
import numpy as np
from gym.spaces.discrete import Discrete
class TabularQLearner(agent.Agent):
def __init__(self, action_space, observation_space, total_episodes, discount=0.99,
init_learn_rate=0.1, final_learn_rate=0.01,
init_egreedy=1.0, final_egreedy... | true |
bb4ef8f3ae265cea86dad4c2ecaaef8862ba1fc4 | Python | riffelllab/GCMS_peakid | /integrate_whole_processed_csv_directory_to_one_csv.py | UTF-8 | 4,691 | 3.078125 | 3 | [] | no_license | import sys #loading a default module, sys
#(sys allows you to pass in file instead of coding the file name into the script)
import csv #loads default module, csv; allows Python to read .csv files
import glob
import os.path
import os
import dicttocsv_csvtolist_v2 as conv
def get_name_and_area_from_gcms(csv_filename):
... | true |
5acc69a30e4f357bcd172d1a83ad05aadd89d753 | Python | Pratiknarola/PyTricks | /objgetnamedattribute.py | UTF-8 | 150 | 3.609375 | 4 | [
"MIT"
] | permissive | #! /usr/bin/env python3
""" Return the value of the named attribute of an object """
class obj():
attr = 1
foo = "attr"
print(getattr(obj, foo))
| true |
204c3eb660d341b6cf228857a6bab56ec0b4f8c6 | Python | Stanford-PERTS/yosemite | /unit_testing/test_example.py | UTF-8 | 1,637 | 3.46875 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | """Provide example code for writing unit tests."""
import unittest
@unittest.skip("Remove this line in test.example.py to see examples.")
class ExampleTest(unittest.TestCase):
"""Collection of unit test examples, showcasing features.
Read more about the kinds of assertions here:
https://docs.python.org/... | true |
f5646458f601449714d975b39922e55319ee6a03 | Python | GoncaloKLopes/rnndissect | /model/bisarnn.py | UTF-8 | 2,948 | 2.5625 | 3 | [] | no_license | import torch
import torch.nn as nn
class BinarySARNN(nn.Module):
def __init__(self, config):
super(BinarySARNN, self).__init__()
self.hidden_dim = config.d_hidden
self.vocab_size = config.vocab_size
self.embed_dim = config.d_embed
self.batch_size = config.batch_size
... | true |
56f6de42acc68d0c5cfc8a1e99c30528c62c4cf4 | Python | royerguerrero/hackmer | /products/templatetags/product_extras.py | UTF-8 | 439 | 2.625 | 3 | [] | no_license | """Product Tags Extras"""
# Django
from django import template
register = template.Library()
@register.filter(name='format_to_cop')
def format_to_cop(value):
return '$ {:,.0f} COP'.format(value)
@register.filter(name='get_main_picture')
def get_main_picture(obj):
return obj.get_main_picture()
@register.... | true |
bfa4eb651f7920a94c9c785e8d5745a704c91b9c | Python | HARI-VELIVELA/leetcode-python | /66.py | UTF-8 | 608 | 3.453125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[27]:
"""Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer ... | true |
7b1212bc6c38cb14048dcd2a9abb6101a68936c0 | Python | VitamintK/AlgorithmProblems | /google-code-jam/2018/round1a/B_bit_party.py | UTF-8 | 1,058 | 3.390625 | 3 | [] | no_license | #could this just be a binary search problem?
#seems easy for a codejam rnd1b...
#but i don't see anything wrong with this approach
import math
class Cashier:
def __init__(self, m, s, p):
self.m = m
self.s = s
self.p = p
cashiers = []
def is_possible(time):
#print(time)
bits = []
... | true |
4c29b73963df28011e6a3a925051ecafdd4a1878 | Python | math4youbyusgroupillinois/Python-Integration | /apitemplateio_lib.py | UTF-8 | 1,911 | 2.640625 | 3 | [
"MIT"
] | permissive | import requests, json
class APITemplateIO:
def __init__(self, api_key):
self.api_key = api_key
def download(self, download_url, save_to):
with open(save_to, 'wb') as output:
response_get = requests.get( download_url, stream=True)
for chunck in response_get.iter_content(... | true |
43b40318cea159c04b5756b1ebda010c54e26d2f | Python | youwi/ApiTestPlatform | /test/tmp2.py | UTF-8 | 865 | 2.84375 | 3 | [] | no_license | import datetime
from Common.utils.DataMaker import DataMaker
t = datetime.datetime.now()
t.isoformat()
print(t.isoformat())
print(t.isoweekday())
print(t.timestamp())
TPL_TIME_ISO = "%Y-%m-%dT%H:%M:%S%z"
print((datetime.date.today() + datetime.timedelta(days=0)).strftime(TPL_TIME_ISO))
print((datetime.datetime.now(... | true |
b5f2923eaadb96f8c32b69112555979173136347 | Python | LuFernandez/PASA | /TP1/codigo/eigenvals.py | UTF-8 | 1,036 | 2.875 | 3 | [] | no_license | import channel_simulator
import numpy as np
import scipy
from matplotlib import pyplot as plt
import math
import pandas as pd
def autocorr(x):
r = np.correlate(x, x, mode='full') / len(x)
return r[len(r) // 2:]
sims = 5000
N = 4
samples_per_bit = 16
n_bits = math.ceil(N/samples_per_bit)
mus_max = np.zeros(sims)
... | true |
bba0be5dc748b67fecd2bcbe55965dfc07c866fa | Python | dsimpson1980/project_euler | /problem20.py | UTF-8 | 397 | 3.890625 | 4 | [] | no_license | """Factorial digit sum
Problem 20
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Brute force
"""
prod = 1
for n in range(1, 101):
prod *= n
... | true |
48b1efe210f406749dcbcc0dcb7757b72e322d17 | Python | Fama18/Programmation_Python | /Nombre_Secret.py | UTF-8 | 426 | 4.375 | 4 | [] | no_license |
def nombre_secret() :
a = int(input("Donner le nombre secret : "))
b = int(input("Donner le nombre déviné par le second utilisateur : "))
i = 1
while a != b :
if b > a :
print("Trop grand")
else :
print("Trop petit")
i += 1
b = int(input("Donner u... | true |
742a35fbcec57c68d928a36577d6c50bdf66b23f | Python | luxiaolei930/python3_book | /第六章/6.3 文本处理和分析.py | UTF-8 | 2,376 | 3.25 | 3 | [] | no_license | # 导入json库
import json
import nltk
from nltk import FreqDist
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'w+')
with open("./reviews.json", encoding="utf8") as f:
data = json.load(f)
# 获取所有评论内容
reviews = [i["review"] for i in data]
########################### 去除停用词与标点符号 ##################... | true |
129ae1b6b873814db30d2ce6895b658ef26936d9 | Python | mhq1065/respose | /homework_8_py/11.2.py | UTF-8 | 1,775 | 3.296875 | 3 | [] | no_license | words = ['traceback','define','identifier','valid','invalid','syntax','indent','unexpected','indices']
expla = ['追溯','定义','标识符','有效的','无效的','语法','缩进','以外的','下标index的复数形式']
def bubleSort(words,expla):#冒泡排序
for i in range(len(words)-1):
for j in range(len(words)-1-i):
if words[j]>words[j+1]:
... | true |
5cf1840967d86cb03b217d0663bb09b8c43684fb | Python | AidanDai/graduation-design | /paper/reference/run.py | UTF-8 | 498 | 2.5625 | 3 | [
"MIT"
] | permissive | import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
ENP = 32
CWP = 37
CPP = 38
ENG = 40
GPIO.setup(ENP, GPIO.OUT)
GPIO.setup(ENG, GPIO.OUT)
GPIO.setup(CWP, GPIO.OUT)
GPIO.setup(CPP, GPIO.OUT)
def forward(delay):
setStep(1, 0, 1, 0)
time.sleep(delay)
setStep(1, 1, 1, 0)
time.... | true |
bb955fe63b42616d4c21ed609bd7f76ff8957c9a | Python | jinkstudy/python-study | /cWebConn/3_beautifulsoup_class/Ex02_attribute.py | UTF-8 | 608 | 3.59375 | 4 | [] | no_license | from bs4 import BeautifulSoup
html = """
<html>
<body>
<ul>
<li><a href='http://www.naver.com'>네이브</a></li>
<li><a href='http://www.daum.net'>다아음</a></li>
</ul>
</body>
</html>
"""
#리스트의 내용과 해당 경로 추출하기
#attr['속성명'] : 해당 속성값을 얻어주는 함수
'''[출... | true |
5a54c98dafa3cf877bc5149417a50ce9ca609715 | Python | rhdp0/e-Gibbs | /e-Gibbs.py | UTF-8 | 6,556 | 2.78125 | 3 | [] | no_license | # e-Gibbs v.1.0
# Desenvolvedor: Rafael Henrique Dias Pereira
import PySimpleGUI as sg
sg.theme('LightBrown13')
class TelaPython:
def __init__(self):
#Layout
layout = [
[sg.Text('Arquivo',size=(8,0)),sg.Input(size=(30,0),key='nome'),sg.FileBrowse()],
[
... | true |
95d9c2def6e77a779af2cb1f2cef8e41362f6e53 | Python | alainlou/leetcode | /p1032.py | UTF-8 | 1,005 | 3.390625 | 3 | [] | no_license | from DS.Trie import TrieNode
class StreamChecker:
def __init__(self, words: List[str]):
self.root = TrieNode()
self.cand = []
self.maxlen = float('-inf')
for w in words:
self.insert(w)
self.maxlen = max(self.maxlen, len(w))
def insert(self, s):
... | true |
c086efab6358e39a159627c80eb72ed2569ba372 | Python | aaaaaachen/PY1901_0114WORK | /days04/demo04.py | UTF-8 | 5,027 | 3.21875 | 3 | [] | no_license |
import os
import sys
import random
import time
while True:
print("PYTHON1901电商平台用户登录")
print("~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~")
print(" 1.新用户注册")
print(" 2.用户登录")
print(" 3.退出系统")
print("~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~")
print("(温馨提示)请输入:")
... | true |
a5de5e09480f2774f2bd202945ec424ea0dc978a | Python | josue0175/Python_Programming | /positional_data.py | UTF-8 | 266 | 3.015625 | 3 | [] | no_license | #!/usr/bin/env python
import sys
input_file = open(sys.argv[1], "r")
listaa = []
listbb = []
for line in input_file:
lista, listb = line.split()
print lista, listb
listaa.append(float(lista))
listbb.append(float(listb))
print listaa, listbb
| true |
252b69bfbd214df0de2c66b771b07e542f132676 | Python | andyweruan/files-here | /cssi/python1/dictionary.py | UTF-8 | 1,447 | 3.484375 | 3 | [] | no_license | my_juice = ['green', 'rubby', 'carrot']
whole_food_price = [9.99, 15.0, 5.0]
print '{} juice costs ${}'.format(my_juice[0], whole_food_price[0])
juice_dic = {}
juice_dic = {'green': 9.99, 'rubby': 15.0, 'carrot': 5.0}
juice_dic['green'] = 2.99
print juice_dic
my_juice.append('orange') #making new thing into the dict... | true |
919a40a3c09186961ce8e698fe10fbe6da47fea0 | Python | Toyib32/Python-Projects-Protek- | /Project2_Chapter8_s.py | UTF-8 | 700 | 3.640625 | 4 | [] | no_license | def dataStat(x):
a = sum(x) / len(x)
b = max(x)
c = min(x)
dataHasil = [a, b, c]
return dataHasil
while True:
try:
n = int(input("Silahkan masukkan banyak data yang Anda inginkan (***data = angka***) :"))
break
except ValueError:
print ("incorrect input! silahkan m... | true |
bebd24dcdc36dbd20afc595aea2247c9913b5c6f | Python | feer56/Kitsune1 | /kitsune/search/tests/test_json.py | UTF-8 | 2,253 | 2.515625 | 3 | [] | permissive | from nose.tools import eq_
from kitsune.search.tests.test_es import ElasticTestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.tests import LocalizingClient
class JSONTest(ElasticTestCase):
client_class = LocalizingClient
def test_json_format(self):
"""JSON without callback shou... | true |
5ae512b103671c6fa06f19c0facfb7b89e51c637 | Python | iwob/pysv | /pysv/utils.py | UTF-8 | 17,230 | 3.25 | 3 | [
"MIT"
] | permissive | import logging
import sys
import argparse
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def index_of_closing_parenthesis(words, start, left_enc ='(', right_enc =')'):
"""Returns index of the closing parenthesis of the parenthesis indicated by start."""
num_opened = 1
for i ... | true |
405b91357e1e3dd18572449dbd0ee94535179d25 | Python | blueshed/blueshed-py | /src/blueshed/utils/generate_password.py | UTF-8 | 1,062 | 2.640625 | 3 | [
"MIT"
] | permissive | '''
Password generation of four commonly used words from a word list
seperated by hyphens.
Created on Apr 7, 2013
@author: peterb
'''
from pkg_resources import resource_filename # @UnresolvedImport
import itertools
import random
from blueshed.utils.email_password import EmailPassword
class GeneratePasswordMixin(ob... | true |
e0a255334f2ae9611cdf418e4234cb351888db34 | Python | yangxueruivs/LeetCode | /RemoveNthNodeFromEndofList.py | UTF-8 | 710 | 3.359375 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
#Double pointer
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
""... | true |
7031962bb174b76bb446f535601d8804a97c4f9f | Python | yanzv/CodeEval | /ConvertBinary.py | UTF-8 | 679 | 4.03125 | 4 | [] | no_license | #Decimal to Binary from challenge
#You are given a decimal (base 10) number, print its binary representation.
#Yan Zverev
#2015
def convertToBinary(number):
counter = 2
binaryNumber = ''
while counter*2 <=number:
counter = counter *2
while counter > 0:
if(number-counter) >= 0:
... | true |
35f9990a8af041a0adedb98858184e7a9fae6599 | Python | clementselvaprasath/learning | /python/coding/codewars/level4/Sudoku.py | UTF-8 | 2,260 | 3.703125 | 4 | [] | no_license | import math
def validate(numbers, length):
# print numbers
expected = "".join(str(x) for x in range(1, length + 1))
numbers.sort()
string = "".join(str(x) for x in numbers)
return expected == string
def perform(sudoku):
data = sudoku.data
length = len(data)
print data
for x in ... | true |
f05d0374d077e1c4ecdfed93efc19941474f9d53 | Python | arlyon/hyperion | /hyperion_cli/models/neighbourhood.py | UTF-8 | 2,648 | 2.546875 | 3 | [
"MIT"
] | permissive | import peewee as pw
from playhouse.shortcuts import model_to_dict
from .base import BaseModel
class Neighbourhood(BaseModel):
"""
Contains information about a police neighbourhood.
"""
name = pw.CharField()
code = pw.CharField()
description = pw.CharField(null=True)
email = pw.CharField(n... | true |
5bb15ee93be06285f92f0358ac194751a5389699 | Python | henriquevedoveli/nlpApp | /app/sumarizador.py | UTF-8 | 1,213 | 2.953125 | 3 | [] | no_license | import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.tokenize import punkt
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from string import punctuation
from heapq import nlargest
from collections import defaultdict
def sumarizador(texto, la... | true |
d1610b6cc6c3c7ac5eb42ee9b31bdc3fece85a35 | Python | ppooiiuuyh/datamining_assignments | /assignment07/assignment07.py | UTF-8 | 1,033 | 3.109375 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
def fun(x):
# f = np.sin(x) * (1 / (1 + np.exp(-x)))
f = np.abs(x) * np.sin(x)
return f
def mypolyfit(x,y,p):
X = np.array([ [x[j]**i for i in range(p+1)] for j in range(x.shape[0]) ])
#X*Xt
Xt_X = np.matmul(X.T,X)
#print(Xt_X)
#(X*Xt)-1
... | true |
7eb3ecf9cb5c4c6829f7a4e1bf65e062a660a3b8 | Python | scanner/django-asutils | /asutils/views.py | UTF-8 | 6,658 | 2.53125 | 3 | [
"MIT"
] | permissive | #
# File: $Id: views.py 1864 2008-10-27 22:11:00Z scanner $
#
# Python imports.
#
import os.path
# Django imports
#
from django.utils import simplejson
from django.template import loader, RequestContext
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGon... | true |
fab5388db022c36571df2ddb3868a82c388b2cce | Python | brendan-donegan/lp-to-lk | /lp-to-lk/lp-to-lk | UTF-8 | 3,375 | 2.578125 | 3 | [] | no_license | #!/usr/bin/python3
import requests
import sys
from argparse import ArgumentParser
from launchpadlib.launchpad import Launchpad
from requests.auth import HTTPBasicAuth
MAAS_BOARD_ID = "19865958"
MAAS_BOARD_URL = "https://canonical.leankit.com/kanban/api/boards/{boardId}"
MAAS_CARD_URL = "https://canonical.leankit.com... | true |
e68d1e1a9d9012adfad7ff780cb86e8023500b1f | Python | NathanielChavdarov/algorithms-old | /primecruncher.py | UTF-8 | 518 | 3.265625 | 3 | [] | no_license | import primegen as p
def primecruncher():
fileHandler = open("primes.txt", "w")
fileHandler.write("2\n3\n")
for j in range(5, 1000000+1):
if p.primetester2(j):
fileHandler.write(str(j) + "\n")
fileHandler.close()
if __name__ == "__main__":
import timeit
n = 1
while Tr... | true |
0470db504db767b7411000822e7d6506afb26103 | Python | fcole90/demotivational-policy-descent | /demotivational_policy_descent/tests/run_data_analysis.py | UTF-8 | 2,273 | 2.796875 | 3 | [
"MIT"
] | permissive | import argparse
import numpy as np
from demotivational_policy_descent.environment.pong import Pong
from demotivational_policy_descent.agents.simple_ai import PongAi
from demotivational_policy_descent.agents.policy_gradient import PolicyGradient
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
par... | true |
80a9e302a4c98b8fbb7d9defe3832ff795093672 | Python | ayush1202/BigDataMeetup | /WY_DataAnalysis_Meetup2_Ayush0619.py | UTF-8 | 10,191 | 3.078125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 15:45:51 2018
@author: AyushRastogi
"""
import sqlite3 # database library - included with python3
import pandas as pd # data processing and csv file IO library
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns ... | true |
00ef06a541df6a0326ac2ece78fcceb38b6231c7 | Python | joon3007/machine_learning_jobpair | /preprocess/augmentation.py | UTF-8 | 1,918 | 2.71875 | 3 | [] | no_license | import scipy.misc
from scipy.ndimage import zoom
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
import colorsys
# ref site : https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv/30609854
def __noisy(img, noise_type = 'gaussian'... | true |
cd7a6d219b7503bb30a8dc84a49dff114f7cf74c | Python | RKouchoo/ImVideo | /ImVideo.py | UTF-8 | 448 | 2.609375 | 3 | [] | no_license | import cv2
import numpy as np
import glob
frame_delay = 15
path = '/raw_images'
name = 'latest_timelapse.avi'
img_array = []
for filename in glob.glob(path):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
out = cv2.VideoWriter(name, ... | true |
c21c92b4b76e12254470daab949dd56d449e8f88 | Python | jarbus/multiagent-particle-envs | /agents_using_gym/gymMountainCarv0/policy.py | UTF-8 | 3,167 | 2.78125 | 3 | [
"MIT"
] | permissive | import numpy as np
from pyglet.window import key
from multiagent.scenarios.simple import Scenario
# individual agent policy
class Policy(object):
def __init__(self):
self.move = [False for i in range(4)]
def action(self, obs):
#agent = env.agents
raise NotImplementedError()
# interact... | true |
e922f4f7b3dd0f7e5bc97c008b3a4b52dc34b104 | Python | saubhik/leetcode | /problems/four_sum_ii.py | UTF-8 | 4,160 | 3.484375 | 3 | [] | no_license | from collections import Counter, defaultdict
from typing import List
from unittest import TestCase
class Solution:
# Gets TLEd with one HashMap.
# Time Complexity: O(n^3)
# Space Complexity: O(n)
def fourSumCount(
self, A: List[int], B: List[int], C: List[int], D: List[int]
) -> int:
... | true |
078fa7354c097a1d1543347aaba9d2e210f1d995 | Python | Korimse/Baekjoon_Practice | /baekjoon/1520.py | UTF-8 | 618 | 3.015625 | 3 | [] | no_license | from collections import deque
dx = [0,0,-1,1]
dy = [1,-1,0,0]
def bfs(n, m):
queue = deque()
count = 0
queue.append((0,0))
while queue:
x,y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx<n and 0<=ny<m:
if ... | true |
1faf90d70072cd60e8266ce190f1c219007b11f0 | Python | tmu-nlp/NLPtutorial2017 | /Omori/tutorial01/train-unigram.py | UTF-8 | 644 | 3.25 | 3 | [] | no_license | import sys
from collections import defaultdict
def train_unigram(input_file, output_file):
word_count = defaultdict(int)
total = 0
with open(input_file, 'r') as f:
for line in f:
word_list = line.strip().split()
word_list.append("</s>")
for word in word_list:
... | true |
82c2e6bd2385f917ea0fb0e7c2be562ef458233e | Python | Jasonandy/Python-X | /cn/opencv/color/color_four.py | UTF-8 | 1,598 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | import cv2
import numpy as np #导入库
blue_lower = np.array([100,43,46])
blue_upper = np.array([124,255,255]) #设置颜色区间
cap = cv2.VideoCapture(0) #打开摄像头
cap.set(3,640)
cap.set(4,480) #设置窗口的大小
while 1: #进入无线循环
ret,frame = cap.read() #将摄像头拍摄到的画面作为frame的值
frame = cv2.GaussianBlur(frame,(5,5),0) #高斯滤波GaussianBlur() 让图... | true |
b76570774b3f65eac1129e40e8a54f997c801a1b | Python | mittalsam20/music_player | /musicplayer.py | UTF-8 | 7,474 | 2.515625 | 3 | [] | no_license | #----------------------------------------------VOLUME FUNCTIONS------------------------------------------
def vup():
vol= mixer.music.get_volume()
mixer.music.set_volume(vol+0.05)
voltext.configure(text='{}%'.format(int(mixer.music.get_volume()*100)))
volbar['value']=mixer.music.get_volume()*100
def vd... | true |
abc71348921b57342f14e5036686f72e2276b048 | Python | AlphaWolf384/pythonlearning | /Game/RockPaperScissorv1.2.py | UTF-8 | 1,497 | 3.984375 | 4 | [] | no_license | ''' Rock, Paper, Scissors v1.2 '''
from random import randint
print('Press X to stop game')
p_score = 0
c_score = 0
d_score = 0
while True:
print('Player: ' + str(p_score) + ' & Computer: ' + str(c_score) + ' & Draw: ' + str(d_score))
player = raw_input('Rock (r), Paper (p), or Scissors (s)? ')
... | true |
d2d7682d630303bcb04e95d9f5bfff9a2eeda0ab | Python | IanOlin/linearityFinal | /simulation.py | UTF-8 | 836 | 3.484375 | 3 | [] | no_license | import math
import numpy as np
class Qubit(object):
'''This defines a qubit in our simulation, we will be using a spin-(1/2) particle
spin is defined as (alpha)|0> + (beta)|1> '''
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.theta = math.atan2(math.sqr... | true |
6c74c5a83cc9f0c646636109dc03beb7b410ba64 | Python | cn5036518/xq_py | /other/a1接口层框架设计1-0326/src22/001/002.py | UTF-8 | 385 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# h1=0
class H2:
def __init__(self):
# self.h1 = 2
pass
def test(self):
# global h1
self.h1 = 2
return self.h1
h11 = H2()
# ret1 = h11.test()
# print(ret1)
# print(h1)
class H1:
def test2(self):
# print(ret1)
... | true |
c24f14f7afac629106010c2052064c5dba32ceaf | Python | Dearyyyyy/TCG | /data/3920/AC_py/515567.py | UTF-8 | 170 | 3.3125 | 3 | [] | no_license | # coding=utf-8
aNum = input()
a1 = int(aNum[0])
a2 = int(aNum[1])
a3 = int(aNum[2])
aNum = int(aNum)
if aNum == a1**3+a2**3+a3**3:
print("YES")
else:
print("NO") | true |
43c5fb82d3e4611a047001cd9e7cc4d4e05480f0 | Python | Real-Fael/faculdade_atividades | /data_structure/extensible_hash/Hash_extensivel.py | UTF-8 | 12,971 | 3.0625 | 3 | [] | no_license | import sys
import csv
import numpy as np
import time
TAMPAG_DEFAULT = 3000 # tamanho que funciona bem para todos os casos testados
FILE_DEFAULT = "D_a2_i20000.csv" # lê um arquivo padrao qualquer
class Registro(object): # registro com todos os campos
def __init__(self, campos=None): # inicializa o registro c... | true |