blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
55d650a479407987f1c152730dd1ea664d9d5e43 | icsaba/demonstrate_chain_pattern | /sensei/emp_types.py | UTF-8 | 1,338 | 2.828125 | 3 | [] | no_license | from employee import Employee
from sensei.observer.observer import Observer
class CEO(Employee, Observer):
def __init__(self, name, title, age):
super(CEO, self).__init__(name, title, age)
self.compensation_package = ['free money', 'cafeteria', '+1 free day']
self.car = 'Rolls Royce' if ... | true |
ec631e26b0516acedf9de3ac2cde7011a902c631 | haiyuanhe/learn_python | /sort/2_selection_sort.py | UTF-8 | 415 | 3.1875 | 3 | [] | no_license | class Solution(object):
def sort(self, nums):
for i in range(len(nums)):
min = i
for j in range(i + 1, len(nums)):
if nums[min] > nums[j]:
min = j
temp = nums[i]
nums[i] = nums[min]
nums[min] = temp
retur... | true |
1903c90bd99b8d048ff411bbf94b9cf906c882e6 | lyz05/Sources | /北理珠/python/python123/词频统计之《哈姆雷特》.py | UTF-8 | 395 | 3.1875 | 3 | [] | no_license | black_list = '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~'
dict = {}
with open("hamlet.txt", "r") as f:
txt = f.read().lower()
for ch in black_list:
txt = txt.replace(ch, ' ')
for item in txt.split():
dict[item] = dict.get(item,0)+1
ans = list(dict.items())
ans.sort(key=lambda x: x[1], reverse=True)
for i in range(10)... | true |
d203300fdc73f34be845571d7e2c8de166beae33 | mclsun/CS1010X | /mission01-template.py | UTF-8 | 546 | 3 | 3 | [] | no_license | #
# CS1010X --- Programming Methodology
#
# Mission 1
#
# Note that written answers are commented out to allow us to run your
# code easily while grading your problem set.
from runes import *
##########
# Task 1 #
##########
def mosaic(a, b, c, d):
clear_all()
return beside(stack(d, c), stack(a, b))
# Tes... | true |
152d4eac555076def2ce5a488e19da1a87d77fe6 | Floyd973/Atlantic-3.0---Python | /envoiMailSiErreurLOG.py | UTF-8 | 1,252 | 2.703125 | 3 | [] | no_license | ## ce programme permet d'envoyer un mail
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def envoiMailSiErreurLOG(depart, mdp, arrivee, nomfichier, temps): # adresse mail départ, mot de passe, adresse mail arrivée, info sur le field test et date de l'erreur, l'heure ... | true |
74d9f8307efd070202cac0b2e03cf44eecf46521 | pickledpotpie/basicbossengine | /bossengine.py | UTF-8 | 622 | 2.890625 | 3 | [] | no_license | import random
import time
crit_dmg = random.randint(1, 6)
class Boss:
def __init__(self, h, d):
self.health = h
self.damage = d
def hit(self, c_dmg):
dmg = self.damage
if c_dmg >= 3:
dmg = self.damage + 4
else:
dmg = dmg
player.health ... | true |
b7dacd765833638b1509309b0d322c3bcc80e501 | Yondela/EEE3096-Prac-02 | /scripts/automate.py | UTF-8 | 2,021 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python3
import os
def automate_python():
for i in range(20):
os.system("./../Python/PythonHeterodyning.py >> ../output/PythonHeterodyningBenchMark.txt ")
clean_benchmark_output_python()
def clean_benchmark_output_python():
lines = list()
with open("../output/PythonHeterodynin... | true |
b878ae9a633d65225f57526a768c952988d940e9 | kysu1313/python-web-scraper | /geo_locating/yello_pages_scraper.py | UTF-8 | 3,967 | 3.28125 | 3 | [] | no_license | #This project is solely used for educational purposes
#I decided to mess around and try out beautiful soup.
#this is what I came up with in about 2-ish hours
#so I know its not pretty, but it does work.
#feel free to improve it.
from bs4 import *
from urllib.request import urlopen as uReq
from bs4 import BeautifulSo... | true |
3073746290bc2a47917c9b96638d36131115f476 | Subhash3/CodeChef | /July_Cook_off/playing_with_strings.py | UTF-8 | 482 | 3.140625 | 3 | [] | no_license | #!/usr/bin/python3
def check(S, R, N) :
S_count = 0
R_count = 0
for i in range(N) :
if S[i] == '1' :
S_count += 1
if R[i] == '1' :
R_count += 1
if S_count == R_count :
return True
else :
return False
try :
T = int(input())
except :
qui... | true |
5412b0d53a36587c9098c556f2fc66b04728667f | Qflat/Progress-Bar | /Version 2/database.py | UTF-8 | 7,941 | 3.0625 | 3 | [] | no_license | import sys
import sqlite3 as sql
from tkinter import *
conn=sql.connect('graduation_progress.db')
c=conn.cursor()
move_on=False
class Course:
def __init__(self,master):
# Window Information
self.master=master
master.title('Create Courses')
# Course Labeling Information... | true |
b6a5fcbb3c7f57d55d39b28e73d57657ef6db6c0 | elmspace/Multivariable_Classification_Machine_Learning_Airline_Tweets | /CityDistanceCalculator.py | UTF-8 | 1,432 | 3.515625 | 4 | [] | no_license | """
Author: Ashkan Dehghan
Description: This module contains functions to read in the city csv file,
and convert coordinates to nearest city using Euclidean distance.
"""
"""
Import libraries
"""
import pandas as pd;
import math;
pathToCitiesCsvFile = "./cities.csv";
def ConvertGeoCoordinateToNearestCity(inp... | true |
be08900a9e2810626dacea66978a2f22137a2203 | pradeep1412/Coursera-Algorithmic-Toolbox | /week2_algorithmic_warmup/fibonacci_last_digit.py | UTF-8 | 392 | 3.390625 | 3 | [] | no_license | # Uses python3
import sys
import time
def get_fibonacci_last_digit_naive1(n):
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, (previous + current) % 10
print(current)
if __name__ == '__main__':
n = int(input())
if n <= 1:
print(n)
quit()... | true |
0291eff55abfd31fa3873db5c6c76856e30473b0 | luaraneri/ExerciciosPython | /S04Exercicio10_11.py | UTF-8 | 416 | 3.921875 | 4 | [] | no_license | n = int(input('Digite:'
'\n[1] Converter de hm/h para m/s;'
'\n[2] Converter de m/s para km/h. \n'))
velocidade = float(input('Digite a velocidade: \n'))
if n==1:
velocidade_convertida = velocidade/3.6
unidade = 'm/s'
else:
valocidade_convertida = velocidade*3.6
unidade = 'k... | true |
50ee5f94dab48f6448dd33f5700312265c139309 | JordanCoyne97/Final_Year_Project | /Demo_programs/PasswordGen.py | UTF-8 | 1,577 | 3.34375 | 3 | [] | no_license | ###############################
# old_password_generator.py #
###############################
import string, random, sys
SELECT = string.ascii_letters + string.punctuation + string.digits
SAMPLE = random.SystemRandom().sample
def main():
while True:
size = get_size()
password = generate_pw(size... | true |
dbe496d614762eebc1c780aa6b09be77fb3f05dd | gavd89/vai | /vai/commands/NewLineAfterCommand.py | UTF-8 | 822 | 2.5625 | 3 | [] | no_license | from .BufferCommand import BufferCommand
from .CommandResult import CommandResult
from ..models.TextDocument import LineMeta
class NewLineAfterCommand(BufferCommand):
def execute(self):
document = self._document
cursor = self._cursor
pos = cursor.pos
self.saveCursorPos()
cu... | true |
38ad44b860edd8394e0296f7c36531fc8d3aae76 | adreena/MyStudyCorner | /LeetCode/codes/word/79.py | UTF-8 | 960 | 2.921875 | 3 | [] | no_license | # O(MN3^L)
# space O(MN3^L)
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.visited=set()
self.n, self.m = len(board), len(board[0])
def dfs(ci,cj,out, word_idx,word):
# print(ci, cj, out, word_idx)
if word_idx == len(word):
... | true |
af6eeeb8216b3ef4d656b022474a679c731924ec | deena-dayalan/mlprediction-queue-waititme | /code/DataCleaning.py | UTF-8 | 5,081 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
sns.set(style="ticks")
import matplotlib.pyplot as plt
import multiprocessing
from joblib import Parallel, delayed
get_ipython().run_line_magic('matplotlib', 'inline')
from scipy.optimize import curve_fit
fro... | true |
e576c892cb751b96fb52116a8f965314d61e8605 | AndreaCensi/boot_olympics | /src/bootstrapping_olympics/programs/manager/meat/servonav/astar_algo.py | UTF-8 | 2,357 | 3.234375 | 3 | [] | no_license | from collections import namedtuple
from contracts import contract
import numpy as np
NodeInfo = namedtuple('NodeInfo', 'parent cost_to_come min_cost_to_go')
def astar(start, target, node2children, heuristics):
"""
start, target: nodes
node2children: given a node, returns a list of tuples (chil... | true |
879e128eeaef518401f9b4d633e804b82342a50d | alecheckert/emdiff | /samples/sample_script.py | UTF-8 | 788 | 3.03125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""
sample_script.py -- Example usage of vbdiff
"""
import pandas as pd
from emdiff import vbdiff
if __name__ == "__main__":
# Load some tracks
tracks = pd.read_csv("sample_tracks.csv")
# Run emdiff
occs, diff_coefs = vbdiff(
tracks,
n_states=5, # nu... | true |
14c8a88961dac9fb8da770e6aa62eb692b08e2de | RooD7/TuringMachine | /Output.py | UTF-8 | 2,580 | 3.25 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Output(object):
def __init__(self):
self.bloco = '................'
self.estado = '0000'
self.esquerda = '____________________'
self.cabecote = '(e)'
self.direita = '____________________'
def newLineClear(self):
return self.bloco+'.'+self.estado+': '+self.e... | true |
f41044439498f580b15b2658362ace8c783be46f | johnsonc/worklog | /visualize.py | UTF-8 | 3,110 | 3.078125 | 3 | [] | no_license | import datetime, textwrap, math
# Print a list of all open tickets.
def openTickets(workTable):
openTickets = workTable.openTickets()
if len(openTickets) > 0:
for ticket in (openTickets):
print( "━━━━━━━━━━━━━━━━━━━━━")
print("\033[1m SINCE ┊ \033[0m{} [{:3.1f}]".format(ti... | true |
ff0a88acb183ad55c6b96dacf791ce36dab633bc | andrewyoung1991/supriya | /supriya/tools/ugentools/Control.py | UTF-8 | 3,315 | 2.859375 | 3 | [
"MIT"
] | permissive | # -*- encoding: utf-8 -*-
from supriya.tools.ugentools.MultiOutUGen import MultiOutUGen
class Control(MultiOutUGen):
r'''A control-rate control ugen.
Control ugens can be set and routed externally to interact with a running
synth. Controls are created from the parameters of a synthesizer
definition, ... | true |
e16f6bd7930948253fd9b79abffb40efec8e26c2 | sam-kumar-sah/Test | /sap exam/pattern.py | UTF-8 | 387 | 2.765625 | 3 | [] | no_license | i/p: 5
o/p:
*****
~~~~~~*
~~~~~~~*
~~~~~~~~*
~~~~~~~~~*
~~~~~~~~~~*
~~~~~~~~~*
~~~~~~~~*
~~~~~~~*
******
#solution:
nn=int(input())
n=(nn-1)//2
print('*'*nn)
for i in range(n):
for j in range(n):
nn=nn+1
print('~'*nn+'*')
print('~'*(nn+1)+'*')
p=nn
for i in range(n,-1,-1):
for j in... | true |
7fd685f63f8ff1d0716fb51263a81547b5b92e0b | naxuat/python-derek | /derek/parsers.py | UTF-8 | 1,000 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | """Parsing functions."""
from email import message_from_file
__all__ = ["deb_changes"]
def line2dict(line):
"""Transforms space-separated line into dictionary."""
md5, size, section, priority, filename = line.split()
return dict(md5=md5, size=size, section=section, priority=priority,
fil... | true |
a3ecc64cd06b3f25632c17ef37a58549cb5f1525 | CalvinAu/Blackjack | /runBlackjack.py | UTF-8 | 697 | 3.65625 | 4 | [] | no_license | #===============================================================================
# runBlackjack.py
# Calvin Au
# 8/5/2014
#===============================================================================
import blackjack
if __name__ == '__main__':
print "Welcome to Blackjack"
game = blackjack.Blackjack()
wh... | true |
adb5a3885897be2b0c8c59bea3ca3a1526e96773 | AdrianVillamayor/Python_First_Try | /test5.py | UTF-8 | 159 | 3.890625 | 4 | [] | no_license | repeat = input("Dime números separados por comas")
numbers = repeat.split(",")
print(numbers)
numbers = [int(numero) for numero in numbers]
print(numbers)
| true |
79fd61a11e85ec648ee98165f8a124f12afcd66c | GribaHub/Python | /exercise12.py | UTF-8 | 562 | 4.6875 | 5 | [] | no_license | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# List Ends
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.
# c... | true |
47683cd6dd1db90907a68cae2f220aad6b176581 | thomaskrause/cora | /bin/lemmatize_coraxml.py | UTF-8 | 3,382 | 2.71875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2017 Marcel Bollmann <bollmann@linguistics.rub.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, inclu... | true |
ce4c50f8b9989596ae77441f0870af56dd33d395 | Yue0925/ProjetTer | /test.py | UTF-8 | 3,284 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 15:36:55 2020
@author: MELLET
"""
import FuzzyMeusure as fm
def first_test(criteria, importanceValues):
lattice, squaredErrors = fm.modeling(criteria, importanceValues)
fm.interaction_index(lattice)
fm.shapley_index(lattice, criteria... | true |
be897510fb27ce05fdd237dd0b37077de9c12a7b | r4dug/PriceTracker | /tracker.py | UTF-8 | 1,672 | 2.875 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import smtplib
import time
#Product used for demo: The new Macbook with M1 chip sold at a local website
URL = 'https://www.pcgarage.ro/notebook-laptop/apple/133-macbook-air-13-with-retina-true-tone-apple-m1-chip-8-core-cpu-8gb-512gb-ssd-apple-m1-8-core-gpu-macos-big-sur-go... | true |
110e9479134b9a600f7d7f2f823ad5f8dc477184 | sempervent/skeletons | /skeletons/validation.py | UTF-8 | 686 | 3.265625 | 3 | [] | no_license | """Provide validation and type ensurance."""
from typing import Union, Any
def ValidationError(Exception):
"""Raise an error because a validation cannot be done."""
def ensure_list(
obj: Any, typ: Any, raises: bool = False, warns: bool = False,
) -> list:
"""Ensure that obj is a list of typ objects.... | true |
4c38ced54d8a8210e2edc53b80b0e5647bb64cfc | matanbroner/StocksPlatform | /data/tests/test_fmp.py | UTF-8 | 3,726 | 2.78125 | 3 | [] | no_license | import unittest
from api.fmp import FinancialModelingPrepApi
# TODO: remove hardcoded API key and use env variable
API_KEY = "e2d9d13e5b7ac7976216133f32d7f775"
class TestFinancialModelingPrepApi(unittest.TestCase):
def setUp(self):
self.api = FinancialModelingPrepApi(api_key=API_KEY)
def test_compan... | true |
dd02d9106f6774c4957289cfcc440f76021ccfd1 | chang821606/storebook | /python_base/code/day07/review.py | UTF-8 | 797 | 3.0625 | 3 | [] | no_license | """
day06 复习
容器
字符串:存储字符编码值,不可变(按需分配),序列
列表:存储变量,可变(预留空间),序列
元组:存储变量,不可变(按需分配),序列
字典:存储键值对,可变(预留空间),散列.
总结:
字典:
优:根据key获取value,速度最快.
如果信息较多,通过键(指定的名称)获取,代码可读性偏好。
缺:不能通过索引/切片获取元素,不灵活.
内存占用较大
列表
... | true |
c8366cfcd2368c2be50a05ead86e01891711a077 | yurei79601/pytorch_cnn | /data_manager.py | UTF-8 | 2,256 | 3.484375 | 3 | [] | no_license | """
definition of pytorch dataset for collecting classification data
e.g. MNIST
"""
import os
from glob import glob
import cv2
import torch
from torch.utils.data import Dataset
class ClassficationDataset(Dataset):
"""
Args:
data_path: 輸入的資料路徑
mode: 資料模式,所有的可能有 'train', 'val'
y_label_li... | true |
ec823265c0ed14e7673be3642eeed39493b5735f | darthcrypto/musicapi | /api/test3.py | UTF-8 | 636 | 3.125 | 3 | [] | no_license | #run as:
#bigfiles.py <number of big files> <directory>
#or:
#bigfiles.py 5 /tmp
import heapq
import os, os.path
import sys
import operator
def file_sizes(directory):
for path, _, filenames in os.walk(directory):
for name in filenames:
full_path = os.path.join(path, name)
yield fu... | true |
47b5ab107c399a459770f184ed555156efdb201c | keakaka/practice01 | /prob10.py | UTF-8 | 744 | 4.40625 | 4 | [] | no_license | # 숫자를 입력 받아서 아래와 같은 실행결과가 나타나도록 코드를 완성하세요.
# a. 입력 받은숫자가 홀수인 경우에는, 0 부터 입력 값까지 홀수의 합을 출력합니다.
# 예제: 입력이 7 이면 16 을 출력(1 + 3 + 5 + 7 = 16 )
# b. 입력 받은 숫자가 짝수인 경우에는, 0 부터 입력 값까지 짝수의 합을 출력합니다.
# 예제: 입력이 10 이면 30을 출력(2 + 4 + 6 + 8 + 10 = 30 )
num = input('숫자를 입력하세요 : ')
mysum = 0
if num.isdigit():
num = int(num)
... | true |
933d04af35a778ac270a154b96a140118901cb59 | mscout1/Tic-Tac-Toe | /board.py | UTF-8 | 2,194 | 3.28125 | 3 | [] | no_license | """
The Tic Tac Toe Board
"""
from itertools import chain
from pprint import pformat
def empty(s):
return s not in (X,O)
board_template ="""
0 1 2
0 {0[0]} | {0[1]} | {0[2]}
-----------
1 {1[0]} | {1[1]} | {1[2]}
-----------
2 {2[0]} | {2[1]} | {2[2]}
"""
X='X'
O='O'
STALEMATE='STALEMATE'
_input_map = {... | true |
56c45663daa22214a9f7d2f8b6ab33bf6c855263 | qlong8807/python3-lesson | /src/socket通信/tcp_client.py | UTF-8 | 517 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env python3
# _*_ coding:utf-8 _*_
"""
运行后会把新浪的首页保存到当前文件夹下
"""
__author__ = 'Jans'
__date__ = '2018/1/25 下午4:12'
__createby__ = 'PyCharm'
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('127.0.0.1', 9999))
# 接收欢迎消息:
print(s.recv(1024).decode('utf-8'))
for data in [... | true |
d6bc895c41ede220ff22b706b5eda2edb0b55ada | takashimakazuki/app-article-backend | /mysite/articles/models.py | UTF-8 | 586 | 2.5625 | 3 | [] | no_license | from django.db import models
import datetime
from django.utils import timezone
class Article(models.Model):
article_id = models.IntegerField('ID')
article_title = models.CharField('タイトル', max_length=100)
article_content = models.CharField('内容',max_length=2000)
article_author = models.CharField('投稿者', m... | true |
255f1b5aba1d81935d42c6ecc9a43ddde3f5657a | hugofer19/Fake-hacker | /domain.py | UTF-8 | 1,073 | 3.375 | 3 | [] | no_license | # Este script não tem qualquer efeito
# O mesmo foi desenvolvido somente para descobrir e testar alguns modulos
import sys
from colorama import Fore, Back, Style
from colorama.ansi import Fore
from colorama import init
import time
import string
import random
import socket as s
def Hacker():
site = in... | true |
eabbaf060392cf9f293397ee300f42b07cdfa7d0 | Aasthaengg/IBMdataset | /Python_codes/p02999/s723697748.py | UTF-8 | 77 | 3.09375 | 3 | [] | no_license | s = input().split(" ")
if int(s[0]) < int(s[1]):
print(0)
else:
print(10) | true |
240bb791b8f92d22c491a636721fa4b8a9a80afc | tickBit/Median-based-clustering | /Median-based-clustering.py | UTF-8 | 4,075 | 3.359375 | 3 | [
"MIT"
] | permissive | # Median based clustering
#
# Inspired from old final exams of a data mining (and machine learning) course...
#
import math
import random
import numpy as np
import matplotlib.pyplot as plt
import operator
# Dataset
D = []
# k clusters
k = 7
# the number of data points
for i in range(500):
D.append([random.rand... | true |
fbd314f025e50208460b4ef57ba0fbc602b0898c | amishbni/HackerRank | /Python/collections_counter.py | UTF-8 | 324 | 3.421875 | 3 | [] | no_license | # https://www.hackerrank.com/challenges/collections-counter/problem
shoes_count = int(input())
sizes = input().split()
customers_count = int(input())
earned = 0
for i in range(customers_count):
shoe, price = input().split()
if shoe in sizes:
earned += int(price)
sizes.remove(shoe)
print(earne... | true |
d2dddf8e4bbb177e45aab7b28980cc57e41e7888 | RaeldZues/Outliers | /Processes.py | UTF-8 | 2,581 | 2.546875 | 3 | [] | no_license | import pandas as pd
import glob2, multiprocessing, os
import json, pyes
from elasticsearch import Elasticsearch
pd.set_option('display.width', 500)
pd.set_option('max_colwidth', 30)
pd.set_option('display.max_rows', 50)
"""
This script takes and accepts sha1 hashes csv, dlls listing csv, process listing csv and combi... | true |
6fcf75f5a3b5ce7ba41cdccccabe8d7a2594f588 | LvXueshuai/Python_test1 | /7-29/call方法.py | UTF-8 | 300 | 3.609375 | 4 | [] | no_license | # class Foo:
# pass
#
# f1 = Foo()
#
# f1() #TypeError: 'Foo' object is not callable
print('-----------------------------------------------')
class Foo:
print('lalaal')
def __call__(self, *args, **kwargs):
print("Start")
f1 = Foo()
f1()
print('--------------------')
Foo() | true |
b06cab85d238e9aa1e4e41124d2fee4947360df8 | davidzheng814/mlpset2 | /optimizers.py | UTF-8 | 9,095 | 2.53125 | 3 | [] | no_license | from sklearn.linear_model import LogisticRegression
from cvxopt import matrix, solvers
import numpy as np
from numpy import linalg as LA
import math
solvers.options['show_progress'] = False
def logistic_regression(X, Y, penalty='l2', lam=0, verbose=0):
C = 1 / float(lam) if lam != 0 else 10000
reg = LogisticRe... | true |
8e9a3231d6277e545d70257aed8365f326367a31 | noname2048/fastapi-prac-001 | /app/main.py | UTF-8 | 1,223 | 2.625 | 3 | [] | no_license | from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine, Table, Column, String, MetaData
from sqlalchemy.engine.base import Engine
def connect_postgresql(user: str, password: str, host: str, port: str, db: str) -> Engine:
url = "postgresql+psyco... | true |
038ecdb57f8de859cb7b781b3dee643f43e4c775 | huesos85/descarteslabs-python | /descarteslabs/workflows/types/containers/known_dict.py | UTF-8 | 3,000 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | import six
from ...cereal import serializable
from ..core import GenericProxytype, ProxyTypeError, assert_is_proxytype
@serializable()
class KnownDict(GenericProxytype):
"""
``KnownDict[<{key: KnownType, ...}>, KeyType, ValueType]``: Proxy mapping from specific keys to specific value
types, with default ... | true |
132744ed396a20f7eeca4c33dd2c1b6f2038705c | benthomasson/mm | /rooms.py | UTF-8 | 2,454 | 2.671875 | 3 | [] | no_license |
from pymud.room import Room as BaseRoom
from pymud.scriptable import Updatable
from pymud.exceptions import *
from pymud.choices import weighted_choices
from pymud.rule import Rule
from mm.rules import roomRules, Burn, mutateKlass, attributeLessThan
from mm.items import FireWood
class Flammable(object):
pass
cl... | true |
dcde6dc3502cc664fd764d040a134e66fe690116 | RightMesh/payment-channel-performance | /web/plot_block_gas.py | UTF-8 | 1,289 | 2.921875 | 3 | [
"MIT"
] | permissive | import requests
import json
import sys
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.optimize import curve_fit
from matplotlib.ticker import PercentFormatter
from scipy import stats
url = 'http://localhost:5000/blockavggas'
# url = 'http://localhost:5000/blockavgcost'
# url = 'htt... | true |
e3d8ec7be17edb6221bf569db187572792915baa | firoz-git/Reg_form | /my_portfolio/images/sec_1/sunOfNumbersFn.py | UTF-8 | 158 | 3.6875 | 4 | [] | no_license | def sum(a,b): #function part
print("a is : " ,a)
print("b is : ",b)
total=a+b
print("total is", total)
sum(20,30) #main part | true |
ac7c55ff87f102927d31c28cf36b68380e859af3 | lezakkaz/Python-workshop | /Examples/LR_example.py | UTF-8 | 1,157 | 3.1875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 28 18:39:46 2017
@author: Khiati Zakaria
"""
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score
x_data = []
y_data = []
file = open("dataset","r")
for line i... | true |
940ed7a9d9538ec43c88671383bfbeec650c90cb | mulki214/test-mnc | /modules/register/views/register_user.py | UTF-8 | 2,553 | 2.5625 | 3 | [] | no_license | import json
import uuid
import time
from config import config
import helper
mainDB = config.mainDB
def create_user(params):
resp = {}
try:
first_name = params['first_name']
last_name = params['last_name']
phone_number = params['phone_number']
address = params['address']
... | true |
643330cd2e156193050dabe4d209ebfb7edaee21 | samuelbustamante/sanluisautomotores | /contact/forms.py | UTF-8 | 1,094 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from django import forms
from models import Message
class MessageForm(forms.ModelForm):
full_name = forms.CharField(
label=u'Nombre : ', max_length=100,
help_text=u'Por favor ingrese su nombre.',
error_messages={
'required': u'Este campo es obligatorio.... | true |
e1130d0a57179a7bc7c69afad7b4e12c9aa388c8 | liguiyuan/insightface | /deploy/find_faces_in_picture.py | UTF-8 | 1,947 | 2.53125 | 3 | [
"MIT"
] | permissive | import cv2
import face_model
import argparse
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', default='', help='path to load model.')
parser.add_argument('--ga-model', default='', help='path to load ... | true |
e1311801e5d52d97df5da7f2bb737efb76ba8153 | TanneruNagaraju/Tanneru | /RF_feature_importance.py | UTF-8 | 3,527 | 3.09375 | 3 | [] | no_license | import numpy as np
import pandas as pd
df = pd.read_csv("irisdataset.csv")
"""
print(df)
print(df.info())
print(df.corr())
print(df.size)
print(df.shape)
print(df.describe())
print(df.columns)
"""
X = df.iloc[:, :4].values
Y = df.iloc[:, 4].values
#print(X)
#print(Y)
print(np.unique(Y))
#print(df... | true |
dc28438172cfb06c015552c39adbc7508524ed81 | AndreaWieland/weather | /api.py | UTF-8 | 3,161 | 2.796875 | 3 | [] | no_license | #TO DO:
# error code handling from both here and openweather
# detecting if latitude and longitude were sent from the browser and using that
# if an address is not found handling
#flask for routes, requests and json for external API calls, parse for url encoding
import requests, json, urllib.parse, datetime, flask
fr... | true |
1d0e0d7f54b32e550de40f4883262dee46783a41 | RZachLamberty/p99 | /python/p99.py | UTF-8 | 3,456 | 3.765625 | 4 | [] | no_license | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
"""
Module: p99.py
Author: zlamberty
Created: 2015-06-02
Description:
Implementation of the p99 problems in python
Usage:
<usage>
"""
def p01(l):
""" find the last element in a list """
return l[-1]
def p02(l):
""" find the penultimate element ... | true |
4788ca4d0ec6bad6a55190a458ffa01c633d7a63 | QingqinLi/hm | /old_boy/网络基础/进程池/进程池同步处理.py | UTF-8 | 367 | 2.90625 | 3 | [] | no_license | from multiprocessing import Pool
import time
def func(num):
num += 1
return num
if __name__ == '__main__':
p = Pool(5)
start = time.time()
for i in range(10):
res = p.apply(func, args=(i,)) # 同步:即使有n个进程,也是一个一个的去执行任务
time.sleep(0.4)
print(res)
print(time.time() - star... | true |
33bc2e95c7f8a30bb6fe682c5aab250d553dc091 | tomas1978/AdventOfCode2020 | /problem4/adventOfCode2020day4.py | UTF-8 | 1,102 | 3.515625 | 4 | [] | no_license | #Day 4 part 1, answer: 210
validPassports = 0
lines = [] #lines read from the file
entries = [] #for complete lines of passport entries
file = open('input.txt', 'r')
for line in file:
if(line!="\n"):
lines.append(line.strip())
else:
lines.append(line)
file.close()
#Rem... | true |
eefd2f7851b94a396620d891c20c6b7ea90747f9 | rlfss/mymodules | /bm_advanced/models/bug_tag.py | UTF-8 | 2,257 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from odoo import models, fields, api
class bugTag(models.Model):
_name = 'bm_bug_tag'
_description = "bug标识"
name = fields.Char('名称')
'''
以下划线(_)开头的属性不是普通的属性,我们称之为模型属性。
也就是说这些属性的作用不是用于描述记录,而是描述整个模型。
常用三模型属性:
_name:这是Odoo内模型的内部标示,如果我们创建的是一个新模型,则必须填写该属性。
_de... | true |
056d9f024e8ad192a5c623d527fc97321d3435f2 | zhyordanova/Python-Basics | /Exam-Preparation/balls.py | UTF-8 | 944 | 4.0625 | 4 | [] | no_license | n = int(input())
total_points = 0
red_point = 0
orange_point = 0
yellow_point = 0
white_point = 0
black_point = 0
other_point = 0
for i in range(0, n):
colors = input()
if colors == 'red':
red_point += 1
total_points += 5
elif colors == "orange":
orange_point += 1
total_po... | true |
95d7ef1e236145ad15c93ac793e27f82a85acd41 | tefra/xsdata | /tests/utils/test_downloader.py | UTF-8 | 5,495 | 2.59375 | 3 | [
"MIT"
] | permissive | import tempfile
from pathlib import Path
from unittest import mock
from unittest import TestCase
from urllib.request import urlopen
from tests import fixtures_dir
from xsdata.models.xsd import Import
from xsdata.models.xsd import Schema
from xsdata.utils.downloader import Downloader
class DownloaderTests(TestCase):
... | true |
d0fbb9d91ebb02ab1744ddd29406a32bc0a4ec7a | kshnam/ML-season-1 | /ML-lab-12-3-char-seq-softmax-only.py | UTF-8 | 2,004 | 3.03125 | 3 | [] | no_license | # python을 이용해 입력을 간단히 구현
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)
tf.reset_default_graph()
sample = " if you want you"
idx2char = list(set(sample)) # index -> char
char2idx = {c : i for i,c in enumerate(idx2char)} # char -> index
# hyper parameters
num_classes = len(char2idx) # final output ... | true |
b3c0fdd1a94aafa3e4e6a3187748abec8550b27e | ComputationalAstrologer/Optics | /AndersonDarlingTest.py | UTF-8 | 1,363 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 17:52:13 2020
@author: rfrazin
Anderson-Darling Test for univariate normality.
See the Wikipedia article.
This implements the single sample test.
The default is case 3 (i.e., unknown mean and var).
For cases 0, 1 and 2, in which the mean and/or ... | true |
069c4793c9f2c1c8941d935a6c29166bbc9360db | progmboy/pfp | /pfp/fuzz/__init__.py | UTF-8 | 2,640 | 2.765625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the base classes used
when defining mutation strategies for pfp
"""
import glob
import os
import six
get_strategy = None
StratGroup = None
FieldStrat = None
def init():
global get_strategy
global StratGroup
global FieldStrat
i... | true |
1b84fb95dcd17e75a0274a79227173a6f5d970d4 | ENS00/trafficSimulator | /UI.py | UTF-8 | 4,600 | 2.90625 | 3 | [] | no_license | import const
from objects import GameRect
# Manage all panels
class UI():
def __init__(self, game):
self.game = game
self.panels = []
self.freePositionLeft = [const.W_WIDTH/30, const.W_HEIGHT/50]
self.freePositionRight = [const.W_WIDTH*2/3, const.W_HEIGHT/50]
self.padding = ... | true |
39b96df2fe5b5f0cd5936872ae46a3bba1865b91 | SuryamitraAkkipeddi/Codility | /Slalom_Skiing.py | UTF-8 | 1,183 | 3.390625 | 3 | [] | no_license | def LongestIncreasingSubsequence(seq):
lower = 0
upper = lic_length
while lower <= upper:
mid = (upper + lower) // 2
if seq[i] < smallest_end_value[mid]:
upper = mid - 1
elif seq[i] > smallest_end_value[mid]:
lower = mid... | true |
7f284b88dbe187a0eef3fa8ac6bd421b4b0d19d5 | streamlink/streamlink | /tests/utils/test_random.py | UTF-8 | 1,918 | 2.890625 | 3 | [
"BSD-2-Clause"
] | permissive | from collections import defaultdict
from itertools import count
from typing import Dict, Iterator, Sequence
import pytest
from streamlink.utils.random import (
CHOICES_ALPHA,
CHOICES_ALPHA_LOWER,
CHOICES_ALPHA_NUM,
CHOICES_ALPHA_UPPER,
CHOICES_HEX_LOWER,
CHOICES_HEX_UPPER,
CHOICES_NUM,
... | true |
a512b00ab46ae1022773a3f200185427a8fe3464 | Seminhar/program | /ComputerVision/ch6/6.3.py | UTF-8 | 1,477 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 19 14:04:19 2018
@author: kaisya
"""
import imtools as its
import pca as pca
from numpy import *
from PIL import Image, ImageDraw
from pylab import *
from scipy.cluster.vq import *
imlist = its.get_imlist('E:/python/pic/Test')
imnbr = len(imlist)
# Load images, run PCA... | true |
245a7f957eb784c54f7a14e18f6ca3502a342095 | happykju1218/Project | /Main-RevisedMainProject.py | UTF-8 | 23,158 | 2.90625 | 3 | [] | no_license | global UserSet
global FriendSet
global TweetSet
global SelectedUser
global dijkArr
dijkArr = []
UserSet = []
FriendSet = []
TweetSet = []
"""---------------------heap sort Start------------------------"""
def heapify(A,i,heapsize,t):
l = left(i)
r = right(i)
if l < heapsize and A[l][t] > A[i][t]:
... | true |
23a1a194fc744d167fec6155beaf1554f066a2cf | cemagg/SUN-EM-CMOM | /src/pre_processor/mom_file_reader.py | UTF-8 | 603 | 2.765625 | 3 | [] | no_license | import numpy as np
def readMoMFile(file_path):
file = open(file_path, 'r')
line = file.readline()
line = file.readline()
content = line.split()
sol_length = int(content[1])
line = file.readline()
isol = np.empty(sol_length, dtype=complex)
index = 0
while line:
content = l... | true |
3aea18124caf8cfcf326342735b23b6c7694dc12 | joshsalvi/Sandbox | /hopfEM.py | UTF-8 | 1,327 | 2.90625 | 3 | [] | no_license | import math
import matplotlib.pyplot as plt
import numpy as num
# self, mu, noiseSTD, tvec = argv
tvec = num.linspace(0, 10, 1000)
mu = 1
noiseSTD = 0.1
# Parameter initialization
xzero = 1
yzero = -1
Dtfac = 10 ** 2
Dt = (tvec[1] - tvec[0]) / Dtfac
N = int(tvec[len(tvec) - 1] / Dt)
# Generate random seed and va... | true |
b39efe4d3df59f2f02c3f78eb668a35b8a9f5256 | valer23/robot | /python/face_crop.py | UTF-8 | 1,257 | 3.109375 | 3 | [
"MIT"
] | permissive | #!usr/bin/env python
from PIL import Image
class FaceCrop:
image_path = None
name_image = None
cpt = 0
def __init__(self):
self.name_image = 'imageFlo.jpg'
self.image_path = 'detected/detected_'
@staticmethod
def display_area(area):
area.show()
@staticmethod
... | true |
d907ad5db2348f0e89c0e5a44703ef2d42468486 | AdityaJ7/denver | /denver/pysetup.py | UTF-8 | 1,169 | 2.78125 | 3 | [
"MIT"
] | permissive | # Copyright (c) 2020 Xcodz.
# All Rights Reserved.
"""
Utilities for setup
Like find package data for including all package data
into the setup.
"""
__version__ = "2020.6.8"
__author__ = "Xcodz"
import os
def find_package_data(package: str, package_name):
files = []
for r, d, f in os.walk(package):
... | true |
3050ace0ad855ddb5745938e9961d295e3edf4e7 | hallka/Test | /PythonScript/AGC20160904b.py | UTF-8 | 784 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 4 21:22:58 2016
@author: you
"""
n, x = input().split()
n = int(n)
x = int(x)
a = list(map(int, input().split()))
t = []
for i in range(len(a)):
t.append(a[i])
i = 0
for i in range(len(a)):
if a[i-1] + x < a[i] :
a[i] = a[i-1] + x
i... | true |
7ebba9b50e9da16bc96cb160ba875a84701d689d | hpoleselo/tools | /WavesForecast/forecast.py | UTF-8 | 9,533 | 2.859375 | 3 | [] | no_license | import datetime
import requests
import re
import sys
from bs4 import BeautifulSoup as BS
class TideChecker(object):
def __init__(self):
self.response = 0
self.checkPage()
def checkPage(self):
try:
self.response = requests.get('htt... | true |
05ee5fa1d900bc8a8a5fde79dc129af73baf88ce | dannydiaz17/Simple-Python-Calculator | /PythonCalculator(Working).py | UTF-8 | 975 | 4.625 | 5 | [] | no_license | import math
#These functions hold the instructions for any given operation
def add(x, y):
z = x + y
print("Your answer is: ")
print(z)
def sub(x, y):
z = x - y
print("Your answer is: ")
print(z)
def mul(x, y):
z = x * y
print("Your answer is: ")
print(z)
def div(x, y... | true |
eb8f815df45e1314d45254114f062e22b66136a1 | SongLiu0828/data-structures-algorithms | /shell_sort.py | UTF-8 | 577 | 3.8125 | 4 | [] | no_license | def shell_sort(alist):
"""最优时间复杂度:根据步长序列的不同而不同
最坏时间复杂度:O(n^2)
稳定性:不稳定"""
n = len(alist)
gap = n // 2
while gap >= 1:
for j in range(gap, n):
i = j
while (i-gap) >= 0:
if alist[i] < alist[i-gap]:
alist[i], alist[i-gap] = alist[i-... | true |
2154fb61a04ac5daa1b4887548a8f7c388757da3 | pricixavier/Think-Phython | /pro38.py | UTF-8 | 260 | 2.515625 | 3 | [] | no_license | import sys, string, math
p,k = input().split()
p,k = int(p),int(k)
L = [ int(x) for x in input().split()]
L.sort()
cnt = 0
p = p // 3
#print(p)
for i in range(0,p) :
L2 = L[3*i : 3*(i+1)]
#print(L2)
if 5-max(L2) >= k :
cnt += 1
print(cnt)
| true |
4e282d124b8b0d37796ea96e28729114a71f0fef | byplacebo/head-first-python | /5th/unique_sort_array.py | UTF-8 | 1,331 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | def sanitize(time_string):
if "-" in time_string:
splitter = "-"
elif ":" in time_string:
splitter = ":"
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + "." + secs
with open("james.txt") as jaf:
data = jaf.readline()
james = sorted([sani... | true |
e42b523942d6042c86c84c3d56c5dd7c2a33c518 | amlan086/Fire-Protection-System | /motor.py | UTF-8 | 1,300 | 2.84375 | 3 | [] | no_license | import curses
import serial
import struct
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD)
motor= serial.Serial('/dev/ttyUSB0',9600)
GPIO.setup(15, GPIO.IN)
############################
screen = curses.initscr()
curses.noecho()
curses.cbreak()
scree... | true |
2c799800e6b7bffbaefea3d8bdd473fa775fad4b | noahlwest/leetcode | /python/easy/504_Base_7.py | UTF-8 | 455 | 3.140625 | 3 | [] | no_license | class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return "0"
is_negative = False
if num < 0:
num *= -1
is_negative = True
ret = ""
while num > 0:
ret = str(num % 7) + ret
n... | true |
64591754bcb665465a1c9955136964787fff5c84 | hangongzi/leetcode | /tree/is_balanced.py | UTF-8 | 894 | 3.625 | 4 | [] | no_license | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def is_balanced(root: TreeNode) -> bool:
def balanced(root: TreeNode, height=0):
if not root:
height = 0
return True, height
balanc_left, left = balanced(r... | true |
ab52891f5868227f188a92ef367aff095e8527a3 | MichelleZ/leetcode | /algorithms/python/corporateFlightBookings/corporateFlightBookings.py | UTF-8 | 457 | 3.03125 | 3 | [] | no_license | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/corporate-flight-bookings/
# Author: Miao Zhang
# Date: 2021-04-09
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * (n + 1)
for s, e, c in bookings:
... | true |
5a988f5f0b07cc927bcd3dff147a0c9b3cd037c3 | akhil112/data-structures | /Sorting/Bubble.py | UTF-8 | 220 | 3.25 | 3 | [] | no_license | lst = [3, 4, 5, 3, 1, 99, 0, 7]
n = len(lst)
for i in range(n):
for i in range(0,n-i-1):
if lst[i] > lst[i+1]:
temp = lst[i]
lst[i] = lst[i+1]
lst[i+1] = temp
print(lst)
| true |
105904d393a2554a9c8c0687bd7fa90dd473440a | nabe-chan/201005-001_TestFastAPI | /src/models.py | UTF-8 | 3,048 | 3.0625 | 3 | [
"MIT"
] | permissive | """
models
User
id (各ユーザ固有のID: 主キー)
username (ログインに必要なユーザネーム)
password (ログインに必要なパスワード)
mail (メールアドレス)
Task
id (各タスク固有のID: 主キー)
user_id (紐づくユーザID: 外部キー)
content (タスク内容)
deadline (タスクの締め切り)
date (タスク作成日)
done (タスクが終了したか)
"""
from dat... | true |
13297e06f54de46638cd27b2627c404ebbd8416a | npsakash/CofC-Coursework | /CSCI 220 - Computer Programming I (Python)/Class Notes and Files/Class Notes/ClassNotes 3.17.16.py | UTF-8 | 1,894 | 4.28125 | 4 | [] | no_license | #Notes March 17
#Selection
def main():
age = eval(input("enter age:"))
if age >= 18:
print("you can vote")
if age >= 21:
print("legal to drink")
else:
print("no beer for you")
else:
print("you are too young to vote")
print("\nDone")
#main()
de... | true |
7db15194b446e1dc47c64f6de93caffc1fd1818e | rrosiek/pc_data_load | /data_load/base/utils/file_utils.py | UTF-8 | 3,712 | 2.84375 | 3 | [] | no_license | import json
import csv
import os
import time
import pickle
from random import randint
def save_file(directory, file_name, data):
# print 'Saving file', file_name
data_file = open(directory + '/' + file_name, 'w')
data_file.write(json.dumps(data))
data_file.close()
def save_text_file(directory, file_... | true |
b6b3f6503720f64494966d68df4ecf32c40cd0a3 | ziyan-wang98/self_modeling_machine | /models/net.py | UTF-8 | 4,516 | 2.671875 | 3 | [] | no_license | import torch
import numpy as np
from torch import nn
from typing import Any, Dict, List, Type, Tuple, Union, Optional, Sequence
from tianshou.utils.net.common import MLP
from .transporter import Transporter
ModuleType = Type[nn.Module]
class Net(nn.Module):
"""Wrapper of MLP to support more specific DRL usage.
... | true |
37095ca144763e36d1ae661edeb097e25c3f1afc | maybeee18/udacity-data-engineer | /1-data-modeling-with-postgres/sql_queries.py | UTF-8 | 3,085 | 2.625 | 3 | [] | no_license | # DROP TABLES
songplay_table_drop = 'DROP TABLE IF EXISTS songplays; '
user_table_drop = 'DROP TABLE IF EXISTS users;'
song_table_drop = 'DROP TABLE IF EXISTS songs; '
artist_table_drop = 'DROP TABLE IF EXISTS artists; '
time_table_drop = 'DROP TABLE IF EXISTS time; '
# CREATE TABLES
songplay_table_create ... | true |
3e74fccfac03baee2fa0f03da773dcf68333edc7 | Jasonzy1015/python-5 | /爬虫/Include/马蜂窝/getfoodtext.py | UTF-8 | 1,238 | 2.609375 | 3 | [] | no_license | import re
from bs4 import BeautifulSoup
import requests
import pymysql
# 打开数据库连接
db = pymysql.connect(host="47.100.58.250", user="root",
password="123456", db="db", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql="select citynumber,tastyindex from cityeatrank where citynumber in(10065,10099,1... | true |
b7e79350580093cb0ff2b195a469eb7256132209 | jocoder22/PythonProject | /regexX/group.py | UTF-8 | 1,697 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env python
import re
# named group
p = r'(?P<group1>\bE\w+)+\W(?P<group2>\w+)'
pattern = re.compile(p, re.I)
text = "The school baseball team is in the Eve evening loop"
result = pattern.search(text)
result.group(1) # 'Eve'
result.group('group1') # 'Eve'
result.groupdict() # {'group1': 'Eve', 'group2'... | true |
b8b3a323f03ec0964d03b95b45272e655428ff98 | FATFATANT/GMUC | /src/input_analysis.py | UTF-8 | 8,306 | 2.75 | 3 | [] | no_license | # encoding: utf-8
'''
data set anaysis
'''
import json
import numpy as np
import os
exp_path = None
def write_triples(file, triples):
'''
write triples file
'''
with open(file, 'w') as f:
for triple in triples:
line = str(triple[0]) + '\t' + str(triple[1]) + '\t' + str(triple[2]) ... | true |
236d453a848ea02f407c4be1c92a130d34824538 | pymft/mft-vanak-archive-october-2018 | /S09/assignment_.py | UTF-8 | 590 | 2.953125 | 3 | [] | no_license | import urllib.request
class Brower:
instances = []
read_instances = []
def __init__(self, url):
self.url = url
def read(self):
"""reads the site content """
# we're gonna use `urllib.request` here
pass
def save(self, name):
"""
:param str name: pa... | true |
309867de7fa17f6edde9140aa6841b13407dc5cd | jwbrooks0/johnspythonlibrary2 | /OS/_os.py | UTF-8 | 5,072 | 2.859375 | 3 | [
"MIT"
] | permissive |
import os as _os
from pathlib import Path as _Path
from psutil import cpu_percent as _cpu_percent
def check_cpu_load(time_to_average_over=1e-1):
""" Returns a percentage of total system CPU usage, averaged over time specified. """
return _cpu_percent(time_to_average_over)
def processFileName(filename):
"""
Extra... | true |
d4f37d495664a2d9181800cb28cdf54183b6677e | JamesLinus/pendulum | /tests/localization_tests/test_fo.py | UTF-8 | 2,280 | 2.765625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from pendulum import Pendulum
from .. import AbstractTestCase
from . import AbstractLocalizationTestCase
class FoTest(AbstractLocalizationTestCase, AbstractTestCase):
locale = 'fo'
def diff_for_humans(self):
d = Pendulum.now().subtract(seconds=1)
self.assertEqual('... | true |
6141f4454d7dc24ab88728b5c8cdb3da65fa072d | MuhammadAnas14/Python-Course-Project-Vendors | /Python Class 2/Temperature.py | UTF-8 | 255 | 4.1875 | 4 | [] | no_license | temperature = input("Enter the temperature Today ")
temperature = int(temperature)
if temperature >= 20 and temperature <= 30:
print("it is moderate today")
elif temperature > 30:
print("it is hot today")
else:
print("it is cold today")
| true |
aef770d82da52072e01074d89174409c6ced3e97 | edt-yxz-zzd/python3_src | /nn_ns/Bijection/ChainedBijection.py | UTF-8 | 2,590 | 2.625 | 3 | [] | no_license |
__all__ = 'chainable ChainedBijection chain_bijections'.split()
from .Bijection import Bijection
from .IdBijection import id_bijection
from .InverseBijection import is_inverse_bijection_of
from .utils import all_Bijections
from itertools import chain
def chainable(b0, b1):
return b0.get_OutputType() == b1.get_I... | true |
72697cd47dd3f6427688b5e10f12c38f07bf8f39 | MehoYouTube/mehobot | /디스코드봇(메호봇).py | UTF-8 | 1,666 | 2.640625 | 3 | [] | no_license | import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print("실행중")
print("...")
print("클라이언트 이름 :", client.user.name)
print("클라이언트 아이디 :", client.user.id)
print("------------------------------------------------")
awa... | true |