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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
17363794950 | '''
Задача 5. Кино
Илья зашёл на один любительский киносайт, где пользователи пишут рецензии на фильмы.
Вот, кстати, список этих фильмов: films = ['Крепкий орешек’, 'Назад в будущее’, 'Таксист’, 'Леон’,
'Богемская рапсодия’, 'Город грехов’, 'Мементо’, 'Отступники’, 'Деревня’]
Илья на сайте в первый раз, он хочет зареги... | Pasha-lt/Skillbox-security | Python_basic/lesson_15/hw_15_05.py | hw_15_05.py | py | 2,301 | python | ru | code | 0 | github-code | 36 |
23882256658 | #!/usr/bin/env python3
"""
Autonomy node for the TurtleBot3.
This script relies on a YAML file of potential navigation locations,
which is listed as a `location_file` ROS parameter.
Example usage:
ros2 run tb3_autonomy autonomy_node.py
ros2 run tb3_autonomy autonomy_node.py --ros-args -p location_file:=/path/to... | sea-bass/turtlebot3_behavior_demos | tb3_autonomy/scripts/autonomy_node.py | autonomy_node.py | py | 5,578 | python | en | code | 207 | github-code | 36 |
28986009891 | EXPECTED_TEST_ANSWER_PART1 = [24000]
EXPECTED_TEST_ANSWER_PART2 = [45000]
def set_max(calories, max_calories):
"""
Returns the larger value
"""
return calories if calories > max_calories else max_calories
def run(data):
"""
Takes a list of values in "data" and returns sum of the largest
... | SocialFinanceDigitalLabs/AdventOfCode | solutions/2022/pughmds/day01/__main__.py | __main__.py | py | 1,188 | python | en | code | 2 | github-code | 36 |
41341957139 | import numpy as np
from scipy import signal
from scipy.signal import iirfilter
from scipy.signal import lfilter
def Implement_Notch_Filter(fs: float, band: list, freq: float, ripple: float, order: int, filter_type: str, data: np.array):
r"""
Args:
fs: frequency sampling
band: the bandwidth aro... | Mariellapanag/pyiEEGfeatures | src/pyiEEGfeatures/IIR_notch_filter.py | IIR_notch_filter.py | py | 2,731 | python | en | code | 1 | github-code | 36 |
17385320330 | """SQLAlchemy models for Carbon Print Calculator."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
"""User in the system."""
__tablename__ = 'users'
id = db.Column(
db.Integer,
primary_key=True,
)
username = db.Column(
db.String(70),
... | pasha-log/capstone-copy | models.py | models.py | py | 770 | python | en | code | 0 | github-code | 36 |
27052908549 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
vals = []
current_vals = []
... | ikedaosushi/leetcode | problems/python/levelOrder.py | levelOrder.py | py | 1,094 | python | en | code | 1 | github-code | 36 |
41284568843 | # 그룹 단어 체커
# 문제
# 그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다. 예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때문에 그룹 단어이지만, aabbbccb는 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다.
# 단어 N개를 입력으로 받아 그룹 단어의 개수를 출력하는 프로그램을 작성하시오.
# 입력
# 첫째 줄에 단어의 개수 N이 들어온다. N은 100보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 단어가 들어온다. 단어는... | dlghgus5656/Algorithm-study | python/문자열_1316번.py | 문자열_1316번.py | py | 1,631 | python | ko | code | 1 | github-code | 36 |
1021810825 | import os
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
model_type = "DPT_Large"
midas = torch.hub.load("intel-isl/MiDaS", model_type)
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
midas.to(device)
midas.eval()
midas_transforms = torch.hub.load("int... | Roman212Koval/Dual-channel_CNN | monocular.py | monocular.py | py | 1,994 | python | en | code | 1 | github-code | 36 |
13050899024 | from sqlalchemy import (
testing, null, exists, text, union, literal, literal_column, func, between,
Unicode, desc, and_, bindparam, select, distinct, or_, collate, insert,
Integer, String, Boolean, exc as sa_exc, util, cast)
from sqlalchemy.sql import operators, expression
from sqlalchemy import column, ta... | lameiro/cx_oracle_on_ctypes | test/integration/3rdparty/SQLAlchemy-1.0.8/test/orm/test_query.py | test_query.py | py | 132,871 | python | en | code | 20 | github-code | 36 |
2655039038 | import torch
import numpy as np
import torch.utils.data
import matplotlib.pyplot as plt
n_train = 1000
class DS(torch.utils.data.Dataset):
def __init__(self, n):
self.n = n
self.y = torch.rand(n)*21-10.5
self.x = torch.sin(0.75*self.y)*7.0+self.y*0.5+torch.randn(n)
def __len__(self):
... | nguyenvantui/deepwriting-master-1 | github_syn/my_mdn2.py | my_mdn2.py | py | 2,177 | python | en | code | 1 | github-code | 36 |
21327628308 | #!/usr/bin/env/ python
# -*- coding:utf-8 -*-
# Created by: Vanish
# Created on: 2019/4/20
# ①自顶向下的备忘录法 还是用了递归
# class Solution:
# def __init__(self):
# self.l = [0,1]+[-1]*38
# def Fibonacci(self, n):
# # write code here
# if n<=1: return n
# if self.l[n-1]==-1:
# ... | wcb2213/Learning_notes | algorithm/dynamic programming/dp总结_1_斐波那契数列_AA.py | dp总结_1_斐波那契数列_AA.py | py | 802 | python | en | code | 0 | github-code | 36 |
11352981784 | from stairs import concatenate
from core.app_config import app
from core.data_utils import (apply_normalization,
apply_reshape,
apply_augmentation,
encode_image,
encode_labels)
from core.consumers impor... | electronick1/stairs_examples | digit_recognizer/core/pipelines.py | pipelines.py | py | 1,086 | python | en | code | 5 | github-code | 36 |
19793717676 | """
Methods to call service methods, also known as unified messages
Example code:
.. code:: python
# the easy way
response = client.send_um_and_wait('Player.GetGameBadgeLevels#1', {
'property': 1,
'something': 'value',
})
print(response.body)
# the other way
jobid = clie... | ValvePython/steam | steam/client/builtins/unified_messages.py | unified_messages.py | py | 2,557 | python | en | code | 934 | github-code | 36 |
24402887263 | import argparse, libmarusoftware, libtools, os
__version__="Marueditor b1.0.0"
__revision__="4"
__author__="Marusoftware"
__license__="MIT"
class DefaultArgv:
log_level=20
filepath=None
class Editor():
def __init__(self, argv=DefaultArgv):
self.argv=argv
self.opening={}
def Setup(self... | Marusoftware/Marutools | marueditor.py | marueditor.py | py | 17,550 | python | en | code | 0 | github-code | 36 |
71513930025 | MIN_NUM = float('-inf')
MAX_NUM = float('inf')
# import rospy
class PID(object):
def __init__(self, kp, ki, kd, mn=MIN_NUM, mx=MAX_NUM):
self.kp = kp
self.ki = ki
self.kd = kd
self.min = mn
self.max = mx
self.reset()
self.last_error = 0.0
def rese... | ColinShaw/self-driving-car-capstone | ros/src/twist_controller/pid.py | pid.py | py | 1,239 | python | en | code | 4 | github-code | 36 |
5744062882 | import argparse
import GitPyService as gps
parser = argparse.ArgumentParser(description="Arguments Description")
parser.add_argument('--repo', nargs='?', default='https://github.com/takenet/lime-csharp', help='Repo to use')
parser.add_argument('--folder', nargs='?', default='', help='Folder to use')
parser.add_argumen... | rafaatsouza/ufmg-practical-assignments | software-repositories-mining/exercices/exercise-2.py | exercise-2.py | py | 2,147 | python | pt | code | 1 | github-code | 36 |
38062258097 | import mysql.connector
from database.database_setup.gcp_sql_config import config
def createReport(user_email, post_url, create_date, rep_description):
cnxn = mysql.connector.connect(**config)
cursor = cnxn.cursor()
insert_stmt = "INSERT INTO Report VALUES (%s, %s, %s, %s)"
data = (user_email, post_ur... | joycedaiyt/Me-In-Loo | endpoints/repositories/report_repo.py | report_repo.py | py | 717 | python | en | code | 1 | github-code | 36 |
13076195782 | import serial
import serial.tools.list_ports
import re
import sys
import pymysql
from time import sleep
db = pymysql.connect(host="twofast-RPi3-0", # your host
user="writer", # username
passwd="heiko", # password
db="NG_twofast_DB") # name of the datab... | kromerh/phd_python | 01_neutron_generator_contol/HBoxDueReadout_V0.py | HBoxDueReadout_V0.py | py | 2,299 | python | en | code | 0 | github-code | 36 |
72791842345 | from collections import deque
"""
Binary Search Tree — ia binary tree with the constraint:
- left subtree < currNode < right subtree
The left and right subtree each must also be a binary search tree.
"""
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.ri... | cs50victor/dsa | dsa/non-linear/implement/Graphs/BinaryTrees/BinarySearchTrees.py | BinarySearchTrees.py | py | 3,330 | python | en | code | 0 | github-code | 36 |
34766714821 | import os
import gc
import time
import random
import warnings
import cv2
import hydra
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as torch_optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from losses import DBLoss
from lr_schedulers import Wa... | huyhoang17/DB_text_minimal | src/train.py | train.py | py | 12,725 | python | en | code | 34 | github-code | 36 |
24140152426 | from django.test import TestCase
import graphene
from api.query.story import Query
from api.tests.util import request_with_loaders
from story.factories import StoryFactory
class TestStoriesQuery(TestCase):
def setUp(self):
self.schema = graphene.Schema(query=Query)
self.request = request_with_lo... | dvndrsn/graphql-python-tutorial | api/tests/query/test_story.py | test_story.py | py | 1,833 | python | en | code | 16 | github-code | 36 |
555988903 | import requests
import time
import numpy as np
from bs4 import BeautifulSoup as bs
def dict_vacancy():
return {'Вакансия': None,
'Зарплата мин': None,
'Зарплата мкс': None,
'Валюта': None,
'Ссылка': None,
'Сайт': None}
def salary_tpl(salary_str, dlm='—... | GruXsqK/Methods_scraping | Lesson_3/Scraper.py | Scraper.py | py | 4,763 | python | en | code | 0 | github-code | 36 |
24614942714 | from typing import Union
import numpy as np
from src.det import det, build_cofactor_matrix
# with extra space
# def transpose(matrix, size):
# transpose_matrix = matrix.copy()
#
# for i in range(size):
# for j in range(size):
# transpose_matrix[i][j] = matrix[j][i]
#
# return transpose... | Lakshmikanth2001/LinearAlgebra | src/inverse.py | inverse.py | py | 1,128 | python | en | code | 1 | github-code | 36 |
5011444074 | def calc_fact(no):
fact = 1
while no > 1:
fact *= no
no -= 1
return fact
no = 0
try:
no = int(input('Enter a number: '))
except Exception as e:
print(e)
print('Please enter valid integer number!')
else:
print('execute this if no any exception occured')
print('Factorial:'... | CodeKul/Python-Nov-2019-Weekday-10am | ExceptionHandling.py | ExceptionHandling.py | py | 391 | python | en | code | 0 | github-code | 36 |
74470691304 | import os
import logging
import numpy
import random
from gensim.models import ldaseqmodel
analyze_topics_static = __import__('4a_analyze_topics_static')
config = __import__('0_config')
try:
import pyLDAvis
CAN_VISUALIZE = True
except ImportError:
CAN_VISUALIZE = False
if __name__ == "__main__":
logg... | Diego999/Risk-Analysis-using-Topic-Models-on-Annual-Reports | 4c_analyze_topics_through_time.py | 4c_analyze_topics_through_time.py | py | 2,519 | python | en | code | 6 | github-code | 36 |
24390865714 | import os.path
import shutil
from . import *
class TestDepfile(IntegrationTest):
def __init__(self, *args, **kwargs):
super().__init__('depfile', stage_src=True, *args, **kwargs)
@skip_pred(lambda x: x.backend == 'make' and
env.host_platform.family == 'windows',
'xfail ... | jimporter/bfg9000 | test/integration/test_depfile.py | test_depfile.py | py | 729 | python | en | code | 73 | github-code | 36 |
29981226502 | from __future__ import absolute_import, print_function
import os.path
import collections
from . import hub, protocols, error, reader, http_ffi, logging, compat
from .hub import switchpoint
from .util import objref, docfrom
from ._version import __version__
try:
from urllib.parse import urlsplit
except ImportErro... | cocagne/gruvi | gruvi/http.py | http.py | py | 24,754 | python | en | code | null | github-code | 36 |
25209669435 | from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.db.models import Q
from django.db.models import Count,Sum,Avg,Min,Max
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from dj... | yamachanyama/Django_app | hello3/views.py | views.py | py | 3,978 | python | ja | code | 0 | github-code | 36 |
37347611174 | '''
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operat... | luoy2/leetcode-python | 238. Product of Array Except Self.py | 238. Product of Array Except Self.py | py | 2,100 | python | en | code | 0 | github-code | 36 |
7318498267 | import shutil
import os
train_path = "./training_id.txt"
source_img_dir = "./coco/images"
source_label_dir = "./coco/labels"
target_dir = "/ssddata/metahand/coco2014_training"
img_list = []
label_list = []
with open(train_path, "r") as file:
content = file.read().split("\n")[:-1]
for img_path in content:
rel_im... | maybeLee/MetaHand | data_coco/copy_train_data.py | copy_train_data.py | py | 800 | python | en | code | 0 | github-code | 36 |
18424838554 |
import sys
from datetime import datetime, timedelta
from hashlib import sha1
from hmac import new as hmac
from os.path import dirname, join as join_path
from random import getrandbits
from time import time
from urllib import urlencode, quote as urlquote
from uuid import uuid4
from wsgiref.handlers import CGIHandler
... | jaredwy/taskoverflow | to-site/taskoverflow/twitteroauth.py | twitteroauth.py | py | 11,846 | python | en | code | 4 | github-code | 36 |
25077224694 | from collections import OrderedDict
import ctypes
import os
import random
import re
import sys
import pandas as pd
from psychopy import core, event, visual
import experiment as ex
from settings import get_settings
settings = get_settings(env="production", test=False)
par = None
experiment_timer = None
class Paradi... | julianstephens/FH-WordOA-PostTest | stimulus.py | stimulus.py | py | 14,113 | python | en | code | 0 | github-code | 36 |
9502049271 | from django.db import models
from django.contrib.auth.models import AbstractUser
from voomsdb.utils.models import PersonalModel, NameTimeBasedModel
from voomsdb.utils.choices import AdmissionTypeChoice
from voomsdb.utils.media import MediaHelper
from voomsdb.utils.strings import generate_ref_no
from django.conf import ... | dauntless001/vooms | home/models.py | models.py | py | 1,596 | python | en | code | 0 | github-code | 36 |
41702890581 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... | yogika/rock-paper-scissors | main.py | main.py | py | 1,010 | python | en | code | 0 | github-code | 36 |
12038245832 | # SSCR Server - Simple Socket Chat Room Server
# Version: Alpha 0.9
# This is the server app of the Simple Socket Chat Room which handles all client connections
# todo: 1. [DONE] Clean up server side prints to only whats relevant to the eye in realtime and implement a log for later debugging/analysing
# 2. [D... | Argentix03/Simple-Socket-Chat-Room | sscr-server.py | sscr-server.py | py | 6,620 | python | en | code | 1 | github-code | 36 |
37290284583 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from .models import Image, Comment, Like
from .forms import userRegForm, log... | RAHUL-ALAM/Cookpad-Assignment | image/views.py | views.py | py | 4,575 | python | en | code | 0 | github-code | 36 |
3599441390 | from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(766, 569)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(30, 20, 61, 21))
self.label.setObjectName("label")
... | richespo/Image-Video-Frame | ImageViewerExample.py | ImageViewerExample.py | py | 2,364 | python | en | code | 0 | github-code | 36 |
75174330665 | from math import hypot, pi, cos, sin
from PIL import Image
import numpy as np
import cv2
def hough(image, theta_x=600, rho_y=600):
"Calculate Hough transform."
print(image.shape)
height, width = image.shape
rho_y = int(rho_y/2)*2 #Make sure that this is even
him = np.zeros((theta_x, rho_y... | squeakus/bitsandbytes | opencv/hough_transform.py | hough_transform.py | py | 3,381 | python | en | code | 2 | github-code | 36 |
73508165543 | import pygame
from typing import Literal
# Init
pygame.init()
pygame.font.init()
# Janela
display = pygame.display.set_mode((1280, 720))
#3 Parte - formas - player
#pos e forma em retangulo
# 0,0 pos esquerda superior
#player1 = pygame.Rect(0, 0, 30, 150)
player1_img = pygame.image.load("assets/player1.png")
playe... | Gwynbleidd203/gameli_2 | main.py | main.py | py | 5,398 | python | en | code | 0 | github-code | 36 |
36709812106 | from Genetic.selection import tournamentSelect,getRouletteWheel,rouletteWheelSelect,Individual
from django.shortcuts import render,get_object_or_404,redirect
from django.views.generic import TemplateView,DetailView,ListView
from .forms import FormularzPoczatkowy
from .models import Epoka,PojedynczaWartoscWyniku,Ustawi... | SJaskowski/OE_2 | Main/views.py | views.py | py | 21,028 | python | pl | code | 0 | github-code | 36 |
24184066518 | '''
Created on May 31, 2011
@author: Giulio
'''
from sysThread import Thread
from threading import Lock
from system.Builder import Builder
class PowerMonitor(Thread):
def __init__(self):
'''
Constructor
'''
Thread.__init__(self)
self._proxy = None
self._power... | gbottari/ESSenCe | src/system/powerMonitor.py | powerMonitor.py | py | 1,003 | python | en | code | 0 | github-code | 36 |
14509567601 | # Import necessary libraries
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import datetime
from bcb import sgs
from bcb import currency
from... | tharikf/WebApp_Cenario_Macroeconomico_Brasileiro | pages/page4.py | page4.py | py | 10,262 | python | pt | code | 1 | github-code | 36 |
21543823611 | import re
import math
myfile = open("orig-xmastree.brd", "r")
myline = myfile.readline()
f = 1.2
l = 0
while myline:
if l < 110 and myline.startswith("<wire "):
x = re.findall('<wire x1="(.*)" y1="(.*)" x2="(.*)" y2="(.*)" width="0.1524" layer="20"/>', myline)
x1 = round(float(x[0][0]) * f, 2);
... | charlierobson/tree | scale.py | scale.py | py | 657 | python | en | code | 0 | github-code | 36 |
39458596841 | from django.urls.resolvers import URLPattern
from django.urls import path
from . import views
urlpatterns = [
path('customer/', views.CustomerList.as_view()),
path('customer/<int:pk>', views.CustomerDetail.as_view()),
path('product/', views.ProductList.as_view()),
path('product/<int:pk>', views.Product... | ankitaggarwal1986/DjangoWorkforce | emart/products/urls.py | urls.py | py | 469 | python | en | code | 0 | github-code | 36 |
9815980344 | import sys
import requests
import random
token = sys.argv[1]
link = sys.argv[2]
useproxies = sys.argv[3]
if useproxies == 'True':
proxy_list = open("proxies.txt").read().splitlines()
def proxyjoin():
try:
proxy = random.choice(proxy_list)
requests.post(apilink, headers=heade... | X-Nozi/NoziandNiggarr24Toolbox | spammer/joiner.py | joiner.py | py | 612 | python | en | code | 0 | github-code | 36 |
4617197672 | '''
File: MagicSquare.py
Description: Creates a magic square and checks to see if it is a magic_square
Student's Name: Jerry Che
Student's UT EID: jc78222
Partner's Name: Terry Woodward Jr
Partner's UT EID: tgw466
Course Name: CS 313E
Unique Number: 86325
Date Created: 06/15/... | jerry-che/Data_Structures_with_Python | MagicSquare.py | MagicSquare.py | py | 3,747 | python | en | code | 0 | github-code | 36 |
18875650180 | from __future__ import print_function
from stone import lexer, mytoken
import tempfile
f = tempfile.TemporaryFile()
f.write("""if (i==1) {
a=1
}
while i < 10 {
sum = sum + i
i = i + 1
}
sum
""")
f.seek(0)
l = lexer.Lexer(f)
while True:
t = l.read()
if t is mytoken.Token.EOF:
print('break')
... | planset/stone-py | chap3_lexer_runner.py | chap3_lexer_runner.py | py | 367 | python | en | code | 3 | github-code | 36 |
17128917439 | class Quad_Encoder:
"""Class of functions for a DC motor Quadratic encoder
This class has two functions
1: .read() returns the current position
2: .zero() sets the postion to zero
"""
def __init__(self,pin1,pin2,timer):
"""Initilizes the Encoder class by taking inputs and cr... | rtam2166/XBAS | encoder.py | encoder.py | py | 1,946 | python | en | code | 0 | github-code | 36 |
36708187417 | """
Animate the prediction changes in a scene over training time by reading the predictions at different time steps during
the training process
Input:
- Path to a pickle file containing the points of a scene
- List of paths to pickle files containing the labels at different time steps of the training process
"""
imp... | tpfeifle/pointcloud-segmentation-attention | attention_points/visualization/labels_during_training.py | labels_during_training.py | py | 2,740 | python | en | code | 8 | github-code | 36 |
18729010139 | import spex_common.modules.omeroweb as omeroweb
from flask_restx import Namespace, Resource
from flask import request, abort, Response
from .models import responses, omero
from flask_jwt_extended import jwt_required, get_jwt_identity
from os import getenv
from urllib.parse import unquote
from spex_common.services.Utils... | Genentech/spex_backend | routes/api/v1/omero.py | omero.py | py | 2,937 | python | en | code | 0 | github-code | 36 |
16743362426 | from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
def settings():
markup = InlineKeyboardMarkup()
shutdown = InlineKeyboardButton(text='🔽 Shutdown', callback_data='shutdown')
restart = InlineKeyboardButton(text='🔄 Restart', callback_data='restart')
lock = InlineKeyboardButton... | ToXic2290/pc-controller-bot | markup.py | markup.py | py | 2,456 | python | en | code | null | github-code | 36 |
4108483697 | from sys import stdin
input = stdin.readline
num, q = [int(x) for x in input().split()]
numbers = [int(x) for x in input().split()]
psa = [0]
for number in numbers:
psa.append(psa[-1] + number)
# print(psa)
for _ in range(q):
start, end = [int(x) for x in input().split()]
print(psa[-1] - (psa[end] - psa[s... | AAZZAZRON/DMOJ-Solutions | gfssoc2j4.py | gfssoc2j4.py | py | 332 | python | en | code | 1 | github-code | 36 |
21192643950 | import turtle
def tree(t,galho):
if galho > 5:
t.fd(galho)
t.rt(20)
tree(t,galho-10)
t.lt(40)
tree(t,galho-10)
t.rt(20)
t.bk(galho)
t.color('brown')
else:
t.color('green')
if __name__ == "__main__":
screen = turtle.Screen()
t = tur... | mathewsmonoo/College_Studies_Python | Estudo_Turtle/turtle_recursive_tree.py | turtle_recursive_tree.py | py | 552 | python | en | code | 0 | github-code | 36 |
73603651945 | from django.contrib import admin
from django.urls import path, include
from . import views
from gcsemaths.exam_questions import exam_non_calc_views
from gcsemaths.a_number import aa_ordering_and_comparative_views, ab_ops_with_int_frac_dec_views
from gcsemaths.b_algebra import algebra_views
from gcsemaths.e_geometry_a... | devjolt/eqg | gcsemaths/urls.py | urls.py | py | 2,107 | python | en | code | 0 | github-code | 36 |
44393189173 | import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
class CenterForm(QMainWindow):
def __init__(self):
super(CenterForm, self).__init__()
# 设置主窗口标题
self.setWindowTitle('深度废物')
# 设置窗口尺寸
self.resize(400,300)
def center(self):
# 获取屏幕坐标
screen... | Jrisking/pyqt6 | CenterForm.py | CenterForm.py | py | 828 | python | en | code | 0 | github-code | 36 |
12433436430 | from datetime import datetime
"""GPS class. Responsible for retrieving GPS data given connection and returning GPS data including lat, long, and time
Attributes: mav_connection:MAVLinkConnection
"""
class GPS:
def __init__(self, mavlink):
""" Initialize GPS class
Args:
mavlink:MAVLinkC... | shamuproject/mavimage | mavimage/gps.py | gps.py | py | 2,385 | python | en | code | 1 | github-code | 36 |
7804091778 | from scrapy import signals
from .logger import logger as lg
from time import sleep
from datetime import datetime as dt
from scrapy.http import HtmlResponse
from scrapy.utils.python import to_bytes
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common... | uniqon-truepoint/afreecatvCrawler | afreecatv/crawler/crawler/middlewares.py | middlewares.py | py | 9,541 | python | en | code | 3 | github-code | 36 |
11357570925 | import json
import asyncio
import time
from nats.aio.client import Client as NATS
async def sleep():
await asyncio.sleep(0.01)
async def pub_random(loop):
nc = NATS()
await nc.connect("localhost:4222", loop=loop)
if nc.last_error:
print("ERROR received from NATS: ", nc.last_error)
else:
... | saboyle/qt-python-nats-wiretap | Version 1 - Qt and Asyncio shared event loop (minimal)/nats_test_publisher.py | nats_test_publisher.py | py | 669 | python | en | code | 1 | github-code | 36 |
40995170472 | import os
import msvcrt
class atm:
account_no=0
name = ''
pin=0
balance=0.0
mobile=''
def __init__(self,a,n,p,b,m):
self.account_no=a
self.name=n
self.pin=p
self.balance=b
self.mobile=m
def getaccount(self):
return self.account_no
def ... | abdul-rehman18/oop-python | bms.py | bms.py | py | 2,382 | python | en | code | 2 | github-code | 36 |
34623870443 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from minisom import MiniSom
from matplotlib.gridspec import GridSpec
import time
from pylab import plot, axis, show, pcolor, colorbar, bone
def load_data():
data = np.load('feature_vector.npy')
df = pd.read_csv('bbc-text.csv')... | elahesalari/Self-Organizing-Map-SOM | SOM-on-center library.py | SOM-on-center library.py | py | 3,545 | python | en | code | 1 | github-code | 36 |
42443818863 | from datetime import date
maior = 0
menor = 0
for cont in range(1,8):
ano = int(input(f'Em que ano a {cont}° pessoa nasceu? '))
if (date.today().year - ano) >= 18:
maior += 1
else:
menor += 1
print(f'Ao todo tivemos {maior} pessoas maiores de idade')
print(f'E também tivemos {menor} pessoas ... | JosueFS/Python | Exercicios/Ex054.py | Ex054.py | py | 341 | python | pt | code | 0 | github-code | 36 |
31309873828 | import sys
from ply import lex
from ply.lex import TOKEN
class Lexer:
def __init__(self, error_func):
self.error_func = error_func
def run(self):
self.lexer = lex.lex(object=self)
def reset_lineno(self):
self.lexer.lineno = 1
def input(self, text):
self.lexer.inpu... | EmilGrigoryan/Interpreter | lexer.py | lexer.py | py | 2,505 | python | en | code | 0 | github-code | 36 |
11268244192 | from random import randint
import math
def main():
task1();
task4();
task5();
def task1():
print("Задание 1")
print("Количество элементов в массиве: ")
length = int(input())
array1 = [randint(0, 10) for _ in range(length)]
print("Массив #1",array1)
array2 = [randint(0, 10) for _ in... | Shortin/Python | G_Pract_1/pract1.py | pract1.py | py | 2,074 | python | ru | code | 0 | github-code | 36 |
20860418193 | # Databricks notebook source
# MAGIC %md
# MAGIC ### Ingest qualifying folder
# COMMAND ----------
# MAGIC %run "../includes/configuration"
# COMMAND ----------
# MAGIC %run "../includes/common_funcs"
# COMMAND ----------
dbutils.widgets.text("p_data_source","")
v_data_source = dbutils.widgets.get("p_data_source"... | hdh997/f1-project | ingestion/8.ingest_qualifying_file.py | 8.ingest_qualifying_file.py | py | 3,035 | python | en | code | 0 | github-code | 36 |
69980575463 | import re
from bs4 import BeautifulSoup
def parse(html):
soup = BeautifulSoup(html, "html5lib")
# Get ingredients
title = soup.find(attrs={'data-testid': "ContentHeaderHed"}).get_text()
# We can't drill down to the list immediately because the yield is
# a sibling
ingredientList = s... | GarrettGeorge/Destijl | parsers/epicurious.py | epicurious.py | py | 1,080 | python | en | code | 0 | github-code | 36 |
31964896901 | import cv2
import time
import sys
from PIL import Image
from multiprocessing import Process
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
import fpstimer
import moviepy.editor as mp
savefile = open('data.txt', 'a', encoding='utf-8')
emojies = {
"🤍": [255, 255, 255],
"🐚": [220, 220... | lolLucoa/scripts | frame generator.py | frame generator.py | py | 6,637 | python | en | code | 0 | github-code | 36 |
31524108278 | """
Test read submittal chain
NOTE: this just makes sure the chain executes properly but DOES NOT assess the quality of the agent's analysis. That is done in the ipython notebooks in the evals/ folder
"""
import pytest
from meche_copilot.schemas import Session
from meche_copilot.chains.read_submittal_chain import Read... | fuzzy-tribble/meche-copilot | tests/unit_tests/chains/read_submittal_chain_test.py | read_submittal_chain_test.py | py | 1,324 | python | en | code | 1 | github-code | 36 |
6789009521 | from rest_framework import serializers
from django.conf import settings
from django.contrib.auth import get_user_model
from actstream import action
from utils.mail import handlers
from custom_auth.helpers import UserProfileWrapper
class RequestContactSerializer(serializers.Serializer):
comment = serializers.C... | tomasgarzon/exo-services | service-exo-core/custom_auth/api/serializers/request_contact.py | request_contact.py | py | 1,545 | python | en | code | 0 | github-code | 36 |
7237082725 | #!/usr/bin/python3
# This Red Panda Lineage dataset management tool is useful for doing sweeping dataset
# revisions, such as ensuring that a field exists in each panda or zoo file, or removing
# photos taken by a specific credited author.
import git
import json
import os
import re
import sys
from shared import MEDI... | wwoast/redpanda-lineage | manage.py | manage.py | py | 30,773 | python | en | code | 22 | github-code | 36 |
16692115241 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 17:00:51 2020
@author: jesus
"""
import socket
sct = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sct.connect(('data.pr4e.org',80))
sct.send('GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode())
while True:
data = sct.recv(512)
if(len(data)<1)... | JA-Developer/Curso-Python-For-Everyone | Sockets.py | Sockets.py | py | 373 | python | en | code | 0 | github-code | 36 |
8649364941 | """
============================
Author:柠檬班-木森
Time:2020/4/21 20:03
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
深浅复制:在列表中有嵌套列表的情况下才会去讨论深浅复制
"""
# li = [1, 2, 3]
#
# li_cp = li.copy()
# print(li, id(li))
# print(li_cp, id(li_cp))
#
# # 修改li
# li.append(999)
# print(li, id(li)... | huchaoyang1991/py27_web | web_01day(前端页面基础)/01扩展内容补充:深浅复制.py | 01扩展内容补充:深浅复制.py | py | 1,043 | python | en | code | 0 | github-code | 36 |
2600967353 | import numpy as np
# T ( z) = T0 + (Tw - T0 ) z^m
def find_dx(x1, x2):
return x1 - x2
def find_t0_m(i, i_arr, to_arr, m_arr):
n = len(i_arr)
j = 0
if i < i_arr[0]:
m = m_arr[0]
to = to_arr[0]
return to, m
#elif i > i_arr[n - 1]:
# m = m_arr[n - 1]
# to = to_a... | xanderkov/ics7-modelling | lab-02/src/methods.py | methods.py | py | 2,401 | python | en | code | 3 | github-code | 36 |
40319289149 | import numpy as np
from scipy import ndimage
from progress.bar import Bar
import argparse
import cv2
import os
import shutil
ImgFolderPathDict = {
"estimate": "estimate/",
"gt_flow": "gt_flow/",
"gt_traj": "gt_trajectories/",
"images": "images/",
"masks": "masks/"
}
SceneFolderName... | hanebarla/CrowdCounting_with_Flow | src/utils/make_human_gaussian.py | make_human_gaussian.py | py | 3,717 | python | en | code | 0 | github-code | 36 |
28238886441 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from lingvo import compat as tf
from lingvo.core import base_input_generator
from lingvo.core import base_layer
from lingvo.core import generic_input
from lingvo.core import py_utils
# Items exceeding this val... | snsun/lingvo | lingvo/tasks/car/base_extractor.py | base_extractor.py | py | 7,549 | python | en | code | null | github-code | 36 |
20456729952 | #!/usr/bin/env python
"""
Entry point for the ledfx controller. To run this script for development
purposes use:
[console_scripts]
python setup.py develop
ledfx
For non-development purposes run:
[console_scripts]
python setup.py install
ledfx
"""
import argparse
import importlib
import logg... | apophisnow/sub-backend | __main__.py | __main__.py | py | 12,252 | python | en | code | 0 | github-code | 36 |
71491780585 | # -*- coding: utf-8 -*-
# HelenのデータセットからXMLファイルを構築してDlibに読み込ませられるXMLファイルを作成する
# 前準備
# 一つのディレクトリ下に以下のファイルを用意する
# 1. facebox のデータが入ったxmlファイル
# 2. annotationの点が入ったファイル(annotation ディレクトリ下に配置する)
#
# Helen_Dataset
# │─ helen_facebox.xml
# └─ annotation
# └─ annotation_data1.txt
# └─ annotation_data2.txt
# ... | chicn/render-dots | create_xml/helen_create_xml.py | helen_create_xml.py | py | 3,149 | python | ja | code | 0 | github-code | 36 |
73743139305 | import random
import time
# -------------------------------
# |(0,0)|(0,1)|(0,2)|(0,3)|(0,4)|
# |(1,0)|(1,1)|(1,2)|(1,3)|(1,4)|
# |(2,0)|(2,1)|(2,2)|(2,3)|(2,4)|
# |(3,0)|(3,1)|(3,2)|(3,3)|(3,4)|
# |(4,0)|(4,1)|(4,2)|(4,3)|(4,4)|
# -------------------------------
class GridWorld():
def __init__(
self... | linklab/e_learning_rl | basic/practice_1/gridworld.py | gridworld.py | py | 10,227 | python | ko | code | 1 | github-code | 36 |
41921068479 | from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from time import sleep
from selenium.webdriver.common.keys import Keys
def getNews():
print('getting news')
text_box = browser.find_element_by_class_name("_2wP_Y")
response = "Let me fetch and send top 5 latest news:\n"
text_box... | Nijaoui-Wassim/Whatsapp-Bot | main.py | main.py | py | 4,682 | python | en | code | 0 | github-code | 36 |
42037384077 | #! /usr/bin/env python
import numpy as np
import time
import Tracking
class Rover:
__arm = None
__tracks = None
__bluerange = (np.array([110, 50, 100]),np.array([130, 255, 255])) #lower, upper color boundaries, in RGB
__greenrange = (np.array([24,166,173]),np.array([125,231,236])) #dark green to light ... | CJoseFlores/HKNOpenCVDemo | arms_module.py | arms_module.py | py | 3,597 | python | en | code | 0 | github-code | 36 |
34788460936 | from aiogram import Router
from aiogram.types import CallbackQuery
from bot.keyboards.inline.raffle import back_to_raffle_menu
crypto_payment = Router()
@crypto_payment.callback_query(lambda call: call.data.split(":")[0] == "Crypto")
async def send_payment_methods(call: CallbackQuery) -> None:
await call.messa... | lowfie/LotteryBot | bot/routers/raffle/crypto_payment.py | crypto_payment.py | py | 445 | python | en | code | 0 | github-code | 36 |
11927767628 | # Converts a base 10 number to binary
# Currently only works bases <= 10
def decimal(num, base):
if base == 10:
return num
total = 0
digits = list(str(num))[::-1]
for i in range(0,len(digits)):
total += int(digits[i]) * base**(i)
return total
| aniruddhamurali/python-algorithms | src/math/number-theory/base_conversion/to_decimal.py | to_decimal.py | py | 280 | python | en | code | 1 | github-code | 36 |
11583789260 | def reverse_list(arr):
left = 0
right = len(arr)-1
while (left < right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left += 1
right -= 1
return arr
arr = [1, 2, 3, 4, 5, 6, 7]
print(reverse_list(arr))
# another and short approach
print(... | karanop001018/Python-Work | reverse a list.py | reverse a list.py | py | 330 | python | en | code | 2 | github-code | 36 |
43296898564 | from __future__ import with_statement
"""
This file is OBSCURE. Really. The purpose is to avoid copying and changing
'test_c.py' from cffi/c/ in the original CFFI repository:
https://foss.heptapod.net/pypy/cffi/
Adding a test here involves:
1. add a test to cffi/c/test.py
- if you need a C function to call, a... | mozillazg/pypy | pypy/module/_cffi_backend/test/test_c.py | test_c.py | py | 5,268 | python | en | code | 430 | github-code | 36 |
74249580265 | """"
Controls ECS Services
"""
import boto3
import logging
import os
DBTABLEENV = "ECSDYNTABLE"
DBREGION = "ECSDBREGION"
class ecsController:
def __init__(self, region, searchTag):
self.region = region
self.client = boto3.client('ecs', region_name= region)
self.searchTag = searchTag.lower... | evoraglobal/SleepSaver | ecsController.py | ecsController.py | py | 12,645 | python | en | code | 0 | github-code | 36 |
5222380259 | # -*- coding: utf-8 -*-
"""
@author: 葛怡梦
@Remark: 人脸识别
@inset: 陈佳婧
"""
import os
import numpy as np
import cv2
import face_recognition
from dvadmin.utils.mail import send_email_demo
from django.conf import settings
# Threshold = 0.65 # 人脸置信度阈值
'''
功能:计算两张图片的相似度,范围:[0,1]
输入:
1)人脸A的特征向量
2)人脸B的特征向量
输出:
1)sim:AB的相似度... | Applied-Energetic/Intelligent-classroom-management-system | django-vue-admin-main/backend/dvadmin/utils/face_identification2.py | face_identification2.py | py | 7,218 | python | en | code | 1 | github-code | 36 |
21184237697 | from flask import request
from flask_restplus import Resource
from ..util.dto import TaskDto
from ..service.task_service import save_new_task, get_all_user_tasks, get_a_user_task, update_task, delete_task, get_all_expired_tasks
api = TaskDto.api
_task = TaskDto.task
_task_update = TaskDto.task_update
parser = api.pa... | dvdhinesh/task_management_rest_api | app/main/controller/task_controller.py | task_controller.py | py | 1,959 | python | en | code | 0 | github-code | 36 |
9163276152 | # Python has functions for creating, reading, updating, and deleting files.
# Open file, create file
# if you run this line below, new file will be created
# w flag is to overide / replace and write
myFile = open('myfile.txt', 'w')
# Get info // display file name
print('Name: ', myFile.name)
print('is Closed: ', myFi... | techmynd/python | concepts/files.py | files.py | py | 846 | python | en | code | 0 | github-code | 36 |
25657398507 | from django.urls import path, include
from rest_framework import routers
from src.api.views import UserUpdateView, UserImageView, CaloriesConsumptionListView, CaptureListView
app_name = 'api'
urlpatterns = [
path('capture/', CaptureListView.as_view(), name='capture-list-view'),
path('calories-consumption/', ... | IkramKhan-DevOps/exsapp-healthcare | src/api/urls.py | urls.py | py | 544 | python | en | code | 1 | github-code | 36 |
21008760995 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess as sp
from pwn import *
import re
import sys
import os
import tempfile
import argparse
def to_8bit(d9):
bits = ''
for c in d9:
bits += bin(ord(c))[2:].rjust(8, '0')
log.debug(bits)
d8 = ''
for i in range(0, len(bits), 9):
... | david942j/defcon-2017-tools | pcap/pcap_tool.py | pcap_tool.py | py | 5,202 | python | en | code | 92 | github-code | 36 |
5302940383 | # coding: utf-8
"""Модуль хранения согласия и входящих в него объектов"""
from token_stage.word import TextWord
class Text:
"""
Текст целиком, предложения, слова, токены
и методы их получения и обработки в контексте целого текста
"""
# подтягиваем внешние библиотеки для обработки естественног... | NenausnikovKV/NLP_library | source/text_stage/text.py | text.py | py | 4,955 | python | ru | code | 0 | github-code | 36 |
28764221918 | from tweepy import API, OAuthHandler
from tweepy.models import Status
from typing import Dict
def init_twitter_api(consumer_key : str,
consumer_secret : str,
access_token : str,
access_token_secret : str) -> API:
r"""Initialize cli... | p768lwy3/medium-telegram-tutorial | Ch. 1: Write a telegram bot to get twitter message/src/utils/twitter.py | twitter.py | py | 1,745 | python | en | code | 0 | github-code | 36 |
20976916712 | import datetime
import psycopg2
from psycopg2 import Error
connection = None
cursor = None
def romanToInt(s):
"""
:type s: str
:rtype: int
"""
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90,
'CD': 400, 'CM': 900}
i = 0... | kiranfreelancer87/AWARDL_BACKEND | PostgretoMySql.py | PostgretoMySql.py | py | 1,875 | python | en | code | 0 | github-code | 36 |
12171042996 | n = int(input())
for i in range(n):
cnt = 0
count = 0
ox = input()
for s in ox:
if s == 'O':
cnt += 1
count += cnt
elif s == 'X':
cnt = 0
print(count)
| hi-rev/TIL | Baekjoon/1차원 배열/oxquiz.py | oxquiz.py | py | 225 | python | en | code | 0 | github-code | 36 |
29124638883 | from select import select
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db... | JakubPazderski/6-subject-1-task | 6-subject-1-task.py | 6-subject-1-task.py | py | 3,331 | python | en | code | 0 | github-code | 36 |
18903346352 | from pathlib import Path
from logging import getLogger
from pypairtree.utils import identifier_to_path
from uchicagoldrtoolsuite import log_aware
from uchicagoldrtoolsuite.core.lib.convenience import log_init_attempt, \
log_init_success
from .abc.materialsuiteserializationreader import \
MaterialSuiteSerializ... | uchicago-library/uchicagoldr-toolsuite | uchicagoldrtoolsuite/bit_level/lib/readers/filesystemmaterialsuitereader.py | filesystemmaterialsuitereader.py | py | 2,400 | python | en | code | 0 | github-code | 36 |
1917766531 | import numpy as np
import matplotlib.pyplot as plt
def load_bin_file(samplerate=2e6, type="complex", bfile="../data/file_source_test", plot=False, start_us=0, end_us=0):
if type not in ["complex", "real"]:
print("data type must be complex or real.")
exit()
with open(bfile, "rb") as f:
d... | HelloKevin07/RAScatter | reader/gr-rfid/misc/code/plot_signal.py | plot_signal.py | py | 1,008 | python | en | code | 0 | github-code | 36 |
10798013262 | import socket
import os
obj = socket.socket()
obj.connect(('127.0.0.1',6542))
size = os.stat("paper list.rar").st_size
obj.sendall(bytes(str(size), encoding="utf-8"))
obj.recv(1024)
with open("paper list.rar","rb") as f:
for line in f:
obj.sendall(line)
obj.close() | whoisalan/-updating-algorithm-design-analysis-assignments | simple_c-s-Python/myClient.py | myClient.py | py | 285 | python | en | code | 0 | github-code | 36 |
31050296898 | import unittest
import hypothesis.strategies as st
from django.test import RequestFactory
from hypothesis import assume, example, given
from ...serializers import HeaderSerializer
from ..payload_factories import PayloadRequestFactory
class TestHeaderSerializer(unittest.TestCase):
def setUp(self):
reque... | ryankask/prlint | prlint/github/tests/serializers/test_header_serializer.py | test_header_serializer.py | py | 2,183 | python | en | code | 0 | github-code | 36 |
35631463735 | from django.shortcuts import render
import requests
API_KEY = '09cdaa56db4d4a6cb93bf1bedde04bd7'
def home(request):
url = f'https://newsapi.org/v2/top-headlines?country=gb&apikey={API_KEY}'
response = requests.get(url)
data = response.json()
articles = data['articles']
context = {
... | CassandraTalbot32/News-API | api/newsapp/views.py | views.py | py | 399 | python | en | code | 0 | github-code | 36 |
27036133703 | import json
import threading
import time
import webbrowser
from multiprocessing import Process, Pipe
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import *
from tkinter.ttk import Treeview
from PIL import Image, ImageTk
import course_do
import encrypt
import getCourse
import login
import setting... | ANDYWANGTIANTIAN/SZU_AutoCourseSelecter | gui.py | gui.py | py | 32,494 | python | en | code | 13 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.