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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33881074633 | from euclide import solve_chinese_remainders
from utils import timeit
@timeit
def get_data():
with open('input.txt') as input_file:
timestamp = int(input_file.readline())
buses = input_file.readline().strip().split(',')
return timestamp, buses
def get_time(timestamp, bus):
time = timesta... | bdaene/advent-of-code | 2020/day13/solve.py | solve.py | py | 1,351 | python | en | code | 1 | github-code | 1 |
31257724932 | """
Create a chart showing movie recommendation frequencies and save as
an Altair JSON for displaying on a webpage
"""
import pandas as pd
import altair as alt
from sql_tables import connect_to_db, read_tables
from sql_tables import HOST, PORT, USERNAME, PASSWORD, DB
def create_frequency_chart(engine,
... | soil55/flannflix | frequency_chart.py | frequency_chart.py | py | 3,101 | python | en | code | 0 | github-code | 1 |
74632508833 | # Programa: Ejercicio8 calcularSueldoTotal.py
#
# Proposito: Un vendedor recibe un sueldo base mas un 10% extra por comisión de sus ventas,
# el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por las tres ventas que realiza en el mes
# y el total que recibirá en el mes to... | jlalvarezfernandez/Python | I Trimestre/secuencialesPython/calcularSueldoTotal.py | calcularSueldoTotal.py | py | 1,613 | python | es | code | 0 | github-code | 1 |
72490710755 | from collections import deque
class Solution:
def validUtf8( data: 'list[int]') -> bool:
start = 0
#data a deque for easy poping so that we can go through the list of nums effeciently
data = deque(data)
try:
while data:
#& means only the overlapping w... | lucasrouchy/validUTF | validUTF.py | validUTF.py | py | 2,379 | python | en | code | 0 | github-code | 1 |
72556059235 | #!/usr/bin/python3
"""A Base class"""
import json
import turtle
import csv
class Base:
"""A Base class"""
__nb_objects = 0
def __init__(self, id=None):
"""constructor for Base class
Args:
id (int): an id attribute. Defaults to None.
"""
if id is not None:
... | Martin-do/alx-higher_level_programming | 0x0C-python-almost_a_circle/models/base.py | base.py | py | 5,721 | python | en | code | 0 | github-code | 1 |
2313246928 | from API_request import get_price
import telebot
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
'start': '1',
'limit': '5000',
'convert': 'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'CMC api-key',
}
bot = teleb... | axyzz/exrbot | main.py | main.py | py | 765 | python | en | code | 0 | github-code | 1 |
9378055793 | import os
import json
import time
import requests
from math import floor
import vlc
def download():
print('We need to download data from the web...one moment')
URL = "http://91.132.145.114/json/stations"
response = requests.get(URL)
if response.status_code == 200:
open("stations", "wb").write(r... | maccu71/projects | stacje.py | stacje.py | py | 2,542 | python | en | code | 0 | github-code | 1 |
71942633953 | # kdc server
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
CLIENT_KEY="CLIENT_KEY"
TGS_KEY="TGS_KEY"
SERVER_KEY="SERVER_KEY"
CT_SK="CT_SK"
CS_SK="CS_SK"
DATA_SERVER='http://localhost:8002'
class MyHandler(BaseHTTPRequestHandler):
def SendRep(self, data):
self.send_response(200)... | WangWeiPengHappy/simple_kerberos | source/kdc.py | kdc.py | py | 2,319 | python | en | code | 0 | github-code | 1 |
30171935940 | from objects.anyPage import anyPage
from objects.customParser import parser
from os.path import dirname, abspath
from configparser import ConfigParser
import json
class configurator:
def __init__(self,value):
configParser = ConfigParser()
self._configPath = dirname(dirname(abspath(__file__))) + "/config/config.... | giantpanda9/codesamples-python3-gevent-site-parser | objects/customCrawlerConfigurator.py | customCrawlerConfigurator.py | py | 2,833 | python | en | code | 0 | github-code | 1 |
72780642275 | import os
import smtpd
import sys
import asyncore
import email
from email.header import decode_header
########################################################################
#
#
# IF YOU CHANGE THIS FILE, YOU HAVE TO REBUILD THE DOCKER CONTAINER
# THE CURRENT manual_run.py will not detect changes
#
#
###############... | bjcoleman/katacoda-scenarios | git-keeper-tutorial/assets/mysmtpd.py | mysmtpd.py | py | 2,486 | python | en | code | 0 | github-code | 1 |
20246478938 | import sys
N,M= map(int, sys.stdin.readline().split())
maps=[]
for i in range(N):
a=sys.stdin.readline().strip()
maps.append(a)
state=set([])
state.add((0,0,maps[0][0])) #count, row,column, 거쳐온 load
dx=[0,0,1,-1]
dy=[1,-1,0,0]
#dist=[[0]*M for _ in range(N)]
solution=1
while state:
x,y,load=state.pop()
... | jhan-04/Test | baekjoon/no.1987.py | no.1987.py | py | 806 | python | en | code | 0 | github-code | 1 |
38566374238 | import torch
import cv2
import numpy as np
import math
from sklearn.metrics import f1_score
from torch.autograd import Variable
from matplotlib.image import imread
# function for colorizing a label image:
def label_img_to_color(img: torch.Tensor):
# label_to_color = {
# 0: [128, 64,128],
# 1: [24... | ZombaSY/Pore-Net-release | models/utils.py | utils.py | py | 27,246 | python | en | code | 0 | github-code | 1 |
26281913404 | #An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps, for every step it was noted if it was an uphill, , or a downhill, step.
#Hikes always start and end at sea level, and each step up or down represents a unit change in altitude. We define the following terms:
#A mou... | livanshu/Data_Science_Portfolio | Hackerrank/Preperation Kit/Counting valleys.py | Counting valleys.py | py | 1,632 | python | en | code | 0 | github-code | 1 |
38948765806 | import cmk.utils.bi.bi_legacy_config_converter
import bi_test_data.sample_config as sample_config
def test_bi_legacy_config_conversion(monkeypatch):
monkeypatch.setattr("cmk.utils.bi.bi_legacy_config_converter.BIManagement._get_config_string",
lambda x: sample_config.LEGACY_BI_PACKS_CONFIG... | superbjorn09/checkmk | tests/unit/cmk/utils/bi/test_bi_legacy_config_converter.py | test_bi_legacy_config_converter.py | py | 533 | python | en | code | null | github-code | 1 |
73380743073 | import numpy as np
import pandas as pd
from sklearn.metrics import log_loss
from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit
from keras.callbacks import ModelCheckpoint, Callback, EarlyStopping
from data_loader import get_data, generator
def cross_validation(model, X_train, X_train_angle, Y... | hzxsnczpku/nishiyami | train.py | train.py | py | 1,980 | python | en | code | 0 | github-code | 1 |
988817178 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 27 17:18:39 2021
@author: Dell
"""
import pandas as pd
from sklearn.utils import shuffle
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, cross_validate, cross_val_predict
from sklearn.model_selection import GridSea... | Slbalderrama/Phd_Thesis_Repository | Electrification_Path/Plot_Scenarios.py | Plot_Scenarios.py | py | 3,532 | python | en | code | 1 | github-code | 1 |
71728283555 | from fastapi import FastAPI, Cookie, Response
from typing import Union
from pydantic import BaseModel
from typing_extensions import Annotated
app = FastAPI()
@app.get("/books")
async def books(
ads_id: Annotated[Union[str, None], Cookie()]
):
return {
"code": 200,
"message": "访问成功",
... | Mengxin-yi/fastApiProject | mainCookie.py | mainCookie.py | py | 355 | python | en | code | 0 | github-code | 1 |
7774996029 | import random
candidates = ['가위', '바위', '보']
p1scissor, p1rock, p1paper = 0, 0, 0
p2scissor, p2rock, p2paper = 0, 0, 0
p1win, p1lose, p2win, p2lose, tie = 0, 0, 0, 0, 0
wintable = {
'가위' : '보',
'바위' : '가위',
'보' : '바위'
}
repeat = int(input('가위바위보를 몇 번 할까요?: '))
for i in range(repeat):
p1select = ran... | EscFrog/Try-helloworld-python | rockpaperscissors.py | rockpaperscissors.py | py | 2,873 | python | ko | code | 0 | github-code | 1 |
38755171884 | """
This module provides functionality to read an excel file containing
information about people and filter the rows based on a user's input by
communicating with a tcp server.
Functions:
send_message(message: str) -> str:
Sends a message to a server and returns the server's response.
read_request(name: str) -> None
... | Praveenstein/iot_training_codes_main | 01_tcp_ip/tcp_client_main.py | tcp_client_main.py | py | 3,723 | python | en | code | 0 | github-code | 1 |
2341338518 | '''
Question: You are in an infinite 2D grid where you can move in any of the 8 directions :
(x,y) to
(x+1, y),
(x - 1, y),
(x, y+1),
(x, y-1),
(x-1, y-1),
(x+1,y+1),
(x-1,y+1),
(x+1,y-1)
You are given a sequence of points and the order in which you need to cover the points. G... | yagamiram/Programming_challenges | reach.py | reach.py | py | 1,631 | python | en | code | 0 | github-code | 1 |
22237947724 | # -*- coding: utf-8 -*-
import pandas as pd
def read_data(file_path):
dataset = pd.read_csv(file_path)
'''
#查看并显示前三条记录
print(dataset.iloc[0:3,:])
print('-' * 30)
'''
# 查看样本数和特征数
print(dataset.shape)
print('-' * 30)
return (dataset)
def get_dict(dataset):
dataset.colum... | DarinaOsamu/predictors-of-cysteine-reactivity-changes | prediction/code/result_dict.py | result_dict.py | py | 2,991 | python | en | code | 0 | github-code | 1 |
4068587599 | '''
Write a Python program to append a new item to the end of the array
Original array: array('i', [1, 3, 5, 7, 9])
Append 11 at the end of the array:
New array: array('i', [1, 3, 5, 7, 9, 11])
'''
from array import *
class Array:
def __init__(self,a_array):
self.a_array=a_array
def add(self,num):
... | abhi776060/test | 28_12_2021/array2.py | array2.py | py | 434 | python | en | code | 0 | github-code | 1 |
11040403165 | import unittest
from .RFQTools import RFQTools
class MyTestCase(unittest.TestCase):
def test_initialization(self):
tools = RFQTools()
tools.RFQMatcherContext(3410)
self.assertEqual(True, True)
def test_qmaterial_matcher(self):
tools = RFQTools()
result = tools.Quote... | Conpancol/PyHeroku | CPFrontend/rfqs/services/RFQToolsTests.py | RFQToolsTests.py | py | 515 | python | en | code | 0 | github-code | 1 |
25645483609 | # coding = utf-8
import os
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset)
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, _input, _output = None):
"""Constru... | BruceQ74/Basic_NLG | data_utils.py | data_utils.py | py | 6,353 | python | en | code | 0 | github-code | 1 |
17145656675 | import json
import flask
from flask import request
from datetime import datetime
import psycopg2
from flask import make_response
from werkzeug import exceptions
import waitress
app = flask.Flask(__name__)
def query(sql, *args):
with psycopg2.connect("dbname=nosp_walk user=postgres") as conn:
with conn.... | Nosp27/nosp-walk | backend/app_init.py | app_init.py | py | 2,329 | python | en | code | 0 | github-code | 1 |
17127249082 | import numpy as np
import pandas as pd
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
from multiprocessing import Pool
from functools import partial
from sklearn.model_selection import KFold
from MatrixFactorization import FactorizeMatrix, GetRepresentationError, CreateLatentVariables
from FeatureSi... | psturmfels/cfAD | CrossValidation.py | CrossValidation.py | py | 6,649 | python | en | code | 1 | github-code | 1 |
35823004636 | #!/usr/bin/env python3
print("please enter count number: ")
N = int(input())
# N = 10
sum = 0
count = 0
print("please enter",N,"numbers: ")
while count < N:
number = float(input())
sum = sum + number
count = count + 1
average = sum / N
print("N = {}, Sum = {}".format(N, sum))
print("average = {:.2f}".format... | Rayme/python | averagen.py | averagen.py | py | 331 | python | en | code | 0 | github-code | 1 |
42426696313 | import sys
input=sys.stdin.readline
n,m,k=map(int,input().split())
c=list(map(int,input().split()))
friend=[i for i in range(n+1)]
def find(friend,x):
if x!=friend[x]:
friend[x]=find(friend,friend[x])
return friend[x]
def union(friend,a,b):
rootA=find(friend,a)
rootB=find(friend,b)
if root... | jhchoy00/baekjoon | 20303.py | 20303.py | py | 984 | python | en | code | 0 | github-code | 1 |
75186994912 | items = []
numbers = []
def add_item():
item_name = input("Enter the item name: ")
number = float(input("Enter the associated number: "))
items.append(item_name)
numbers.append(number)
def remove_item():
print("Items in the collection:")
for i, item in enumerate(items, start=1):
print(... | ranveerhothi/List-App-Project | main.py | main.py | py | 2,530 | python | en | code | 0 | github-code | 1 |
37404377541 | #!/usr/bin/env python3
# coding: utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import multiprocessing as mp
import math
import plotly
from plotly.graph_objs import Scatter, Line
import numpy as np
from numpy.lib.stride_tricks import as_strided as ast
from scipy.ndimage import ga... | chenaddsix/pytorch_a3c | utils.py | utils.py | py | 7,553 | python | en | code | 1 | github-code | 1 |
5065913081 | """Transforms for preprocessing images during data loading"""
import PIL
import torch
import copy
import numpy as np
def img_pad(img, mode='warp', size=224):
"""
Pads a given image.
Crops and/or pads a image given the boundries of the box needed
img: the image to be coropped and/or padded
bbox: th... | DongxuGuo1997/TransNet | src/transform/transforms.py | transforms.py | py | 6,739 | python | en | code | 6 | github-code | 1 |
74004351074 | class Pizza:
'''
Pizza class to define Pizza Objects
'''
def __init__(self,id,title,overview,image,vote_average,vote_count):
self.id = id
self.title= title
self.overview = overview
self.vote_average = vote_average
self.vote_count = vote_count
| dishonkuria/pizza_shop | app/models/pizza.py | pizza.py | py | 300 | python | en | code | 0 | github-code | 1 |
39892102996 | # Scrapy settings for acvo_org project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'acvo_org'
SPIDER_MODULES = ['acvo_org.spiders']
NEWSPIDER_MODULE = 'acvo_o... | tcdvm/ACVO | acvo_org/acvo_org/settings.py | settings.py | py | 644 | python | en | code | 0 | github-code | 1 |
31267879602 | from rest_framework.fields import IntegerField
from rest_framework.serializers import ModelSerializer, Serializer
from post.models import Post, PostLike
class PostCreateSerializer(ModelSerializer):
class Meta:
model = Post
fields = (
'id',
'text',
'author_id',
... | RomanDemianenko/starnavi | post/api/serialzers.py | serialzers.py | py | 754 | python | en | code | 0 | github-code | 1 |
23657966447 | #!Python-2.7.11/bin/python
import os,sys
import argparse
import numpy as np
import copy
sys.path.append('Python-2.7.11/lib/python2.7/site-packages')
from ete2 import Tree,TreeStyle,TextFace,NodeStyle
parser = argparse.ArgumentParser(description='Phylogenetic Tree analysis for Cancer Evolution.')
parser.add_argument('-... | gda7090/cancer | phylogenetic_tree_phylip.py | phylogenetic_tree_phylip.py | py | 13,457 | python | en | code | 1 | github-code | 1 |
6953564000 | from django.http import HttpResponseRedirect, HttpResponse
from django.core.mail import send_mail
from django.shortcuts import render
from contacto.forms import FormularioContactos
from django.template import loader
# Create your views here.
def contactos(request):
#form=FormularioContactos()
if request.metho... | JokerBerlin/python | contacto/views.py | views.py | py | 983 | python | en | code | 0 | github-code | 1 |
73737550115 | # -*- coding: utf-8 -*-
"""Base controller to interact with the Sofa scene.
"""
__authors__ = "emenager, tnavez"
__contact__ = "etienne.menager@inria.fr, tanguy.navez@inria.fr"
__version__ = "1.0.0"
__copyright__ = "(c) 2020, Inria"
__date__ = "Jul 29 2022"
import Sofa
class BaseVisualizationController(Sofa.Core.Con... | SofaDefrost/CondensedFEMModel | Libraries/Simulation/DirectControllers/BaseVisualizationController.py | BaseVisualizationController.py | py | 4,487 | python | en | code | 1 | github-code | 1 |
17481379343 | nums = '123456789'
def pandigital(str):
"""Check whether 'str' contains ALL of the chars in 'nums'"""
return 0 not in [c in str for c in nums]
def multiples(num,n):
tor = ""
for i in range(1,n+1):
tor += str(num*i)
return tor
print(multiples(192,3))
print(pandigital(multiples(192,3)))
largest = 0
p = ""... | pussinboot/euler-solutions | euler_38.py | euler_38.py | py | 541 | python | en | code | 0 | github-code | 1 |
26184567771 | # %%
import torch
import torch.nn as nn
import torch.optim as optim
import torchtext
from torchtext.data import Field, BucketIterator, TabularDataset
from torchtext.data.functional import sentencepiece_tokenizer, load_sp_model
from pathlib import Path
import dill
import numpy as np
import os
import random
import re... | mmcux/de-nds-translation | translate_input.py | translate_input.py | py | 18,238 | python | en | code | 32 | github-code | 1 |
19890027037 | import torch
import numpy as np
import torch.nn as nn
import math
from PIL import Image
import os
from core.constants import palette, NUM_CLASSES, IGNORE_LABEL
def denorm(x):
out = (x + 1) / 2
return out.clamp(0, 1)
def norm(x):
out = (x - 0.5) * 2
return out.clamp(-1, 1)
def reset_grads(model, requi... | shahaf1313/ProCST | core/functions.py | functions.py | py | 9,425 | python | en | code | 25 | github-code | 1 |
18773450898 | import os, math, sys
from collections import Counter
def get_vocabulary(item_class):
class_vocabulary = []
for filename in os.listdir('train/' + item_class):
file = open(os.path.join('train/' + item_class, filename), encoding='latin-1')
class_vocabulary += [word for line in file for word in li... | myociss/probabilistic-classifiers | bayes.py | bayes.py | py | 3,170 | python | en | code | 0 | github-code | 1 |
42894401315 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 17:57:13 2019
@author: jcunanan
"""
#######################################
# Problem Description
#Bob the Adventurer is one step away from solving the mystery of an ancient Mayan tomb.
#He just approched the secret chamber where the secre... | j-cunanan/Fun-Algorithm-Problems | Destroy_all_statues.py | Destroy_all_statues.py | py | 3,311 | python | en | code | 0 | github-code | 1 |
36221665148 | import numpy as np
import os
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing databa... | epayne323/sqlalchemy-challenge | app.py | app.py | py | 6,008 | python | en | code | 0 | github-code | 1 |
24087040276 | # Сохраяем ИД пользователя/ИД ответа/значение ответа
# Собираем ответы - делаем словарь ответов и возвращаем
# Возвращаем список словарей-ответов
import os
def start_file():
f = open('users_data.csv','w')
f.close()
def insert_data(id,question_id,question_value):
f = open('users_data.csv','a')
f... | mikh-maksi/techs_of_development | python/registration/question-files-check.py | question-files-check.py | py | 3,819 | python | en | code | 0 | github-code | 1 |
26815440104 | from keras.models import Sequential, load_model
from keras.layers import Embedding, Conv1D, MaxPooling1D, LSTM, GRU, Dense
from keras.layers.wrappers import Bidirectional
y_idx2word=8
def run_classifier(x_train_seq,x_test_seq,y_train_one_hot,y_test_one_hot):
model = Sequential()
print("-----------------------... | NehalAB/Text_Classifier | multi_class_neural_network.py | multi_class_neural_network.py | py | 1,777 | python | en | code | 0 | github-code | 1 |
32976833994 | from token_daniel import token
cabecalho_api_github = {
'Content-Type': 'application/json',
'Authorization': f"Bearer {token}"
}
colunas_node = ['nome', 'linguagem', 'stargazes', 'watchers', 'data_criacao', 'forks', 'url', 'releases']
colunas_repo_loc = ['nome', 'loc'] | danielWagnerr/lab6 | Lab01_02/script/configuracao.py | configuracao.py | py | 281 | python | pt | code | 0 | github-code | 1 |
12043921117 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
curr=head
sum1=0
dummy=ListNode(0)
dum=dummy
... | Kruti-02/LeetCode | 2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.py | 2181-merge-nodes-in-between-zeros.py | py | 575 | python | en | code | 0 | github-code | 1 |
22860088317 | # -*- coding: utf-8 -*-
from openerp import api, fields, models
from openerp import tools
class OperatingUnitView(models.Model):
# This class is solely for PABI2
_name = 'operating.unit.view'
_auto = False
name = fields.Char(
string='Name',
)
code = fields.Char(
string='Code',... | ecosoft-odoo/cmo_generic | operating_unit/models/operating_unit_view.py | operating_unit_view.py | py | 611 | python | en | code | 1 | github-code | 1 |
17315387689 | """
Code adapted from https://github.com/uvavision/Double-Hard-Debias/blob/master/eval.py
"""
import glob
import os
import numpy as np
from sklearn.utils import Bunch
from sklearn.cluster import AgglomerativeClustering, KMeans
from six import iteritems
def evaluate_categorization(word_vectors, X, y, method='kmeans', ... | YolandaMDavis/DoubleHardMulticlass | common/concept.py | concept.py | py | 5,620 | python | en | code | 0 | github-code | 1 |
40762266793 |
def getadd():
import requests
import json
import getip
ip = getip.get()
send_url = f'http://api.ipstack.com/{ip}?access_key=7cf3582503675544e752924eb3142e79&format=1'
r = requests.get(send_url)
j = json.loads(r.text)
lat = str(j['latitude'])
lon = str(j['longitude'])
print(la... | usthandwa/WeThinkCode_Work | Matcha/views/functions.py | functions.py | py | 1,063 | python | en | code | 0 | github-code | 1 |
31666142254 | # author: sunshine
# datetime:2021/8/5 下午3:17
import torch
import torch.nn as nn
from transformers import BertModel
class SMPNet(nn.Module):
def __init__(self, args, num_class):
super(SMPNet, self).__init__()
self.bert = BertModel.from_pretrained(args.bert_path)
self.fc1 = nn.Sequential(
... | fushengwuyu/smp2020_ewect | src/model.py | model.py | py | 1,411 | python | en | code | 1 | github-code | 1 |
33008352550 | import keyboard
import time
import random
from ctypes import windll, wintypes, byref
from functools import reduce
from cafe_coding_download import enable
enable()
f = open('cafe_coding_download.py', 'r', encoding='UTF-8')
data = f.read()
f.close()
i = 0
s = ''
while True:
if keyboard.read_key():
s += d... | Yotty0404/Cafe_Coding | cafe_coding_keyboard.py | cafe_coding_keyboard.py | py | 741 | python | en | code | 2 | github-code | 1 |
22025020858 | import networkx as nx
from random import randint
from math import exp
import numpy as np
from typing import List, Dict, FrozenSet, Iterator, Tuple
from pydantic import BaseModel
from .graph_utils import (
list_subsets_of_given_size,
pairs_of_sets,
)
class SubtreeData(BaseModel):
agg_root: int
agg_size... | sowiks2711/color-coding-subtree-isomorphism | color_coding/time_optimised_alg.py | time_optimised_alg.py | py | 8,360 | python | en | code | 0 | github-code | 1 |
19845668758 | from django.shortcuts import render
from .forms import UploadTransactionFileForm
from .models import TransactionFIles, Transactions
from .serializers import TransactionnsSerializer
from .utils.mixins import TransactionMixin
from rest_framework.generics import ListCreateAPIView
from rest_framework.views import APIView, ... | reisquaza/CNAB | transactions/views.py | views.py | py | 3,344 | python | en | code | 0 | github-code | 1 |
2226540156 | from dataclasses import dataclass, field
# dataclass ja cria para nós o init, repr e eq
@dataclass(init=True)
class Pessoa:
_nome: str
_idade: float
enderecos: list[str] = field(default_factory=list)
def __post_init__(self):
print("depois do init")
@property
def nome(self):
... | michaelmedina10/estudos-python | oop/dataclass.py | dataclass.py | py | 411 | python | pt | code | 1 | github-code | 1 |
39099255085 | import queue
from threading import Thread
import numpy as np
from transformers import *
from openie import StanfordOpenIE
from utility.utility import *
#from bert_serving.client import BertClient
from rouge import Rouge
from stanfordcorenlp import StanfordCoreNLP
import pickle
from data.raw_data_loader import... | RuifengYuan/FactExsum-coling2020 | make_data.py | make_data.py | py | 18,770 | python | en | code | 17 | github-code | 1 |
1063359949 | from django.db import models
class BaseModel(models.Model):
created_at = models.DateTimeField(
"Data de Criação", auto_now=False, auto_now_add=True
)
modified_at = models.DateTimeField(
"Data de Modificação", auto_now=True, auto_now_add=False
)
class Meta:
abstract = True
... | CleysonPH/cdm-unofficial-api | mangas/models.py | models.py | py | 2,848 | python | en | code | 0 | github-code | 1 |
42745367065 | import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from custom_interfaces.srv import ComponentStatus
class PerceptionNode(Node):
def __init__(self):
super().__init__('perception_node')
self.cameraSubscriber = self.create_subscription(
String,
'camera',
self.c... | fablabiub1/ros_project | install/perception/lib/python3.10/site-packages/perception/perception_node.py | perception_node.py | py | 1,618 | python | en | code | 0 | github-code | 1 |
25410789355 | import optparse
import xml.etree.ElementTree
from util import build_utils
MANIFEST_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="%(package)s"
split="%(split)s">
<uses-sdk android:minSdkVersion="21" />
<application and... | hanpfei/chromium-net | build/android/gyp/generate_split_manifest.py | generate_split_manifest.py | py | 2,284 | python | en | code | 289 | github-code | 1 |
16863144799 | from __future__ import absolute_import
import errno
import os
from oio.common.easy_value import debinarize
def read_user_xattr(fd):
"""Read all extended attributes starting with "user." """
if hasattr(fd, "fileno"):
fd = fd.fileno()
meta = {}
try:
meta = debinarize(
{
... | open-io/oio-sds | oio/common/xattr.py | xattr.py | py | 667 | python | en | code | 621 | github-code | 1 |
6781656863 | # 두 요소의 위치를 바꿔주는 helper function
def swap_elements(my_list, index1, index2):
# 코드를 작성하세요.
my_list[index1],my_list[index2]=my_list[index2],my_list[index1]
# 퀵 정렬에서 사용되는 partition 함수
def partition(my_list, start, end):
# 코드를 작성하세요.
b=start
i=start
p=end
pivot=my_list[p]
while 1:
i... | Hyunjong1461/python | 200307/퀵정렬.py | 퀵정렬.py | py | 1,315 | python | ko | code | 0 | github-code | 1 |
1986352570 | from ctypes import alignment
from tkinter import *
from tkinter import messagebox as mb
import json
#Class for GUI components
class Assessment(object):
def __init__(self, database_filename, gui):
#Snag data
with open(database_filename) as f:
data = json.load(f)
se... | ChHarding/grit-scale-HCI584 | grit-scale_CH.py | grit-scale_CH.py | py | 7,484 | python | en | code | null | github-code | 1 |
24485972564 | import sys
import math
import time
m = 26
n = 3
barList = [1, 2, 3,4,5,6,7,8]
ergListSumme = []
ergListSumme.append([1,3,4,7,10])
ergListSumme.append([1,3,4,8,10])
ergListSumme.append([1,2,5,8,10])
ergListSumme.append([1,2,5,9,9])
ergListSumme.append([1,1,5,8,10])
erg = ""
ergList = []
ergebnis = []
laenge = 99
zwE... | mw197hub/codingame | easy/Gold Packing/testGold.py | testGold.py | py | 1,112 | python | de | code | 0 | github-code | 1 |
12137137685 | import datetime
class Message:
"""Represents a message sent to a chat.
Attributes
----------
chat: :class:`models.Chat`
The chat the message belongs to
type: :class:`str`
The type of message sent
id: :class:`str`
The id of the message
content: :class:`str`
... | A-Trash-Coder/dlive.py | dlive/models/message.py | message.py | py | 1,232 | python | en | code | 4 | github-code | 1 |
74246693794 | # https://leetcode.com/problems/valid-anagram/
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_hash = {}
t_hash = {}
for i in range(len(s)):
s_hash[s[i]] = s_hash.get(s[i], 0) + 1
t_hash[t[i]] = t_hash.get(t[i], 0) + 1
if len(s_hash) != len(t_h... | kevinjunge/leetcode_problems | valid_anagram.py | valid_anagram.py | py | 453 | python | en | code | 0 | github-code | 1 |
28413956290 | import json, os, requests, subprocess
# Your Discogs username and API key
username = ''
api_key = ''
# The ID of the folder containing your collection
folder_id = 0
# Base URL for Discogs API
base_url = 'https://api.discogs.com'
# Endpoint for retrieving collection releases
endpoint = f'/users/{username}/collection... | notaSWE/wallofrecords | local_option/get_collection.py | get_collection.py | py | 1,616 | python | en | code | 0 | github-code | 1 |
17977485378 | # implementation based on DeepLTL https://github.com/reactive-systems/deepltl
import tensorflow as tf
from dlsgs.transformer import attention
from dlsgs.transformer import positional_encoding as pe
from dlsgs.transformer.common import create_padding_mask, create_look_ahead_mask
from dlsgs.transformer.beam_search impo... | ju-kreber/Transformers-and-GANs-for-LTL-sat | impl/dlsgs/transformer/base.py | base.py | py | 16,431 | python | en | code | 1 | github-code | 1 |
13382414004 | import unittest
import subprocess
import os
import numpy as np
from openfermion import (
QubitOperator, InteractionOperator, FermionOperator, IsingOperator,
get_interaction_operator, hermitian_conjugated
)
from zquantum.core.circuit import build_uniform_param_grid
from zquantum.core.utils import create_object
f... | wugaxp/qe-openfermion | src/python/qeopenfermion/_io_test.py | _io_test.py | py | 4,933 | python | en | code | 1 | github-code | 1 |
28663203794 | import os
from dotenv import load_dotenv
import sqlalchemy
from sqlalchemy import join
from sqlalchemy.orm import sessionmaker, query
from models import create_tables, Publisher, Book, Shop, Stock, Sale
load_dotenv()
user = os.environ.get('USER')
password = os.environ.get('PASSWORD')
db = os.environ.get('DB')
DSN = f... | juicebiz/13-orm | main.py | main.py | py | 2,648 | python | en | code | 0 | github-code | 1 |
5263695237 | def solve():
N, M = map(int, input().split())
l = [-1, -1, -1]
for i in range(N+1):
for j in range(N-i+1):
if 1000 * i + 5000 * j + 10000 * (N-i-j) == M:
l = [i, j, N-i-j]
print(l[2], l[1], l[0])
print(solve())
| KushibikiMashu/at-coder-try | AtCoder_Biginners_Selection/085C.py | 085C.py | py | 264 | python | en | code | 0 | github-code | 1 |
25985254999 | # -*- coding:utf-8 -*-
"""
数据预处理
# goal_set.p 已划分train和dev
# goal_set_simul.p 就是test
# 其中 train = 1882 ,dev = 268
# 数据类型:{'consult_id': '10742613', 'disease_tag': '小儿支气管炎', 'goal': {'explicit_inform_slots': {'痰': '1'}, 'implicit_inform_slots': {'嗓子沙哑': '2'}}}
# 制作disease_set.p
# 制作slot_set.p
# 制作disease_symptom_set.p... | Ccccandy/20211208 | model3/data_preprocessing.py | data_preprocessing.py | py | 3,562 | python | en | code | 0 | github-code | 1 |
9396049033 | def find_square(m, n, board):
square = set()
for idx in range(m-1):
for jdx in range(n-1):
target = board[idx][jdx]
right = board[idx][jdx+1]
down = board[idx+1][jdx]
diag = board[idx+1][jdx+1]
if target and right and down and diag:
... | dhsong95/programmers-algorithm-challenges | 2018 KAKAO BLIND RECRUITMENT 1차/프렌즈4블록.py | 프렌즈4블록.py | py | 1,448 | python | en | code | 0 | github-code | 1 |
39910768806 | from common import *
#函数功能:读取一幅图片的多个mask文件并叠加
def mask_read_and_stack(mask_sub_dir, H, W):
mask = np.zeros((H, W), np.uint8)
mask_img_list = [mask_img for mask_img in os.listdir(mask_sub_dir)]
index = 0
for mask_img in mask_img_list:
index = index + 1
sub_mask = cv2.imread(mask... | Gaoyg/Nucleus-detection | data/preprocess.py | preprocess.py | py | 6,107 | python | en | code | 0 | github-code | 1 |
22594854315 | # 一个简单的读取csv文件的例子
#使用list来装在数据.
import csv
def reader(filepath) :
with open(filepath) as th :
toolreader=csv.reader(th)
list0=list(toolreader)
for list1 in list0 :
print(list1)
items=[
['1','Lawnmower','Small Hover mower','Fred','$150','Excellent','2012-01-05'],
['2','... | liwenjie0/python01 | csv_example/testcsv.py | testcsv.py | py | 824 | python | en | code | 0 | github-code | 1 |
13355817975 | class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
self.res = []
self.solve(s, "", 0)
return self.res
def solve(self, s, cur_s, idx):
if idx == len(s):
self.res.append(cur_s)
cur_s = cur_s[:-1]
return
... | Biruk-Tassew/Competitive_programming | 784-letter-case-permutation/784-letter-case-permutation.py | 784-letter-case-permutation.py | py | 699 | python | en | code | 0 | github-code | 1 |
34874712206 | '''
백준 20055 컨베이어 벨트 위의 로봇
삼성
'''
def count():
ans = 0
for temp in indure:
if temp == 0:
ans += 1
return ans
def rotate():
indure.insert(0, indure.pop())
robot.insert(0, robot.pop())
def drop_robot():
if robot[-1]:
robot[-1] = False
def robot_move():
for i in r... | CodeNinja1126/coding_test | coding_test_py/20055.py | 20055.py | py | 858 | python | en | code | 0 | github-code | 1 |
33843097301 | from transformers import ColorTransformer
from ..blend.blend import *
from ..palettes.core_palette import *
from ..scheme.scheme import *
from .image_utils import *
from .string_utils import *
# /**
# * Generate custom color group from source and target color
# *
# * @param source Source color
# * @param color C... | DimitrisMilonopoulos/mitsugen | src/material_color_utilities_python/utils/theme_utils.py | theme_utils.py | py | 3,222 | python | en | code | 88 | github-code | 1 |
74779771874 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, value):
if self == None:
self = value
elif self.data >= value.data:
if self.left == None:
self.left = value
else... | iyeranush/100daysOfCoding | 025_binary_search_tree.py | 025_binary_search_tree.py | py | 2,173 | python | en | code | 0 | github-code | 1 |
20454510000 | ### This is the LSTM training module ###
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Flatten, LSTM, Conv1D, MaxPooling1D, Dropout, Activation
from keras.layers.embeddings import Embedding... | Sang555/Multimodal-disaster-analysis | CODE/Text_training_module.py | Text_training_module.py | py | 2,674 | python | en | code | 0 | github-code | 1 |
33032274895 | import tensorflow as tf
import numpy as np
np.random.seed(2)
tf.set_random_seed(2) # reproducible
class Actor(object):
def __init__(self, sess, n_features, action_bound, lr=0.0001):
self.sess = sess
self.s = tf.placeholder(tf.float32, [1, n_features], "state")
self.a = tf.placeholder(tf... | FloraHF/2DSI | 2DSI/Actor.py | Actor.py | py | 3,283 | python | en | code | 0 | github-code | 1 |
74416921314 | from collections import defaultdict
# Utility function to create dictionary
def multi_dict(K, type):
if K == 1:
return defaultdict(type)
else:
return defaultdict(lambda: multi_dict(K-1, type))
with open('input-10.txt') as f:
lines = [row.strip() for row in f]
print(lines)
X=1
cycles = [... | fshsweden/AdventOfCode2022 | 10a.py | 10a.py | py | 805 | python | en | code | 0 | github-code | 1 |
14477324527 | from django import forms
from .models import Image
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title','url','description')
#我们的用户不会在表单中直接为图片添加 UR... | aangang/bookmarks | bookmarks/images/forms.py | forms.py | py | 2,247 | python | zh | code | 0 | github-code | 1 |
75059288672 | import numpy as np
from pprint import pprint
# define matrices
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
matrix3 = np.array([[19, 20, 21], [22, 23, 24], [25, 26, 27]])
# multiply matrices
result = np.dot(np.dot(matrix1, matrix2), matrix3)
# p... | vatsaaa/mtech | semester_1/03_assignments/Python/exercise02/06_multiply_3_matrices.py | 06_multiply_3_matrices.py | py | 347 | python | en | code | 0 | github-code | 1 |
3513686248 | import streamlit as st
from streamlit_player import st_player
column1, column2, = st.columns(2)
st.subheader("Send Email Receipts using automation")
st_player("https://youtu.be/G3fTz6VnnTc")
st.divider()
st.subheader("Recording Videos using Flonnect")
st_player("https://youtu.be/id_Oj7cG0Hs")
st.divider()
st.s... | madhuammulu8/FR-Analysis | pages/_👨🏽💻_Knowledge Transfer.py | _👨🏽💻_Knowledge Transfer.py | py | 725 | python | en | code | 0 | github-code | 1 |
39818017608 | #!/usr/bin/env python3
import json
import requests
import subprocess
session = requests.Session()
proc = subprocess.run(['git', 'for-each-ref', '--format=%(refname:lstrip=3)', 'refs/remotes/origin/??????????????????????????????????'],
stdout=subprocess.PIPE,
check=True,
)
to_delete = []
for branch in proc.stdo... | HsiangHo/macOS | .github/clean.py | clean.py | py | 882 | python | en | code | 0 | github-code | 1 |
24856926246 | # -*-coding:utf-8 -*-
import numpy as np
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
"""
Author:
Jack Cui
Blog:
http://blog.csdn.net/c406495762
Zhihu:
https://www.zhihu.com/people/Jack--Cui/
Modify:
2017-10-11
"""
def loadDataSet(fileName):
numFeat = len(... | Jack-Cherish/Machine-Learning | AdaBoost/sklearn_adaboost.py | sklearn_adaboost.py | py | 1,320 | python | en | code | 8,026 | github-code | 1 |
1704795648 | def findrange(W, l, maxindex, goal):
start = l
end = maxindex
while start <= end:
mid = (start + end) // 2
if W[mid] > goal:
end = mid - 1
else:
start = mid + 1
return start
def solution(weights):
answer = 0
weights.sort()
size = len(weights)... | SunghunKim98/Algorithm_Study | sprint11/KMS/실시간 문제풀이/시소짝궁.py | 시소짝궁.py | py | 810 | python | en | code | 0 | github-code | 1 |
73591823713 | #! /usr/bin/env python
# Import ROS.
import rospy
# Import the API.
from iq_gnc.py_gnc_functions import *
# To print colours (optional).
from iq_gnc.PrintColours import *
# Import 3D Plotting Library
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Import Kalman Filter Library
from pykalman imp... | khulqu15/smc_drone | ros_smc_kf/scripts/square.py | square.py | py | 5,474 | python | en | code | 1 | github-code | 1 |
21703164964 | # Author: Abdulaminkhon Khaydarov
# Date: 06/11/22
# Problem URL: https://leetcode.com/problems/running-sum-of-1d-array/
from typing import List
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] = nums[i] + nums[i - 1]
return nu... | webdastur/leetcode | array/easy/leetcode1480_1.py | leetcode1480_1.py | py | 628 | python | en | code | 7 | github-code | 1 |
73002043233 | from __future__ import print_function
import os
import errno
from HTMLParser import HTMLParser
import urllib2
ARTS_LIST = 'arts-select.list'
NUMBER_TO_DOWNLOAD = 100 # set to -1 to download all
# The URL for the artifact from Bigquery is a webpage, which contains a link
# to download the original image. This cla... | IBM/tensorflow-kubernetes-art-classification | download.py | download.py | py | 2,576 | python | en | code | 60 | github-code | 1 |
43758862321 | # -*- coding: utf-8 -*-
# file: __init__.py
# date: 2021-07-20
import os
import _io
import json
import logging
import time
import datetime
import pyspark
import pyspark.sql
from typing import Any, Union, Dict, List, Tuple
from ... import pysparkit
LOGGER: logging.Logger = pysparkit.get_logger(__name__, level=loggi... | innerNULL/pysparkit | pysparkit/io/__init__.py | __init__.py | py | 5,878 | python | en | code | 0 | github-code | 1 |
23051885140 | import tensorflow as tf
import numpy as np
import os
import argparse
import math
from model import GridCell
from custom_ops import block_diagonal
from data_io import Data_Generator
from matplotlib import pyplot as plt
from utils import draw_heatmap_2D, draw_path_to_target, draw_path_to_target_gif
import itertools
cla... | ruiqigao/GridCell | path_planning.py | path_planning.py | py | 16,048 | python | en | code | 18 | github-code | 1 |
36427243193 | """
318. Maximum Product of Word Lengths
Medium
514
47
Favorite
Share
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, re... | fengyang95/OJ | LeetCode/python3/318_MaximumProductOfWordLengths.py | 318_MaximumProductOfWordLengths.py | py | 2,324 | python | en | code | 2 | github-code | 1 |
26524777453 | #Dependencies
from relu import relu
from convolutional_mlp import LeNetConvPoolLayer
from logistic_sgd import LogisticRegression
from mlp import HiddenLayer
from dropout import dropout_neurons_from_layer
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
import theano
class RetinopathyNet(... | rocket-raccoon/DiabeticRetinopathyDetection | retinopathy_net.py | retinopathy_net.py | py | 2,958 | python | en | code | 0 | github-code | 1 |
22173126794 | import song
class Playlist:
""" A playlist of songs."""
def __init__(self, title):
""" (Playlist, str) -> NoneType
A playlist of songs titled title.
>>> playlist = Playlist('Canadian Artists')
>>> playlist.title
'Canadian Artists'
>>> playlist.songs
[]... | jcanning/Class_craftingQualityCode | Class Files/playlist.py | playlist.py | py | 2,566 | python | en | code | 0 | github-code | 1 |
31588107873 | import dataclasses
import json
import logging
import re
import sys
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Set, List, Union
from para_tranz.utils.config import PROJECT_DIRECTORY, ORIGINAL_PATH, TRANSLATION_PATH, PARA_TRANZ_PATH, LOG_LEVEL, \
LOG_DEBUG... | TruthOriginem/Starsector-096-Localization | para_tranz/utils/util.py | util.py | py | 8,353 | python | en | code | 21 | github-code | 1 |
1370447652 | import datetime
from django.core import serializers
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from weather.models import *
# Create your views here.
def weather(request, location):
location = location.split(',')[-1]
index = request.GET.get('index')
... | BruceDGit/HexuWeather | Server/weather_server/weather/views.py | views.py | py | 8,222 | python | en | code | 3 | github-code | 1 |
4038397722 | # TASK - 1
# A To-Do List application is a useful project that helps users manage and organize their tasks efficiently.
# This project aims to create a command-line or GUI-based application using Python, allowing users to create, update,
# and track their to-do lists.
from tkinter import *
import tkinter.messagebox as... | KaustabRoy/CODSOFT | Task1-ToDoListManager/main.py | main.py | py | 17,100 | python | en | code | 0 | github-code | 1 |
8699686219 | # -*- coding:utf-8 -*-
'''
print api example: print('output is: ' + str(output))
'''
import random
# from print_api import print
'''
n: the total number of games to win
n1: the number of games player1 won
n2: the number of games player2 won
'''
def Bookie1(n, n1, n2):
for i in range(2 * n - n1 - n2 - 1): # the... | songkuixi/StatisticsLab | Task2/Bookie.py | Bookie.py | py | 2,320 | python | en | code | 3 | github-code | 1 |
35319530610 | import re
info = "Jose Maria Almeida;00351 962341234;1997-11-19"
namePattern = re.compile(r'[A-Z][a-z]+ ([A-Z][a-z]+)+')
phonePattern = re.compile(r'00351 \d{9}')
datePattern = re.compile(
r'\d+-(((01|03|05|07|08|10|12)-(0[1-9]|1[0-9]|2[0-9]|3[0-1]))|((02)-(0[1-9]|1[0-9]|2[0-9]))|((04|06|09|11)-(0[1-9]|1[0-9]|2[0... | ZePedroFernandes/LEI_ASI | Parte 1/Exame Modelo/TesteModelo1/Ex3.py | Ex3.py | py | 976 | 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.