seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
25433089369 | from itertools import combinations
import sys
input = sys.stdin.readline
dx = (1,0,-1,0)
dy = (0,1,0,-1)
INF = int(1e9)
def out_of_range(ny:int, nx:int) -> bool:
return ny < 0 or nx < 0 or ny >= n or nx >= n
def position(val: tuple[int]) -> list[int]:
return [(num//n, num%n) for num in val]
de... | reddevilmidzy/baekjoonsolve | 백준/Silver/14620. 꽃길/꽃길.py | 꽃길.py | py | 878 | python | en | code | 3 | github-code | 1 |
15210648124 | # -*- coding: utf-8 -*-
# 标识符
# 第一个字符必须是字母表中字母或下划线'_'。
# 标识符的其他的部分有字母、数字和下划线组成。
# 标识符对大小写敏感。
# python保留字
# 保留字即关键字,我们不能把它们用作任何标识符名称。
# Python的标准库提供了一个keyword module,可以输出当前版本的所有关键字
import keyword
print(keyword.kwlist)
# 注释
# Python中单行注释以#开头,多行注释用三个单引号(''')或者三个双引号(""")将注释括起来。
#自然字符串, 通过在字符串前加r或R。 如 r"this is a line ... | bensoho/Python | Basic_Python/Chapter01/01_syntax.py | 01_syntax.py | py | 859 | python | zh | code | 0 | github-code | 1 |
14236671750 | import cv2
import imutils
import sys
import math
import tkinter as tk
import numpy as np
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
# import pickle
np.set_printoptions(threshold=sys.maxsize)
PERFECT_HEX... | kashmoney2000/catan-spot-chooser | cv.py | cv.py | py | 12,931 | python | en | code | 0 | github-code | 1 |
74136873634 | #!/usr/bin/env python3
import socket
from threading import Thread
from config import SERVER_IP, SERVER_PORT, CLIENT_CONNECT_TIMEOUT
class Client(object):
def __init__(self, server_ip, server_port, client_connect_timeout):
self._server_ip = server_ip
self._server_port = server_port
self._c... | aviafelix/simplechatpy | client.py | client.py | py | 1,510 | python | en | code | 0 | github-code | 1 |
10995813645 | """
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
3
/ \
5 1
/ \ / \
6 2 0 8
/\
7 4
示例 1:
输入: root = [3,5,1,6,2,0,... | bendanwwww/myleetcode | code/lc236.py | lc236.py | py | 2,372 | python | zh | code | 1 | github-code | 1 |
23363766608 | import pickle
import os
print("--------------------------------------------------------------------------------------------------------------------------------")
print(" Welcome to Bosco Public School ")
print()
print(" ... | officialkushagragupta/Library_Management_System | final final project python.py | final final project python.py | py | 10,630 | python | en | code | 0 | github-code | 1 |
40453581223 | # ! IMPORTANT !
# Create a copy called settings.py
# Mongo connection info
DATABASE = {
"name":"memes-tests", # Just in case this gets run on production, it won't wipe out the DB
"host":"mongo"
}
# Number of seconds to keep cache.
LAG_ALLOWED=1.5
# Generate this once, and only change it when you want to forec... | subdavis/memetrades-server | memeServer/settings-example.py | settings-example.py | py | 1,323 | python | en | code | 12 | github-code | 1 |
8681356478 | import time
import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
start_time = time.time()
print(f"{client}, {userdata}")
print(f"Received message on topic '{message.topic}': {message.payload.decode()}")
end_time = time.time()
elapsed_time = end_time - start_time
with open... | danielkaczmarczyk/mqtt-playground | subscriber.py | subscriber.py | py | 603 | python | en | code | 0 | github-code | 1 |
35635936481 | import numpy as np
import sympy
import matplotlib.pyplot as plt
import copy
param_names=["K", "r"]
params={x:sympy.symbols(x) for x in param_names}
t=sympy.symbols("t")
p0=sympy.symbols("P0")
P_t=params["K"]/(1+(sympy.exp(-params["r"]*t)*(params["K"]-p0)/p0))
P_t=(params["K"]*p0*sympy.exp(params["r"]*t))/(params["K"]+... | HOLL95/General_electrochemistry | Theory/FIM/sympy_fim_logistic.py | sympy_fim_logistic.py | py | 2,056 | python | en | code | 2 | github-code | 1 |
26917764938 | # 20221110 - Python - Python OOP - Polymorphism and Abstraction
# 04 - Shapes - judge url: https://judge.softuni.org/Contests/Practice/Index/1942#2
from abc import ABC, abstractmethod
from math import pi
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
@abstractmethod
def ca... | theterminal/python_04_python_oop_2022 | 20221110_13_L_Polymorphism_and_Abstraction/L13_04_shapes.py | L13_04_shapes.py | py | 1,492 | python | en | code | 0 | github-code | 1 |
19159108219 | '''¿Cual es el comandante que mas batallas ha ganado?'''
import pandas as pd
def reducir_data(file_path, list_columnas):
df = pd.read_csv(file_path)
df = df[list_columnas]
return df
df = reducir_data('battles.csv', ['name', 'attacker_commander', 'defender_commander', 'attacker_outcome'])
| panchoclo3/Games-of-Thrones | pregunta_1.py | pregunta_1.py | py | 306 | python | en | code | 0 | github-code | 1 |
8518140724 | import gzip
import os
import logging
from functools import partial
import numpy as np
import numpy.ma as ma
from pyg2p import Loggable
from . import grib_interpolation_lib
from .latlong import LatLong
from .scipy_interpolation_lib import ScipyInterpolation, DEBUG_BILINEAR_INTERPOLATION, DEBUG_ADW_INTERPOLATION, \
... | ec-jrc/pyg2p | src/pyg2p/main/interpolation/__init__.py | __init__.py | py | 21,232 | python | en | code | 5 | github-code | 1 |
71984887714 | # python3
import sys
def compute_min_refills(distance, tank, stops):
"""
Find the minimum number of refuelling stops along a distance AB where the
vehicle has a certain tank capacity and fuel stops are arranged randomly at
some distance from A.
"""
stops.insert(0, 0)
stops.append(distance)... | akashvshroff/DSA_Coursera_Specialisation | Algorithmic_Toolbox/week3_assignment/car_fueling.py | car_fueling.py | py | 974 | python | en | code | 0 | github-code | 1 |
3022188184 | from setuptools import setup, find_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='Zeek-Indenter',
version='0.1.0',
description='Python package to indent Zeek s... | corelight/zeek-indenter | setup.py | setup.py | py | 750 | python | en | code | 4 | github-code | 1 |
42952895279 | import uproot#3 as uproot
import numpy as np
import pandas as pd
from tqdm import tqdm
import torch
import dgl
from dgl import backend as F
from torch.utils.data import Dataset, DataLoader, Sampler
#from modules.fixed_radius_graph import FixedRadiusNNGraph
#from dgl.geometry.pytorch import FarthestPointSampler
lay... | atlas-calo-ml/ML4PIONS_GRAPH | modules/ML4Pions_Dataset.py | ML4Pions_Dataset.py | py | 19,597 | python | en | code | 1 | github-code | 1 |
12614935309 | import ConfigParser
import logging
from logging.config import fileConfig
from base import Base
from mootdao import MootDao
class Achievements(Base):
def __init__(self, user_id):
Base.__init__(self, __name__)
self.user_id = user_id
self.config = ConfigParser.ConfigParser()
self.con... | erinbleiweiss/Moot | moot/moot/achievements.py | achievements.py | py | 5,754 | python | en | code | 0 | github-code | 1 |
23400568493 | #!/usr/bin/env python
# Author: Mandeep Singh
# Contact: msingh98@uw.edu
# Developed for: ServiceNow
#
# This is the main script that runs the Software_Spend_Reporter.
import sys
import os
from Company import Company
from pandas import read_csv
# The following if else statements stop the execution of the script if
#... | themandysingh/Software_Spend_Reporter | Software_Spend_Reporter.py | Software_Spend_Reporter.py | py | 1,467 | python | en | code | 0 | github-code | 1 |
9497389498 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import backlight
import subprocess
subprocess.run(f"xbacklight -inc {backlight.diff}", shell=True)
brightness = backlight.getBrightness()
if brightness < backlight.diff:
brightness = 100
backlight.notifyBrightness(brightness)
| jtavizon98/scripts | brightness_up.py | brightness_up.py | py | 274 | python | en | code | 0 | github-code | 1 |
39393923147 |
# Script to process hyperopt log and summarise results. Useful for multiple hyperopts in one file (e.g. from hyp_exchange.sh)
import sys
import os
from re import search
import statistics
import pandas
import numpy
from tabulate import tabulate
infile = None
curr_line = ""
strat_results = {}
strat_summary = {}
# ro... | nateemma/strategies | scripts/SummariseHyperOptResults.py | SummariseHyperOptResults.py | py | 4,899 | python | en | code | 199 | github-code | 1 |
8999900973 | from django.contrib import admin
from payment.models import PaidMember, UserInfo
class PaidMemberAdmin(admin.ModelAdmin):
""" Premium User Admin """
list_display = (
'user',
'start_date',
'end_date',
'subscription',
)
admin.site.register(PaidMember, PaidMemberAdmin)
cla... | stefbez/bee-fitness | payment/admin.py | admin.py | py | 567 | python | en | code | 0 | github-code | 1 |
36645439776 |
def Square_and_Multiply(a, x, n):
b = bin(x)[2:]
b = str(b)
y = 1
for i in range(len(b) - 1, -1, -1):
if b[i] == '1':
y = y * a % n
#print('y=',y)
a = a * a % n
# print('a=',a)
return y
def keygen(e1,d,p):
e2=Square_and_Multiply(e1,d,p)
return... | rameezrz25/cryptography | totalcrypto/182548-Program Number6-ELGAMEL-2-11-2018.py | 182548-Program Number6-ELGAMEL-2-11-2018.py | py | 2,251 | python | en | code | 0 | github-code | 1 |
3559214492 |
# Odin M. Moron-Garcia
# Date of Creation 21st September, 2021
# For our purposes we need Doc2Vec since it is suitable for downstream machine learning applications
# And this script will refurbish the original Doc2Vec tutorial so the models are calculated for KEGG, COGs and pFAm
# datasets for the GenePhene2 bacteri... | omgmvi/genephene2 | Genomes/scripts/D2V_bk/Doc2Vec_Genomes_GenePhene2.py | Doc2Vec_Genomes_GenePhene2.py | py | 4,332 | python | en | code | 0 | github-code | 1 |
16850165553 | #!/usr/bin/env python3
import rospy
import numpy as np
from sensor_msgs.msg import LaserScan
from ...nodes.update import Update
class CalcAvgFrontDist(Update):
def __init__(self, scan_var_name, dist_var_name, fov):
super().__init__()
self.scan_var_name = scan_var_name
self.dist_var... | jarumihooi/Object_Sorter_Robot | scratch/mr_bt/nodes/update_nodes/scan_updates/calc_avg_front_dist.py | calc_avg_front_dist.py | py | 919 | python | en | code | 1 | github-code | 1 |
24859931153 | from typing import cast
from fastapi import Request
from starlette.datastructures import UploadFile
from fcg.infrastructure.types import OutputFormat
from fcg.viewmodels import parse
from fcg.viewmodels.form_base_viewmodel import FormBaseViewModel
class MosViewModel(FormBaseViewModel):
def __init__(self, reques... | saltastroops/finder-chart-generator | fcg/viewmodels/mos_viewmodel.py | mos_viewmodel.py | py | 1,029 | python | en | code | 0 | github-code | 1 |
15708411103 | """
DEFINE YOUR FUNCTIONS BELOW
"""
def get_final_price():
"""
Takes a list of prices and calculates what the final price of the purchase will be.
pre-condition: The function needs the subtotal of the order (the total of all the prices entered added together) to be greater than or equal to 1000.
post... | casuallysentient/lab_04 | price_calculator.py | price_calculator.py | py | 1,287 | python | en | code | 0 | github-code | 1 |
7043092758 | # coding: utf-8
import sys
import time
import dataset
import sorting
from collections import defaultdict
TESTS = ["basico", "ordenado", "ordenado_inverso"]
# gets the list of supported sorting algorithms from the `sorting` module
ALGORITHMS = [f for f in dir(sorting) if callable(getattr(sorting, f)) and not f.star... | eze210/tda1 | tp1/sorting/run_test.py | run_test.py | py | 3,753 | python | en | code | 0 | github-code | 1 |
17000288984 | from django.shortcuts import render, redirect
from .models import *
# course filter
from django.template.loader import render_to_string
from django.http import JsonResponse
# total duration sum
from django.db.models import Sum
def home(request):
course_menu_category = Categories.get_all_category(Categories)
... | foyez-ahammad/lms-course | course/views.py | views.py | py | 4,163 | python | en | code | 0 | github-code | 1 |
2888086477 | import sys
snput = lambda: sys.stdin.readline().rstrip()
m_snput = lambda: map(int, snput().split())
if __name__ == "__main__":
n, m = m_snput()
count = (n * (n - 1) + m * (m - 1)) // 2
print(count)
"""
input_str = snput()
input_num = int(snput())
some_map = m_snput()
"""
| Kumamoto-Hamachi/atcoder_pr | abc_contest/abc159/a/a.py | a.py | py | 306 | python | en | code | 1 | github-code | 1 |
17609606258 | # Author: Jordan Cain, 2015-16
import re
import sys
import time
import parse
import walker
from debugUtil import Trace
from methodHolder import Method
from classHolder import Class
from optimisations import Recursion
from optimisations import LoopToUnroll
def detect(parent, debugObj):
global debug
debug = deb... | jordanCain-zz/Java-Optimisation-Atom-Plugin | OptimisationDetect/scan.py | scan.py | py | 9,391 | python | en | code | 0 | github-code | 1 |
23035981858 | import logging
import os
from scrapy.exceptions import CloseSpider
from scrapy.linkextractors import LinkExtractor
import scrapy
from scrapy.spiders import CrawlSpider, Rule
class SpiderOne(scrapy.Spider):
name = "sp1"
counter = 0
linkextractor = LinkExtractor(allow=('https://en.wikipedia.org/wiki/(.)')... | ViliamJ/VINF | vinf_airplanes/vinf_airplanes/spiders/spider_one.py | spider_one.py | py | 2,369 | python | en | code | 0 | github-code | 1 |
22466508863 | import wiotp.sdk.application
import json
import uuid
from time import sleep
import jarHelper
import bot
class ApplicationClient:
def __init__(self):
f = open('../../properties.json')
properties = json.load(f)
self.typeId = properties['DEVICE']['DEVICE_TYPE']
self.deviceId = propert... | sak007/SmartJar | code/bot/wiotpApplicationClient.py | wiotpApplicationClient.py | py | 1,429 | python | en | code | 2 | github-code | 1 |
18540755230 | import string
import time
from copy import deepcopy
from math import sqrt
from random import shuffle, sample, random, choice
from typing import Set, List
import numpy as np
from tensorflow.python.keras.utils.np_utils import to_categorical
from utils import Grid, Region_map, Rule, Move, calc_dim, calc_moveset, EMPTY, C... | ST3LL/Projet_PTS-DIA_13 | sudoku_base.py | sudoku_base.py | py | 6,974 | python | en | code | 0 | github-code | 1 |
4615472490 | # usr/bin/env python3
# -*- coding:utf-8- -*-
from gui import GUI
from tkinter import Tk
TEXT = {
"title": "RA3录像自动分析工具",
"info_1": "请先选择一个录像文件",
"browse_file": "选择文件",
"export_1": "导出流程图信息",
"export_2": "导出所有命令信息",
"No Support": "无法获取电脑的操作",
"Invalid Faction": "不支持该阵营(帝国)",
"Error":... | BigShuang/Red-Alert-3-Battle-Flow-Chart | ra3autohander/main_zh.py | main_zh.py | py | 1,249 | python | en | code | 4 | github-code | 1 |
10852006322 | # encoding:utf-8
from common.douyu_request import dyreq
from common.logger import logger
from common.config import conf
from common.get_secrets import get_secrets
from lxml import etree
import re
import math
import requests
def get_badge():
"""
:return: 获取具有粉丝牌的房间号、当前经验、升级所需经验、升级还需要的经验
"""
badges_url ... | TheSlientnight/douyu_helper | common/dy_badge.py | dy_badge.py | py | 2,248 | python | en | code | 34 | github-code | 1 |
29119532621 | import csv
from Functions import IsNumber, TypeChange
class SmallData:
# Each SmallData object corresponds to a line of intensities for 1 unique compound
ID = 0
mz = ''
driftTime = 0 # Not required, samples with a drift time will be marked so
intensities = []
name = '' # Name of experiment, ... | cregast/MSIC_Master | FileIO.py | FileIO.py | py | 3,387 | python | en | code | 0 | github-code | 1 |
31598620564 | from websites.model import User
user = User()
# MELAKUKAN SCAN
user.update_value_rtdb(key='id', value='17970112128304')
# user.update_value_rtdb(key='id', value='1797018304')
def cek_proyektor(id_proyektor, nama, nomor, kondisi):
status = False
for proyektor in user.get_collection("proyektor"):
if p... | allail-qadrillah/Peminjaman-alat-RFID | unittest.py | unittest.py | py | 1,096 | python | en | code | 0 | github-code | 1 |
9618269930 | var = 100
if var == 100: print("Value of expression is 100")
speed = 85
mood = ''
if speed >= 80:
print('License and registration please')
if mood == 'terrible' or speed >= 100:
print('You have the right to remain silent.')
elif mood == 'bad' or speed >= 90:
print("I'm going to have to wr... | hemantkgupta/Python3 | basics/4-decision-flow.py | 4-decision-flow.py | py | 1,428 | python | en | code | 0 | github-code | 1 |
69878638113 | num_list = [1,2,3,4,5]
answer = []
odd = 0
even = 0
for i in range(len(num_list)) :
if(num_list[i] % 2 == 0) :
even += 1
else :
odd += 1
answer.append(even)
answer.append(odd)
print(answer) | jjongram/demo-repository | self_study/src/programmers/짝수홀수개수.py | 짝수홀수개수.py | py | 213 | python | en | code | 1 | github-code | 1 |
19644698860 | from fractions import Fraction
import re
class Conversions:
def __init__(self, *args, **kwagrs):
pass
def us_to_dec(self, value: str) -> float:
"""
Convert US odds to float
Args:
value (str): US odds ie -600, 475
Returns:
float: converted us odd... | gVkWY8NJAa/OddsCalculator | conversions.py | conversions.py | py | 3,688 | python | en | code | 1 | github-code | 1 |
72143594595 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Optional
import warnings
from .base import TemplateWidget, Block
from .buttons import ModalButton, CollapseButton, LinkButton, FormButton
class BasicHeader(TemplateWidget):
"""
The base header class, which contains the bulk of the functionalit... | caltechads/django-wildewidgets | wildewidgets/widgets/headers.py | headers.py | py | 8,800 | python | en | code | 9 | github-code | 1 |
14588765850 | from quiz.models import Quiz
from .serializers import QuestionSerializer
#Função que recebe um nome de jogador e inicia um quiz para ele
def start_quiz(player_name: str) -> Quiz:
quiz = Quiz(player_name=player_name)
quiz.save()
return quiz
#Função que retorna um quiz dado o id do quiz
def _get_quiz(quiz_... | jmelo-435/UNIQUIZ_APP | uniquiz/quiz/services.py | services.py | py | 1,593 | python | pt | code | 0 | github-code | 1 |
22261399048 | """ analysis of foreign umpires"""
import matplotlib.pyplot as plt
from main import matches,umpires
def foreign_umpire_analysis():
"""foreign umpire analysis"""
foreign_umpire = set()
for match in matches:
foreign_umpire.add(match['umpire1'])
foreign_umpire.add(match['umpire2'])
umpire_... | shivapittala19/IPL_dataset_analysis | foregin_umpire.py | foregin_umpire.py | py | 1,127 | python | en | code | 0 | github-code | 1 |
31756752130 | # coding:utf-8
from virt_who import *
from virt_who.base import Base
from virt_who.register import Register
from virt_who.testing import Testing
class Testcase(Testing):
def test_run(self):
self.vw_case_info(os.path.basename(__file__), case_id="RHEL-133739")
hypervisor_type = self.get_config("hype... | VirtwhoQE/virtwho-ci | tests/tier1/tc_1036_check_ignore_swp_file_in_etc_virtwho_d.py | tc_1036_check_ignore_swp_file_in_etc_virtwho_d.py | py | 2,018 | python | en | code | 0 | github-code | 1 |
72318840994 | with open('test/puzzle_input.txt') as f:
groups = [x.split('\n') for x in f.read().split('\n\n')]
# Part 1
total_yes = 0
for group in groups:
n_yes = 0
answered = set() # Contains letters that has been answered by current group
for person in group:
for question in person:
if questi... | TrongTheAlpaca/AdventOfCode | 2020/day_6/day_6_0.py | day_6_0.py | py | 658 | python | en | code | 2 | github-code | 1 |
216313915 | import datetime
import pytz
# Cogs Configuration
cogs = ["cog_manager", "currency", "moderation", "miscellaneous"]
# Moderation Configuration
filtered = ["dick"]
# Bot Configuration
name = "Dreamworld"
shop_emoji = None
shop_categories = ["mlbb", "genshin", "roblox", "valorant", "discord", "roles"]
formal_shop_cate... | MothTheMortal/dreamworld | config.py | config.py | py | 11,845 | python | en | code | 1 | github-code | 1 |
180138624 | #!/usr/bin/env python
import os, sys
import argparse
from PlottingToolkit import *
from ROOT import *
gROOT.Macro( "rootlogon.C" )
gROOT.LoadMacro( "AtlasUtils.C" )
gROOT.SetBatch(1)
#gStyle.SetErrorX(0)
xtitle = {
"x" : "X",
"inclusive" : "Inclusive cross-section [pb]",
}
####################... | rdisipio/eikos | bin/eikos-plot-knowledge_update_2d.py | eikos-plot-knowledge_update_2d.py | py | 3,384 | python | en | code | 1 | github-code | 1 |
37395788457 | opcion = 0
total = 0
while opcion != 6:
print("===== Menú Principal =====")
print("1.- Pan Amasado")
print("2.- Pan Molde")
print("3.- Pan Baguette")
print("4.- Pan Integral")
print("5.- Total de compra")
print("6.- Salir del programa")
opcion = int(input("Ingrese opción: "))
if op... | patricioyanez/PGY1121_003 | EA3/Ejemplo3While.py | Ejemplo3While.py | py | 1,083 | python | es | code | 0 | github-code | 1 |
6649249684 | import logging
from flask import jsonify, request
from flask_swagger import swagger
from flask_swagger_ui import get_swaggerui_blueprint
from ocean_provider.constants import BaseURLs, Metadata
from ocean_provider.myapp import app
from ocean_provider.routes import services
from ocean_provider.utils.basics import get_co... | oceanprotocol/provider | ocean_provider/run.py | run.py | py | 3,539 | python | en | code | 25 | github-code | 1 |
31617496117 | import datetime,json
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APITestCase
from StringIO import StringIO
from rest_framework.parsers import JSONParser
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.test import Client
... | EdgeCaseBerg/whoseopinion.com | api/questions/tests.py | tests.py | py | 17,831 | python | en | code | 0 | github-code | 1 |
73811586273 | import json
from flask import current_app as app, request, session
from flask_login import login_user, current_user
import models
from utils import request_json, get_https_conn, success, failed, user_to_dict, sort_models, stop, hash_pwd, str_rand
from plugins.fileHelper import save_remote_pic
from plugins.ResourceContr... | dickhfchan/borocol | server/controllers/GoogleAuthController.py | GoogleAuthController.py | py | 5,429 | python | en | code | 0 | github-code | 1 |
72786479073 | from estructura import estructura
import random
class recomendador(estructura):
def __init__(self, rutaCatalogo, rutaUsers):
self.rutaCatalogo = rutaCatalogo
self.rutaUsers = rutaUsers
self.catalogo = {}
self.indexadorSubgenero = 1
self.directSubgenero = {}
self.gene... | ungit70/TEST | recomendador.py | recomendador.py | py | 3,836 | python | es | code | 0 | github-code | 1 |
43514752978 | '''
1010. 总持续时间可被 60 整除的歌曲
在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 i 和 j 满足 i < j 且有 (time[i] + time[j]) % 60 == 0。
示例 1:
输入:[30,20,150,100,40]
输出:3
解释:这三对的总持续时间可被 60 整数:
(time[0] = 30, time[2] = 150): 总持续时间 180
(time[1] = 20, time[3] = 100):... | km1994/leetcode | topic9_hash_table/T1010_numPairsDivisibleBy60/interview.py | interview.py | py | 1,432 | python | zh | code | 24 | github-code | 1 |
3246717195 | from pathlib import Path, PurePath
import xlrd
import xlwt
src_path = '/Users/miraclewong/github/PythonPractice/python_productivity/调查问卷'
# dst_file = '/Users/miraclewong/github/PythonPractice/python_productivity/result/结果.xlsx'
dst_path = '/Users/miraclewong/github/PythonPractice/python_productivity/工资单/工资单.xlsx'
p ... | MiracleWong/PythonPractice | python_productivity/01_excel_merge_spilt.py | 01_excel_merge_spilt.py | py | 2,362 | python | en | code | 0 | github-code | 1 |
25185773466 | violator_songs = [
['World in My Eyes', 4.86],
['Sweetest Perfection', 4.43],
['Personal Jesus', 4.56],
['Halo', 4.9],
['Waiting for the Night', 6.07],
['Enjoy the Silence', 4.20],
['Policy of Truth', 4.76],
['Blue Dress', 4.29],
['Clean', 5.83]
]
def search_song(song, list_song):
... | tuzer69/PythonLearning | Module16/05_songs/main.py | main.py | py | 732 | python | en | code | 0 | github-code | 1 |
41861809765 | import time
import tkinter #For module (pre installed)
import sys #to import system files (pre installed)
from tkinter import * #whole module is imported
from tkinter import font #importing local time
#Used to display time on the label
def DClock():
curr_time= time.strftime("%H:%M:%S") #Time
clock.co... | Nivesh-GitHub/Make-a-clock | Theclockcode.py | Theclockcode.py | py | 724 | python | en | code | 0 | github-code | 1 |
17004996570 | print(" -📋YOU HAVE TO DO✅- ")
options=["edit - add" , "delete"]
tasks_for_today=input("enter the asks you want to do today - ")
to_do=[]
to_do.append(tasks_for_today)
print("would you like to do modifications with your tasks? ")
edit=input("say yes if you would like edit your tasks - ")
if edit=... | Anshikaverma24/to-do-app | to do app/app.py | app.py | py | 1,500 | python | en | code | 0 | github-code | 1 |
73823335394 |
# import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn import cluster, datasets, mixture
from sklearn.preprocessing import StandardScaler
from itertools import cycle, islice
import warnings
# for reproducibility
np.random.seed(201277)
# ============
# Generate data
# =======... | ArkaB-DS/SpectralClustering | Codes/comparisons.py | comparisons.py | py | 3,418 | python | en | code | 1 | github-code | 1 |
38937917036 | import errno
import os
import socket
from typing import AnyStr, cast, Dict, List, Optional, Tuple, Union
from six import ensure_str
import cmk.utils.debug
import cmk.utils.paths
import cmk.utils.store as store
from cmk.utils.exceptions import MKTerminate, MKTimeout, MKIPAddressLookupError
from cmk.utils.log import co... | superbjorn09/checkmk | cmk/base/ip_lookup.py | ip_lookup.py | py | 11,074 | python | en | code | null | github-code | 1 |
33926594806 | import subprocess
import argparse
import os
from time import *
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_path", type=str)
parser.add_argument("--scene_path", type=str)
parser.add_argument("--pair_file", type=str)
parser.add_argument("--kernel_path", type=str)
parser.add_argument("--img_path", t... | shaochangxu/DenseReconstruction-CMD | Kernel/colmap_script.py | colmap_script.py | py | 4,934 | python | en | code | 0 | github-code | 1 |
20239780834 | from django.shortcuts import render,redirect
from .models import *
from .forms import *
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required(login_url=('accounts:login'))
def home(request):
products = Product.objects.all().order_by('-id')
context = {'products':produc... | rcoffie/store-inventory | products/views.py | views.py | py | 2,790 | python | en | code | 0 | github-code | 1 |
28883027729 | from flask import (
redirect,
request,
session,
render_template,
url_for,
Blueprint,
)
main = Blueprint('main', __name__)
@main.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form.get('name')
if not name:
return red... | LeeW-jc/chat-by-websocket | routes/main_route.py | main_route.py | py | 616 | python | en | code | 4 | github-code | 1 |
29511766908 |
import solver
if __name__ == '__main__':
while True:
expression = str(input("Введите выражение: "))
result = solver.Solver(expression)
print(
f"Выражение: {result.expression} \n"
f"Результат: {result.result} \n"
f"Причина: {result.reason} \... | ndless29/logical-foundations-of-intelligent-systems | Lfis/main.py | main.py | py | 376 | python | ru | code | 0 | github-code | 1 |
40538329668 | import os
import re
# Pattern to catch time stamps
time_pattern = re.compile('\[.*\]')
# tag_pattern = re.compile('<.*>')
# weird_brackets = re.compile('\(\(\)\)')
char_set = set()
punctuation = set(['*', '~', '(', '_', '<', '>', '-', ')', ' '])
def update_set(line):
if not re.match(time_pattern, line) and line... | ammarasmro/Kurdish-Language | speech-recognition/utils/char_map_generator.py | char_map_generator.py | py | 801 | python | en | code | 8 | github-code | 1 |
14681654244 | n = int(input())
final_dict = {}
for i in range(n):
command = input().split(' ')
if command[0] == 'register':
user_name = command[1]
license_plate = command[2]
if user_name not in final_dict:
final_dict[user_name] = license_plate
print(f'{user_name} r... | Grigorov999/SoftUni-Python | Python_fundamentals/course_chapters_excercises/dictionaries/EX07_05_SoftUni Parking.py | EX07_05_SoftUni Parking.py | py | 805 | python | en | code | 0 | github-code | 1 |
17144967943 | import datetime
from django.test import TestCase
from Test_Designing.forms import TestCreateForm, QuestionForm
from Result_Analysis.models import Teacher
from django.contrib.auth.models import User
from Discussion_Forum.models import *
class ExamFormTest(TestCase):
name = 'ASE Quiz 1'
description = 'ASE Quiz... | BrijeshBumrela/Scholaris | Scholaris/testModule/test_forms.py | test_forms.py | py | 1,804 | python | en | code | 3 | github-code | 1 |
39837283394 | def main():
# create lists and dicts
data = {}
names = {}
dates = []
date_num = {}
panopto_viewers = {}
student_date_time = {}
date_num_participants = {}
add_data(data, names, dates, date_num, panopto_viewers, student_date_time, date_num_participants)
get_averages(data)
organ... | bengao10/attendanceModeling | attendance.py | attendance.py | py | 15,571 | python | en | code | 0 | github-code | 1 |
3150635854 | """citeseer_rnm.py
The domain knowledge here is represented in paper connections p1 and p2 which tend to be about
the same topic. For example:
∀p1 ∀p2 AG(p1 ) ∧ Cite(p1 , p2 ) → AG(p2 )
Where Cite is an evidence predicate (value over the groundings is known a priori), determining whether
a pattern cites another one.
"... | samuelebortolotti/rnm | citeseer_rnm.py | citeseer_rnm.py | py | 12,360 | python | en | code | 0 | github-code | 1 |
37774782473 | import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
import project.data.preprocess_data as preprocess
import torch
from sklearn.preprocessing import LabelEncoder
from pytorch_pretrained_bert import BertTokenizer
def tokenize_input(baseline_text, context_text, split, token... | Sanger2000/Predicting-Lung-Cancer-Disease-Progression-from-CT-reports | project/data/make_features.py | make_features.py | py | 5,785 | python | en | code | 0 | github-code | 1 |
35388028773 | from sklearn.ensemble import GradientBoostingRegressor
from xgboost import XGBRegressor
from catboost import CatBoostRegressor
import pandas as pd
import numpy
from numpy import ndarray
def df_processing(df, df_test):
df.drop('genres', axis=1, inplace=True)
df_test.drop('genres', axis=1, inplace=True)
... | akozlovskaya/ml_msu | GradBoost/awards_prediction.py | awards_prediction.py | py | 2,479 | python | en | code | 1 | github-code | 1 |
16484998137 | from tkinter import *
import time
import threading
import random
class Galaxy:
def __init__(self, qnt):
self.win = Tk()
self.win.geometry("800x500")
self.win.title("Galaxy")
self.win.resizable(0,0)
self.win.config(bg="black")
self.gen = False
self.t = time.sl... | goodeny/Galaxy-Simulation | galaxy.py | galaxy.py | py | 420 | python | en | code | 0 | github-code | 1 |
1645497463 | def is_question(parsed_frag):
likelihood = 0
begins_with_verb = False
beings_with_wh_word = False
# the fragment starts with a verb
# now we need to check if this is a WH or auxilary verb
print(parsed_frag[0].pos_)
if parsed_frag[0].pos_ == 'VERB':
begins_with_verb = True
#... | AITestingOrg/semantic-network-repository | src/analysis/algorithms/question_classifier.py | question_classifier.py | py | 660 | python | en | code | 3 | github-code | 1 |
39651466436 | import logging
import os
from twisted.internet import reactor
from .extra.kv_client import KvClient
from .hipchat_api import HipChatApi
from .hipchat_db import HipchatUserDb
from .hipchat_xmpp import make_client
from .schedule import Schedule
from .util.config import init_config, write_config_file_utf8
from .util.day... | LipuFei/team-hipchat-bot | bot/bot.py | bot.py | py | 2,874 | python | en | code | 0 | github-code | 1 |
1669354899 | # Fernando Ulises Gomez Sanchez
# Hacer un programa que pida nombre y edad y que imprima la persona más grande
print("Algoritmo NombreEdadGrande");
nombre1=input("Dame un nombre ")
nombre2=input("Dame un segundo nombre ")
edad1 = int(input("¿Cuál es la edad de la primera persona que nombraste? "))
edad2 = int(input("¿... | fernandougomezs2/FP | Unidad3/FGS_TareaPSeInt2.1_Ejercicio5.py | FGS_TareaPSeInt2.1_Ejercicio5.py | py | 476 | python | es | code | 0 | github-code | 1 |
38806556181 | import cv2
archivo_video = './videos/video.avi'
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
# Se establece que el video se almacena el contenido en la variable archivo_video con una tasa de refresco
# de 20 cuadros/segundo y una resolucion 640x480
video = cv2.VideoWriter(archivo_video, fourcc, 20, (640, 480))
camara =... | omarjcm/p59-programacion_hipermedial | code/ra/02_camara.py | 02_camara.py | py | 785 | python | es | code | 1 | github-code | 1 |
9903202895 | from django.urls import reverse_lazy
from django.views.generic import ListView
from django.views.generic.edit import CreateView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.edit import DeleteView
from .models import Thing
class ThingLis... | oryon-dominik/skeleton-django-postgres-docker | apps/things/views.py | views.py | py | 1,089 | python | en | code | 2 | github-code | 1 |
21173485215 | import matplotlib.pyplot as plt
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, s=40)
# plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='nome', s=40)
# Definindo o titulo do gráfico e nomeia os eixos x e y
plt.title("Square Num... | martinssantoscristiano/Gerando_Dados | scatter_squares.py | scatter_squares.py | py | 741 | python | pt | code | 1 | github-code | 1 |
3501269202 | #!/usr/local/bin/python
import sys
import csv
reader = csv.reader(sys.stdin, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n\r')
for line in reader:
#if it's the header, we skip it
if line[0] == "id":
continue
#if question, id = node_id; if comment id = abs_parent_id
... | scepas/forum-mr | MapperStudentsThread.py | MapperStudentsThread.py | py | 445 | python | en | code | 0 | github-code | 1 |
74269633954 | """
Title : alphabeth_position.py
Source : Module 1 Remed Purwadhika no.4
Summary : Buatlah suatu fungsi yang menerima string, dimana setiap huruf di string tersebut digantikan dengan posisinya di urutan alphabet.
Bila ada string lain selain huruf alphabet, jangan dihiraukan ... | laksonodimitrij/Remedial-Modul-1 | Remed_04_Alphabet_Position.py | Remed_04_Alphabet_Position.py | py | 1,667 | python | en | code | 0 | github-code | 1 |
2888530327 | import sys
snput = sys.stdin.buffer.readline
m_snput = lambda: map(int, snput().split())
MAX = 2 * 10 ** 5 + 1
if __name__ == "__main__":
N, W = m_snput()
all_time = [0] * MAX
first = MAX
last = 0
# imos
for _ in range(N):
s, t, p = m_snput()
all_time[s] += p
all_time[t]... | Kumamoto-Hamachi/atcoder_pr | abc_contest/abc183/d/d2.py | d2.py | py | 739 | python | en | code | 1 | github-code | 1 |
32620909163 | from xml.parsers import expat
import textInfos
from logHandler import log
class XMLTextParser(object):
def __init__(self):
self.parser=expat.ParserCreate('utf-8')
self.parser.StartElementHandler=self._startElementHandler
self.parser.EndElementHandler=self._EndElementHandler
self.parser.CharacterDa... | atsuoishimoto/tweetitloud | source/XMLFormatting.py | XMLFormatting.py | py | 1,394 | python | en | code | 1 | github-code | 1 |
20848266733 |
def assert_http2(_file, stmt):
"assert ssl with http2, return True if it's a SSL server."
if stmt['directive'] == 'listen':
port = int(stmt['args'][0].split(':')[-1])
if port == 443:
assert 'http2' in stmt['args'], \
"HTTP/2 everywhere : %s #%i" % (_file, stmt['line'... | factorysh/assert-nginx | assert_nginx/asserts.py | asserts.py | py | 1,091 | python | en | code | 0 | github-code | 1 |
32599542666 | #!/usr/bin/python3
from typing import List
import json
from bplib.butil import TreeNode, arr2TreeNode, btreeconnect
from collections import deque
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
s... | negibokken/sandbox | leetcode/117_populating_next_right_pointers_in_each_node_II/main.py | main.py | py | 907 | python | en | code | 0 | github-code | 1 |
5574350066 | '''
O(1) complexity
Comparsion. For instance, we have two variables a and b. And when we doing this a==b we just take a and b from the memory and compare them.
Let's define "c" as cost of memory, and "t" as cost of time.
In this case we're using 2c (because we're using two cells of the memory) and 1t (because ther... | yungjas/Tech-Interview-Qns-Practice | easy/palindrome.py | palindrome.py | py | 816 | python | en | code | 0 | github-code | 1 |
34666613900 | print("hola, bienvenido ")
p1=int(input("por favor indique el peso del paquete "))
d1=int(input("por favor digite la distancia a la que se va a enviar el paquete en kilometros "))
if p1<10:
print("el paquete ha sido rechazado porque el peso esta por debajo del minimo ")
precio=(p1*1500)+(d1*4000)
if p1>100:
i... | julife12/prueba | valordescuento.py | valordescuento.py | py | 806 | python | es | code | 0 | github-code | 1 |
1607549456 | import random
import time
p=random.sample(range(1,1000000),20000)
elem=0
start=time.time()
k=0
for i in range(0,len(p)):
if elem==p[i]:
print("Found at ", i)
k=1
break
if k==0:
print("Not Found")
print("Time Taken:",time.time()-start)
| love-0710/algorithm-lab | 3.2_linear.py | 3.2_linear.py | py | 300 | python | en | code | 0 | github-code | 1 |
672255385 | # Name: Agnes Li
# CSE 160
# Autumn 2021
# Final Exam
from operator import itemgetter
# Problem 1
def least_exp_store(ingred_price_dict, ingred1, ingred2):
'''
Arguments:
ingred_price_dict: a dict of price_lists
ingred1, ingred2: 2 strings representing ingredients
Returns:
A list... | getachew67/CSE-160 | Final Exam/final_21au.py | final_21au.py | py | 5,308 | python | en | code | 0 | github-code | 1 |
20265749918 | import time
from abc import ABCMeta, abstractmethod
from ..base import Patch, Algorithm
class LocalSearch(Algorithm):
"""
Local Search (Abstact Class)
All children classes need to override
* :py:meth:`get_neighbour`
.. hint::
Example of LocalSearch class. ::
class MyLocalSea... | coinse/pyggi | pyggi/algorithms/local_search.py | local_search.py | py | 5,817 | python | en | code | 28 | github-code | 1 |
4850984677 |
def export_causatives(adapter, collaborator):
"""docstring for export_causatives"""
#put variants in a dict to get unique ones
variants = {}
for variant in adapter.get_causatives(institute_id=collaborator):
variant_id = '_'.join(variant.variant_id.split('_')[:-1])
variants[variant... | gitter-badger/scout | scout/export/variant.py | variant.py | py | 798 | python | en | code | null | github-code | 1 |
26693079992 | import numpy as np
import pandas as pd
text_file = open('../inputs/day12/input.txt', 'r')
lines = text_file.read().splitlines()
def check_small_caves(path, vertexes):
one_small_cave_double = False
for v in vertexes:
if v.islower() and path.count(','+v) > 1:
if one_small_cave_double: # >1 ... | realmistic/advent_of_code_2021 | solutions/day12.py | day12.py | py | 1,981 | python | en | code | 0 | github-code | 1 |
41204473377 | """
Hangman Game
Auther: Marvyn Bailly
Version: 0.02
Play Hangman
"""
from os import system, name
import random
def loadWords():
words = []
with open('words.txt','r') as f:
for line in f:
for word in line.split():
words.append(word)
return words
def chooseWord(words):
"""
wor... | MarvynBailly/MarvynBailly.github.io | games/hangman/hang_man.py | hang_man.py | py | 4,310 | python | en | code | 0 | github-code | 1 |
31461333551 | # Get the PIDs of datasets in a given dataverse (and optionally any dataverses in that dataverse).
# Includes deaccessioned datasets. Excludes harvested and linked datasets.
import csv
import glob
import json
import os
import requests
import sys
import time
from tkinter import filedialog
from tkinter import ttk
from t... | jggautier/dataverse-scripts | other_scripts/get_dataset_PIDs.py | get_dataset_PIDs.py | py | 15,027 | python | en | code | 5 | github-code | 1 |
410962230 | """Provides a lift over annotator and helpers."""
import logging
from typing import Any, Optional
from dae.annotation.annotation_pipeline import AnnotationPipeline
from dae.annotation.annotation_pipeline import Annotator
from dae.annotation.annotation_pipeline import AnnotatorInfo
from dae.annotation.annotation_pipel... | iossifovlab/gpf | dae/dae/annotation/liftover_annotator.py | liftover_annotator.py | py | 7,386 | python | en | code | 1 | github-code | 1 |
70977147233 | """Training module for nondefaced-detector."""
import os
import math
import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.utils import class_weight
from tensorflow.keras import backend as K
from tensorflow.keras import metrics
from tensorflow.keras.optimizers import Adam
from tensorflow.keras... | nipreps/nondefaced-detector | nondefaced_detector/training/training.py | training.py | py | 6,609 | python | en | code | 6 | github-code | 1 |
72592409635 | import json
from lemon.app import Lemon
from lemon.const import HTTP_METHODS
from lemon.request import HttpHeaders
class ASGIResponse:
def __init__(self, status, headers: HttpHeaders, content):
self.status = status
self.headers = headers
self.content = content
@property
def statu... | joway/lemon | tests/asgi.py | asgi.py | py | 3,904 | python | en | code | 28 | github-code | 1 |
71679994274 | import re
import json
from lib.configLoader import config
from lib.xlsGetter import request_table
template = {
'weeks': config['weeks'],
'lessons': config['lessons'],
'blank': config['blank'],
'time': config['time'],
'courses': config['courses']
}
footer_match_list = [
'(体育).+?◇(.+?)◇(\\d+-\\... | Chenrt-ggx/CTWC | public/lib/xlsParser.py | xlsParser.py | py | 3,864 | python | en | code | 1 | github-code | 1 |
28416420424 | #!/usr/bin/env python3
a = [1,2]
b = [0,1,2,3]
if a in [b[i:i+len(a)] for i in range(len(b))]:
print(True)
for i in range(len(a)):
if a == b[i:i+len(a)]:
print("Matched from {}".format(i))
| 10sr/junks | python/sublist.py | sublist.py | py | 209 | python | en | code | 0 | github-code | 1 |
14124670906 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
SETTINGS_RENAMES = (
("SHOP_SSL_ENABLED", "SSL_ENABLED"),
("SHOP_SSL_FORCE_HOST", "SSL_FORCE_HOST"),
)
class Migration(DataMigration):
def forwards(self, orm):
"Write your f... | phodal/echoes | conf/migrations/0004_ssl_account_settings_rename.py | 0004_ssl_account_settings_rename.py | py | 1,887 | python | en | code | 14 | github-code | 1 |
41973501255 | from musikla.core.events.transformers.transformer import Transformer
from musikla.core.events.transformers.balance_notes import BalanceNotesTransformer
from musikla.core.events.transformers.compose_notes import ComposeNotesTransformer
from musikla.audio.player import PlayerLike
from musikla.audio.interactive_player imp... | pedromsilvapt/miei-dissertation | code/musikla/musikla/libraries/keyboard/buffer.py | buffer.py | py | 7,137 | python | en | code | 0 | github-code | 1 |
38094427184 | import pytest
from tests.utils import assertDictContainsKeyWithValue
from wiremock.resources.mappings import (
AllMappings,
BasicAuthCredentials,
DelayDistribution,
DelayDistributionMethods,
Mapping,
MappingMeta,
MappingRequest,
MappingResponse,
)
@pytest.mark.unit
@pytest.mark.serial... | wiremock/python-wiremock | tests/test_resources/test_mapping/test_mapping_serialization.py | test_mapping_serialization.py | py | 12,311 | python | en | code | 44 | github-code | 1 |
23778588737 | import json
#省和城市的逻辑
class NationalCities(object):
def choice(self,prct):
provice = tuple(prct().keys())
provices = list()
for pro in provice:
provices.append((pro,pro))
citys_list = sum(list(prct().values()),[])
citys = list()
for city in citys_list:
... | hsztyw/testswiper | ztc/ztc/ztc/api_cof.py | api_cof.py | py | 1,238 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.