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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
31333928448 | #!/usr/bin/env python3
import atexit
import copy
import datetime
import json
import os
import re
import sys
import threading
import botocore
from flask import Flask
from prometheus_client import make_wsgi_app, Gauge
from pyemvue import PyEmVue
from pyemvue.enums import Scale, Unit
from werkzeug.middleware.dispatcher ... | thebaron/vueprom | src/vueprom.py | vueprom.py | py | 5,230 | python | en | code | 2 | github-code | 6 |
74309693947 | from turtle import Screen
from pong_paddle import Paddle
from ball_class import Ball
from scoreboard import Score
import time
screen = Screen()
screen.bgcolor("black")
screen.title("Pong Game")
screen.setup(width=1000, height=800)
screen.tracer(0)
r_paddle = Paddle((450, 0))
l_paddle = Paddle((-450, 0))
ball = Ball()
s... | shuklaritvik06/PythonProjects | Day - 22/main.py | main.py | py | 996 | python | en | code | 0 | github-code | 6 |
42579723690 | import os
import git
import datetime
import argparse
class was_it_rufus:
"""
A class that instantiates all variables and methods about git status.
...
Methods
-------
Prints the git status
"""
def __init__(self, git_directory):
"""
Constructs all the necessary att... | srirammura/was_it_rufus | main.py | main.py | py | 2,076 | python | en | code | 0 | github-code | 6 |
2518936352 | from Getnum import getnum
def maxcha(alist):
n = len(alist)
num_min = min(alist)
num_max = max(alist)
if num_min == num_max :
return 0
d = (num_max-num_min)/(n+1)
tong = []
for i in range(n+1):
tong.insert(i,[])
print(tong)
for j in alist:
if j == num_max:
... | youyuebingchen/Algorithms | qiyue_alg/03_找差值最大值.py | 03_找差值最大值.py | py | 825 | python | en | code | 0 | github-code | 6 |
21529376169 | from .base_view import ClassView
def get_model_value(instance, field):
try:
value = getattr(instance, field)
except Exception:
if field.find('__') > 0:
fields = field.split('__')
elif field.find('.') > 0:
fields = field.split('.')
else:
raise... | sajithak52/store-django-app | myproject/base_class/views/list_view.py | list_view.py | py | 3,646 | python | en | code | 0 | github-code | 6 |
5001531967 | from datetime import datetime
from django import template
from tag.models import Tag
register = template.Library()
@register.inclusion_tag('toptags.html')
def toptags():
tags=Tag.objects.all().order_by('-followers_count')[:5]
args={}
args['tags']=tags
return args
@register.inclusion_tag('trendingtags.... | duonghau/hoidap | tag/templatetags/tag_template.py | tag_template.py | py | 745 | python | en | code | 0 | github-code | 6 |
30984123610 | """ apps/docs/urls.py """
from django.urls import path
from . import views
app_name = 'docs'
urlpatterns = [
path('', views.index, name='index'),
path('overview/', views.overview, name='overview'),
path('what_is_an_ordo/', views.what_is_an_ordo, name='what_is_an_ordo'),
path('create_an_account/', vie... | BrRoman/ordomatic | ordomatic/apps/docs/urls.py | urls.py | py | 709 | python | en | code | 3 | github-code | 6 |
2572453901 | """Домашнее задание.
Написать функцию вычисляющую метрику пользователей лифта.
ОПИСАНИЕ СИТУАЦИИ
Допустим у нас есть 10-ти этажное здание, в котором есть один лифт вместимостью 10 человек.
На каждом этаже есть кнопка вызова лифта. Когда человеку нужно попасть с этажа Х на этаж У, он нажимает кнопку вызова
лифта, ждёт... | LiliaMilutina/OzonMasters | AB-testing/task4.py | task4.py | py | 8,025 | python | ru | code | 1 | github-code | 6 |
75276539706 | import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
def testing(group_test, y_test, model):
rmse = 0
j = 1
result = []
while j <= 100:
x_test = group_test.get_group(j).to_numpy()
data_predict = 0
for t in range(x_test.shape[0]): # iterate t... | jiaxiang-cheng/PyTorch-Transformer-for-RUL-Prediction | testing.py | testing.py | py | 1,420 | python | en | code | 140 | github-code | 6 |
9434937105 | import random
import datetime
import urllib
from optparse import make_option
from django.core.management.base import BaseCommand
from django.core.files.storage import default_storage
from django.core.files.base import File
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except Impor... | fusionbox/django-fusionbox-blog | fusionbox/blog/management/commands/seed_blogs.py | seed_blogs.py | py | 3,513 | python | en | code | 1 | github-code | 6 |
73532195387 | from otree.api import Currency as c, currency_range
from . import views
from ._builtin import Bot
from .models import Constants
class PlayerBot(Bot):
def play_round(self):
yield (views.Demographics, {
'q_country': 'BS',
'q_age': 24,
'q_gender': 'Male'})
yield ... | dimaba/svotree | tests.py | tests.py | py | 619 | python | en | code | 7 | github-code | 6 |
39688498284 | # Time: O(V+E)
# Space: O(V+E)
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
num_graph = collections.defaultdict(list)
for (x,y),val in zip(equations, values):
num_graph[x].append([y, val])
... | cmattey/leetcode_problems | Python/lc_399_evaluate_division.py | lc_399_evaluate_division.py | py | 1,085 | python | en | code | 4 | github-code | 6 |
39225944668 | from ddl.tensorflow.cpp_backend import CPPBackend
class Communicator:
"""
表示一个通信域的类
"""
# 缓存全体进程所在通信域的信息
__world = None
def __init__(self, communicator_id: int):
"""
@param communicator_id: 其实是一个整数, 传入c_api中, C后端将会将其转换成指针再处理
python端将其看作一个整数即可
"""
self.... | LYL232/Experiment-Distributed-Deep-Learning | src/py/ddl/tensorflow/communicator.py | communicator.py | py | 1,892 | python | zh | code | 0 | github-code | 6 |
40106131495 | from .auto import Auto
import gettext
def russian(text):
text = text.replace("usage:",
"использование:")
text = text.replace("show this help message and exit",
"показывает это сообщение и выходит")
text = text.replace("error:",
"ошибк... | Papr1ka/config | practice4/auto/cli.py | cli.py | py | 1,875 | python | ru | code | 0 | github-code | 6 |
5308151620 | # n = int(input())
# s = input()
# ans = 0
# bonus = 0
# for i in range(len(s)):
# if s[i] == 'O':
# bonus += 1
# ans += i + bonus
# elif s[i] == 'X':
# bonus = 0
# print(ans)
n, s = input(), input()
score, bonus = 0, 0
for idx, ox in enumerate(s):
if ox == 'O':
score, bon... | louisuss/Algorithms-Code-Upload | Python/Baekjoon/17389.py | 17389.py | py | 395 | python | en | code | 0 | github-code | 6 |
23932718939 | import os
import numpy as np
import pandas as pd
from variables import csv_path, label_encode, file_name, cutoff
from sklearn.utils import shuffle
def preprocess_data(csv_path):
df = pd.read_csv(csv_path)
df = df.copy()
df.dropna(axis=0, how='any', inplace=False)
df['label'] = df.apply(y2indicator, axi... | 1zuu/Pytroch-Examples | IrishClassifier/util.py | util.py | py | 1,061 | python | en | code | 2 | github-code | 6 |
32055141770 | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
def initiate_db():
cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, year integer, read integer)')
connection.commit()
def add_db(book, author, year):
try:
cursor.execute("... | minnalisa/book_shelf | database2.py | database2.py | py | 1,624 | python | en | code | 0 | github-code | 6 |
15420800470 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib.request
# 132 명의 남자 연예인들
man_list = [
'장근석',
'유아인',
'유동근',
'이서진',
'송일국',
'최재성',
'장혁',
'김민종',
'지창욱',
'주진모',
'안성기',
'이순재',
'신영균',
'이정재',
... | myoons/CycleGAN-Gender-Changer | data_utils/Korean_Crawling/man_crawling.py | man_crawling.py | py | 4,090 | python | en | code | 6 | github-code | 6 |
73907153148 | import tkinter as tk
import os
from style import fnt, ACTIVE_BG, BG, FG, ACCENT
class Option(tk.Checkbutton):
def __init__(self, parent, filename):
# Pull option content from file
with open(filename, 'r') as f:
self.content = f.readlines()
# Grab description of option f... | johnathan-coe/TexInit | widgets.py | widgets.py | py | 1,828 | python | en | code | 0 | github-code | 6 |
72699110267 | import os
import requests
class RegistryHandler(object):
get_repos_url = '/v2/_catalog'
get_tags_url = '/v2/{repo}/tags/list'
get_digests_url = '/v2/{repo}/manifests/{tag}'
delete_digest_url = '/v2/{repo}/manifests/{digest}'
def __init__(self, host):
self.host = host
def get_repos(se... | zzyy8678/stady_python | delete_regestry.py | delete_regestry.py | py | 2,144 | python | en | code | 0 | github-code | 6 |
26038424036 | from __future__ import annotations
from typing import ClassVar
from pants.core.util_rules.environments import EnvironmentField
from pants.engine.target import (
COMMON_TARGET_FIELDS,
BoolField,
Dependencies,
DictStringToStringField,
IntField,
MultipleSourcesField,
SpecialCasedDependencies,... | pantsbuild/pants | src/python/pants/backend/adhoc/target_types.py | target_types.py | py | 12,321 | python | en | code | 2,896 | github-code | 6 |
35282991136 | import subprocess
import argparse
import datetime
import json
import time
def get_options():
parser = argparse.ArgumentParser(
description='Provision a Kubernetes cluster in GKE.')
parser.add_argument(
'-c', '--cluster', type=str, default=None,
help='K8s cluster to configure'
)
... | NVIDIA/nvindex-cloud | provision/gke/finalize.py | finalize.py | py | 2,346 | python | en | code | 10 | github-code | 6 |
3625906365 | from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import DetailView, View, UpdateView, ListView, TemplateView
from django.core.urlresolvers import reverse
from django.urls import reverse_lazy
from django.contrib import messages
from django.http import Http404
from .models impor... | tegarty/E-Commerce_django | orders/views.py | views.py | py | 8,371 | python | en | code | 1 | github-code | 6 |
37176821074 | import os
def clear_screen():
os.system('cls')
def recording_file(data):
with open('School.csv', 'w', encoding='utf-8') as file:
for line in data:
file.writelines(line)
file.close()
def add_contact(name, date_birth, sch_class, mid_ball):
with open('School.csv','r', encoding='utf... | Svetabtr/Homework_Python | hometask_8/modul_work.py | modul_work.py | py | 2,049 | python | en | code | 0 | github-code | 6 |
27213133585 | import sys
M = int(sys.stdin.readline().rstrip())
S = set()
for i in range(M):
line = sys.stdin.readline().rstrip().split()
command = line[0]
if command == 'all':
S = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
elif command == 'empty':
S = set()
else:
... | hammii/Algorithm | BAEKJOON_python/11723_집합.py | 11723_집합.py | py | 762 | python | en | code | 2 | github-code | 6 |
37373909261 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 3 08:08:17 2017
@author: ivyONS
"""
IVY_AUTHORISATION = ''###please enter yours credentials
DEFAULT_CONFIG = {
"subBuildingName":{
"pafSubBuildingNameBoost":1.5,
"lpiSaoTextBoost":1.5,
"lpiSaoStartNumberBoost":1.0,
"lpiS... | ONSdigital/address-index-data | DataScience/Analytics/beta/default_param.py | default_param.py | py | 3,430 | python | en | code | 18 | github-code | 6 |
34777830541 | # Set up logging
import sys
import logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
level=logging.WARNING,
)
logger = logging.getLogger(__name__)
from typing import Optional
from dat... | ServiceNow/picard | seq2seq/prediction_output.py | prediction_output.py | py | 7,647 | python | en | code | 299 | github-code | 6 |
45254772596 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 20 23 20:40:00
@author: kirsh012
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
import joblib
from sklearn.model_selection import PredefinedSplit, GridSearchCV
from sklearn.ensemble import RandomFo... | tk27182/masters-thesis | Code/run_test_randomforest.py | run_test_randomforest.py | py | 3,799 | python | en | code | 0 | github-code | 6 |
14505164780 | import typing
from qittle.http.client import ABCHTTPClient, AiohttpClient
from .abc import ABCSessionManager
class SessionManager(ABCSessionManager):
def __init__(self, http_client: typing.Optional[typing.Type[ABCHTTPClient]] = None):
self.http_client = http_client or AiohttpClient
self.... | cyanlabs-org/qittle | qittle/http/session/manager.py | manager.py | py | 621 | python | en | code | 8 | github-code | 6 |
13276813866 | import sys
from os.path import join
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QListWidgetItem, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import sqlite3
from functools import partial
class EditInfo(QWidget):
def __init__(self, id) -> None:
... | QBoff/Moscow-Kiper | task5/main.py | main.py | py | 5,993 | python | en | code | 0 | github-code | 6 |
10139749320 | from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from .forms import (CreateCourseForm,
CreateCourseRegistrationForm,
CreateDepartmentForm,
... | shreygoel7/Pinocchio | Pinocchio/academicInfo/views.py | views.py | py | 12,563 | python | en | code | 0 | github-code | 6 |
39732651900 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 12:44:53 2022
@author: mathaes
"""
import copy
class HexBoard:
"""
The HexBoard class represents a state of a game of Hex on an
n x n hexagonal-parallelogram board.
The two players are represented by X and O.
One p... | ccorbell/gametheory | hex/hexboard.py | hexboard.py | py | 9,928 | python | en | code | 0 | github-code | 6 |
28158074215 | """Destroy unused AMIs in your AWS account.
Usage:
ami_destroyer.py <requiredtag> [options]
Arguments:
<requiredtag> Tag required for an AMI to be cleaned up in the form tag:NameOfTag
Options:
--retain=<retain> Number of images to retain, sorted newest to latest [default: 2]
-... | crielly/amidestroyer | amidestroyer.py | amidestroyer.py | py | 4,275 | python | en | code | 5 | github-code | 6 |
40686886293 | import time
import unittest
import s1ap_types
from integ_tests.s1aptests import s1ap_wrapper
from integ_tests.s1aptests.s1ap_utils import MagmadUtil, SpgwUtil
class TestAttachNwInitiatedDetachFail(unittest.TestCase):
"""
S1AP Integration test for Failed Network Initiated Detach
"""
def setUp(self):
... | magma/magma | lte/gateway/python/integ_tests/s1aptests/test_attach_nw_initiated_detach_fail.py | test_attach_nw_initiated_detach_fail.py | py | 2,615 | python | en | code | 1,605 | github-code | 6 |
4222865674 | #!usr/bin/python
import os
import SimpleITK as sitk
import numpy as np
import scipy.ndimage.interpolation
import skimage.exposure
import skimage.filters
import skimage.transform
path="//Users//zhangyuwei//Desktop//test"
ShrinkFactor = 4
for i in os.walk(path):
for j in range(len(i[2])):
... | 20zzyw/Radiomic-Toolbox | N4ITK_instance.py | N4ITK_instance.py | py | 4,354 | python | en | code | 0 | github-code | 6 |
73590162109 | # Filename : 02-添加子类属性.py
# Date : 2018/8/2
"""
对象属性的继承:是通过继承init方法来继承的对象属性
给当前类添加对象属性:重写init方法,如果需要保留父类的对象属性,需要使用
super()去调用父类的init方法
多态:同一个事物有多种形态,子类继承父类的方法,可以对方法进行重写,
一个方法就有多种形态(多态的表现)
类的多态:继承产生多态
"""
class Person:
def __init__(self, name='', age=2):
self.name = name
self.age = age
class Sta... | gilgameshzzz/learn | day14Python对象3/02-添加子类属性.py | 02-添加子类属性.py | py | 1,547 | python | zh | code | 0 | github-code | 6 |
5114407056 | import numpy as np
import pandas as pd
from scipy import ndimage
from scipy.interpolate import interp1d
import astropy.units as u
import astropy.coordinates as coord
from astropy.cosmology import FlatLambdaCDM
from astropy.constants import M_sun
import tensorflow as tf
from flowpm import utils as ut
import copy
impo... | pointeee/preheat2022_public | FGPA.py | FGPA.py | py | 18,340 | python | en | code | 0 | github-code | 6 |
38454129872 | n = int(input())
L = [list(map(int,input().split())) for _ in range(n)]
papers = [0,0,0] #-1,0,1
def same(A):
ref = A[0][0]
for row in A:
for i in row:
if i != ref:
return 9
return ref
def cut(y,x,n):
global papers
num = same([L[i][x:x+n] for i in range(y,y+n)... | LightPotato99/baekjoon | recursive/papernum.py | papernum.py | py | 520 | python | en | code | 0 | github-code | 6 |
2578089451 | from collections import defaultdict
def func(nums1, nums2):
hash = defaultdict(int)
while nums1:
np1 = nums1.pop()
hash[np1[0]] += np1[1]
while nums2:
np2 = nums2.pop()
hash[np2[0]] += np2[1]
return sorted([[key, value] for key, value in hash.items()])
... | mayo516/Algorithm | 주리머/2-2w/wc/(성공) 6362. Merge Two 2D Arrays by Summing Values.py | (성공) 6362. Merge Two 2D Arrays by Summing Values.py | py | 409 | python | en | code | null | github-code | 6 |
25798704755 | #! python3
import sys
import win32api
from PyQt5.QtWidgets import QApplication, QWidget, \
QToolTip, QPushButton, QMessageBox, QDesktopWidget, \
QMainWindow, QAction, QMenu, QStatusBar
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import QCoreApplication
'''
#面向过程
app = QApplication(sys.argv)
w = QWid... | JcobCN/PyLearn | pyQt5.py | pyQt5.py | py | 3,718 | python | en | code | 0 | github-code | 6 |
28156199284 | from functools import partial
from pathlib import Path
from typing import Dict, Any, Callable, Tuple, Optional, Sequence
import PIL
import imageio
import numpy as np
import torch
from PIL import Image
from torch import Tensor
from torch.nn import Module, Tanh, Parameter
from torch.nn.functional import grid_sample, l1_... | akanimax/3inGAN | projects/thre3ingan/singans/image_model.py | image_model.py | py | 20,218 | python | en | code | 3 | github-code | 6 |
36107263574 | import torch
def unpack_data(results):
pix = results['input']
hand_pix = results['hand_pix']
fake_fish_depth = results['fake_fish_depth']
heatmap = results['heatmap']
heatmap_true = results['heatmap_true']
heatmap_reprojected = results['heatmap_reprojected']
joint = results['joint']
re... | KAIST-HCIL/DeepFisheyeNet | run/pipeline/helper.py | helper.py | py | 407 | python | en | code | 27 | github-code | 6 |
31791424883 | import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='bhamcal',
version='0.1',
license='GPL 3',
python_requires='>=3',
author='Justin Chadwell',
author_email='jedevc@gmail.com',
url='https://github.com/jedevc/bhamcal',
descripti... | jedevc/bhamcal | setup.py | setup.py | py | 881 | python | en | code | 12 | github-code | 6 |
74543276668 | # count 메소드를 활용해서 풀어보자
s='110010101001'
answer=[]
num=0
cnt=0
zero=0
while (not (s=='1')):
ones = s.count('1')
zero += len(s)-ones
s=bin(ones)[2:]
cnt+=1
# while(True):
# if(s=='1'):
# break
# #0 걷어내기
# new_s=''
# for i in s:
# if (i=='1'):
# new_... | JiHwonChoi/Algorithm | code_challenge01_05.py | code_challenge01_05.py | py | 584 | python | en | code | 0 | github-code | 6 |
74416652349 | # Ten program wyświetla pięć liczb losowych
# z przedziału od 1 do 100.
import random
def main():
for count in range(5):
# Wygenerowanie liczby losowej.
number = random.randint(1, 100)
# Wyświetlenie wygenerowanej liczby.
print(number)
# Wywołanie funkcji main().
main()
| JeanneBM/Python | Owoce Programowania/R05/25. Random_numbers2.py | 25. Random_numbers2.py | py | 317 | python | pl | code | 0 | github-code | 6 |
42677098996 | from pwn import *
# conn = remote('20.197.63.174', 3331)
conn = process(['python3', 'game.py'])
def send_replacements(lst):
global conn
n = len(lst)
confirm = [b'y'] * n
confirm[-1] = b'n'
for i in range(n):
conn.sendline(lst[i])
conn.sendline(confirm[i])
def play_level(lst, level=0):
global... | neelaryan2/CTFs | ctf/2021/iitbctf/swap_game/solve.py | solve.py | py | 1,567 | python | en | code | 0 | github-code | 6 |
60843869 | # -*- coding:utf-8 -*-
import time
import pickle
from .utils import Logger
class Scheduler(object):
spider = None
def __init__(self, crawler):
self.settings = crawler.settings
self.logger = Logger.from_crawler(crawler)
if self.settings.getbool("CUSTOM_REDIS"):
from custom... | ShichaoMa/structure_spider | structor/scheduler.py | scheduler.py | py | 2,682 | python | en | code | 29 | github-code | 6 |
24132755409 | #!/usr/bin/env python
import argparse
def filter_sam( out_fn, in_fn, chromosome):
with open(out_fn, 'w') as donor_out:
for line in open(in_fn, 'r'):
if line.startswith("@SQ"):
if "SN:{}\t".format(chromosome) in line:
donor_out.write(line)
elif line.startswith("@"):
donor_ou... | supernifty/reference-bias | bin/filter_sam.py | filter_sam.py | py | 832 | python | en | code | 2 | github-code | 6 |
811313586 | # Inserting a Node Into a Sorted Doubly Linked List
# Given a reference to the head of a doubly-linked list and an integer, , create a new DoublyLinkedListNode object having data value
# and insert it at the proper location to maintain the sort.
class DoublyLinkedListNode:
def __init__(self, data=0, prev=None, ... | Saima-Chaity/Leetcode | LinkedList/insertingANodeIntoASortedDoublyLinkedList.py | insertingANodeIntoASortedDoublyLinkedList.py | py | 1,344 | python | en | code | 0 | github-code | 6 |
1425636890 | # -*- coding: utf-8 -*-
# import needed modules
from requests import get
from csv import writer, reader
from datetime import date
import sys
# %% define function for export/save data to *.csv file
def write_csv(data, filepath):
with open(filepath, 'w', newline='') as csv_file:
write = writer(csv_file)
... | filrat2/rain_forecast | rain_forecast.py | rain_forecast.py | py | 4,691 | python | pl | code | 0 | github-code | 6 |
36229690900 | from typing import Optional
'''
1373. 二叉搜索子树的最大键值和
dfs
边统计和边判断是否为搜索树即可。
一旦子树不为搜索树,直接520520。
'''
null = None
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxSumBST(self, root: Optional[TreeNode]) ... | z-w-wang/Leetcode-Problemlist | DailyProblem/Tree/1373.2023-05-20.py | 1373.2023-05-20.py | py | 1,207 | python | en | code | 3 | github-code | 6 |
1336912689 | #!/usr/bin/env python3
from http.server import ThreadingHTTPServer
from os.path import dirname, realpath
from .httpHandler import HTTPApiHandler
from .fileCacher import cacheFile
from ..query import QueryHandler
def startServer(port):
HTTPApiHandler.queryHandler = QueryHandler()
filesPath = dirname(realpath(__... | wheelerd/uni-chatbot | stockbot/web_frontend/__main__.py | __main__.py | py | 1,427 | python | en | code | 2 | github-code | 6 |
27321029603 | """
Kela Kanta data preprocessing
Reads Kela Kanta data, applies the preprocessing steps below and writes the result to files.
- remove extra linebreaks
- remove empty lines
- transform base16 ints to base10 ints
- parse dates
- replace "," with "." as a decimal point
Note: running this script on ePouta takes several... | dsgelab/finregistry-data | finregistry_data/registries/kela_kanta.py | kela_kanta.py | py | 5,134 | python | en | code | 0 | github-code | 6 |
8665817734 | import os
import boto3
from elasticsearch import Elasticsearch
from unittest import TestCase
from me_articles_drafts_delete import MeArticlesDraftsDelete
from tests_util import TestsUtil
class TestMeArticlesDraftsDelete(TestCase):
dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:4569/')
el... | AlisProject/serverless-application | tests/handlers/me/articles/drafts/delete/test_me_articles_drafts_delete.py | test_me_articles_drafts_delete.py | py | 4,930 | python | en | code | 54 | github-code | 6 |
34199270716 | import time
import json
import requests
import datetime
import math
import sys
from pprint import pprint
s_time = time.time()
path = sys.argv[0].replace('c_timer.py', '')
# скважина качает 4м3/ч или 4000л/ч охватывая 10соток или 1000м2, т.е. за час получается 4л/м2 или 4мм
with open(path+'json/const_zones.json') as... | sdfim/watering | c_timer.py | c_timer.py | py | 2,563 | python | ru | code | 0 | github-code | 6 |
42340475091 | from coroutine import coroutine
@coroutine
def grep(pattern):
print('looking for %s pattern' % pattern)
try:
while True:
line = (yield)
if pattern in line:
print(line)
except GeneratorExit: # run when g.close() is called
print('Going away, Good bye')
... | danny-94/coroutines | grep_close.py | grep_close.py | py | 569 | python | en | code | 0 | github-code | 6 |
21618000912 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
class check_box_single():
def __init__(self):
self.driver = webdriver.Chrome('./chromedriver')
self.driver.implicitly_wait(10)
self.driver.get("ht... | CorozelEmanuel/Luxoft2021-proiect1 | Ceausu Ionut Marian/Selenium1/exemple/checkboxsingle.py | checkboxsingle.py | py | 1,572 | python | en | code | 0 | github-code | 6 |
27175032500 | from .base_source import BaseSource
import numpy as np
class LineSource(BaseSource):
def __init__(self, source_params):
super().__init__(source_params)
self.x = source_params['x_start']
self.y1 = source_params['y_start']
self.y2 = source_params['y_end']
if self.function == ... | vlrmzz/tfdtd | simulator/sources/line_source.py | line_source.py | py | 2,013 | python | en | code | 0 | github-code | 6 |
75226368188 | class Calci():
def __init__(self, tokens):
self._tokens = tokens
self._current = tokens[0]
def expression(self):
eq_result = self.term()
while self._current is '+':
self.next()
eq_result += self.term()
print(result)
while self._cur... | prashanth612/sparkcentralcalculator | Calulcator.py | Calulcator.py | py | 1,701 | python | en | code | 0 | github-code | 6 |
2516918892 | import netCDF4 as netCDF
from extraction_utils import basic, getCoordinateVariable
import json
import matplotlib.pyplot as plt
import decimal
import numpy as np
import traceback
class ImageStats(object):
"""docstring for ImageStats"""
def __init__(self, filename, variable):
super(ImageStats, self).__init__()
sel... | pmlrsg/GISportal | plotting/data_extractor/analysis_types/image_stats.py | image_stats.py | py | 2,466 | python | en | code | 71 | github-code | 6 |
6484276041 | import os
import shutil
import time
import configparser
from PIL import Image
STEP = 10
# from lib.utils import Id2name
# INPUT_DIR = r"data/MH_01_easy/mav0/cam0/data"
# OUTPUT_DIR = r"./imgs"
config = configparser.ConfigParser()
config.read("config.ini", encoding="utf-8")
INPUT_DIR = config["DEFAULT"]["SIMULATOR_... | franioli/COLMAP_SLAM | simulator.py | simulator.py | py | 1,283 | python | en | code | 0 | github-code | 6 |
26776312630 | """Apply Perl::Critic tool and gather results."""
import argparse
import logging
import subprocess
from typing import List, Optional
from statick_tool.issue import Issue
from statick_tool.package import Package
from statick_tool.tool_plugin import ToolPlugin
class PerlCriticToolPlugin(ToolPlugin):
"""Apply Perl:... | sscpac/statick | statick_tool/plugins/tool/perlcritic_tool_plugin.py | perlcritic_tool_plugin.py | py | 3,117 | python | en | code | 66 | github-code | 6 |
73029609789 | from django.db import models
class ShowManager(models.Manager):
def basic_validator(self, postData):
errors = {}
if len(postData['show_title']) < 2:
errors["show_title"] = "Show title should be at least 2 characters!"
if len(postData['show_network']) < 3:
errors["sh... | Jgomez1996/deployment_test | shows_app/models.py | models.py | py | 904 | python | en | code | 0 | github-code | 6 |
27535046003 | from common import *
def updateaddr():
rent = Mydb()
items = ['id', 'title', 'addr', 'area', 'city']
table = 'rent58'
updatelnglat = 0
updateaddr = 0
rent.select(table, items, None)
records = rent.cur.fetchall()
for record in records:
id, title, addr, area, city = record
condition = dict(id=id)
taddr = t... | flwwsg/rent58 | updateaddrs.py | updateaddrs.py | py | 1,085 | python | en | code | 0 | github-code | 6 |
41373296282 | #!/usr/bin/env python
from graph import DiGraph, before_after_calculations
import os
import json
import threading
import random
from datetime import date
def read_graphml_files():
with open('tmp/interesting_graphs.txt') as fh:
lines = [line.rstrip() for line in fh]
return [(line, DiGraph.from_graphm... | mkapra/graph_measurements_segmentation | simulate_networks.py | simulate_networks.py | py | 1,686 | python | en | code | 0 | github-code | 6 |
29279214986 | from setuptools import setup, find_packages
VERSION = '0.0.19'
DESCRIPTION = 'ParkingLot is a Python service imitating a parking lot like system.'
LONG_DESCRIPTION = 'The service indicates rather a vehicle allowed or not allowed to enter the parking lot.'
# Setting up
setup(
name="parkinglot",
vers... | PsychoRover/parking-lot | setup.py | setup.py | py | 935 | python | en | code | 0 | github-code | 6 |
28985728032 |
import sys,re, os, io, codecs
from _collections import defaultdict
def loadModelfile():
modelfile = sys.argv[1]
features = defaultdict()
#load model file into features
with open(modelfile,"r", encoding = "ISO-8859-1") as modelhandler:
model = modelhandler.readlines()
for cldata in mo... | chandrashekar-cv/POS-Tagging | ner/netag.py | netag.py | py | 3,029 | python | en | code | 0 | github-code | 6 |
72908983868 | import os
import testinfra.utils.ansible_runner
import pytest
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('all')
@pytest.mark.parametrize("name", [
("apt-transport-https"),
("software-properties-common"),
("unattended-upgrades"),
... | ddrugeon/ansible-pi-bootstrap | roles/unattended-upgrades/molecule/default/tests/test_install_mandatory_tools.py | test_install_mandatory_tools.py | py | 607 | python | en | code | 0 | github-code | 6 |
12667959383 | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from modelo import (
FuncionalidadRecetas,
FuncionalidadSemanas,
FuncionalidadConfiguracion,
)
from pdf import crear
from modelo import Recetas, Configuracion
import tkinter
class VistaApp:
def ventana_volver(ventana):
... | IgnacioGuede/Comedere | vista.py | vista.py | py | 20,056 | python | es | code | 0 | github-code | 6 |
27813014463 | import numpy as np
import gym
import cv2
class StackedEnv(gym.Wrapper):
def __init__(self, env, width, height, n_img_stack, n_action_repeats):
super(StackedEnv, self).__init__(env)
self.width = width
self.height = height
self.n_img_stack = n_img_stack
self.n_action_repeats ... | yiliu77/deep_rl_proj | environments/stacked.py | stacked.py | py | 1,405 | python | en | code | 3 | github-code | 6 |
75159668346 | import little_helper
def paths(list):
"""
>>> list(paths([[0],[1]]))
[[0, 1]]
>>> list(paths([[1, 2]]))
[[1], [2]]
>>> list(paths([[0],[1,2]]))
[[0, 1], [0, 2]]
"""
if len(list) > 0:
lists = []
for option in list[0]:
for path in paths(list... | broersma/advent-of-code-2020-python | 14_2.py | 14_2.py | py | 1,639 | python | en | code | 0 | github-code | 6 |
854412704 | version = '0.2'
identifier = 'edu.utah.sci.vistrails.itk'
name = 'ITK'
import core.bundles.utils
import core.requirements
from core.modules.vistrails_module import Module, ModuleError
# Ugly, but Carlos doesnt know any better
if core.bundles.utils.guess_system() == 'linux-ubuntu':
import sys
sys.path.append('... | VisTrails/VisTrails | contrib/itk/__init__.py | __init__.py | py | 4,935 | python | en | code | 100 | github-code | 6 |
16920362382 | from approzium import AuthClient
from approzium.pymysql import connect
auth = AuthClient(
"authenticator:6001",
# This is insecure, see https://approzium.org/configuration for proper use.
disable_tls=True,
)
conn = connect(host="dbmysqlsha1", user="bob", db="db", authenticator=auth)
with conn.cursor() as c... | cyralinc/approzium | sdk/python/examples/pymysql_connect.py | pymysql_connect.py | py | 420 | python | en | code | 57 | github-code | 6 |
19124516217 | from components import decorators
from components import endpoints_webapp2
import webapp2
import api
import config
import notifications
import service
import swarming
README_MD = (
'https://chromium.googlesource.com/infra/infra/+/master/'
'appengine/cr-buildbucket/README.md')
class MainHandler(webapp2.Request... | mithro/chromium-infra | appengine/cr-buildbucket/handlers.py | handlers.py | py | 1,762 | python | en | code | 0 | github-code | 6 |
28705152846 | # Дана упорядоченная последовательность an чисел от 1 до N.
# Из копии данной последовательности bn удалили одно число, а оставшиеся перемешали. Найти удаленное число.
import random
n = int(input('Введите длину последовательности: '))
first_list = [i for i in range(1, n + 1)]
set_first_list = set(first_list)
print(f'... | MihailOgorodov/python_courses | seminar3/4.py | 4.py | py | 788 | python | ru | code | 0 | github-code | 6 |
37877845832 | import datetime
from PySide2.QtWidgets import QDialog
from ui_add_update import Ui_Dialog
class addDialog(QDialog):
def __init__(self, *args, **kvargs):
super().__init__(*args, **kvargs)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.OkButton.clicked.connec... | randrust/cashflow_pyside2 | dialogs/add_dialog.py | add_dialog.py | py | 1,602 | python | en | code | 0 | github-code | 6 |
30358219721 | import unittest
from traits.api import HasTraits, Int, Str, Tuple
from traitsui.api import Item, View
from traits.testing.api import UnittestTools
from traitsui.tests._tools import (
BaseTestMixin,
create_ui,
requires_toolkit,
reraise_exceptions,
ToolkitName,
)
class TupleEditor(HasTraits):
... | enthought/traitsui | traitsui/tests/editors/test_tuple_editor.py | test_tuple_editor.py | py | 2,229 | python | en | code | 290 | github-code | 6 |
31331693062 | #! /usr/bin/python3
import os
import sys
import glob
import time
import shutil
import logging
import argparse
import subprocess
import pandas as pd
from pathlib import Path
from itertools import repeat
from multiprocessing import Pool
from nest.bbduk import QualCheck
from nest.alignment import Bwa
from nest.alignment i... | ohjeyy93/NFNeST | nest.py | nest.py | py | 21,367 | python | en | code | 0 | github-code | 6 |
3167046119 | #!/usr/bin/env python3
import base64
from functions.aes import (
gen_random_bytes,
get_blocks,
pkcs7_unpad,
pkcs7_pad,
PKCS7Error,
AESCipher,
)
_STRINGS = [
base64.b64decode(s)
for s in [
"MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=",
"MDAwMDAxV2l0aCB0aGUgYmFzcyB... | svkirillov/cryptopals-python3 | cryptopals/set3/challenge17.py | challenge17.py | py | 2,562 | python | en | code | 0 | github-code | 6 |
29478342356 | import sys
import networkx as nx
from assignNetwork import assignNetwork
conflicts = []
messageTypes = []
incomingMessages = []
outgoingMessages = []
stableStates = []
graph = {}
G = nx.MultiDiGraph()
assert len(sys.argv[1:]) <= 2, "Too many arguments"
file = sys.argv[1]
if(len(sys.argv[1:]) == 2):
constraiantFil... | ChingLingYeung/honoursProject | simple_conflict.py | simple_conflict.py | py | 10,499 | python | en | code | 0 | github-code | 6 |
27392319981 | key = []
image = dict()
with open("Day20.txt", 'r') as INPUT:
data = INPUT.read().replace(".", "0").replace("#", "1").split("\n\n")
key = list(map(int, list(data[0])))
rest = data[1].split("\n")
for i in range(len(rest)):
a = list(map(int, list(rest[i])))
for j in range(len(a)):
... | stepheneldridge/Advent-of-Code-2021 | Day20.py | Day20.py | py | 1,594 | python | en | code | 0 | github-code | 6 |
29792276111 | #!/usr/bin/env python3
import pandas as pd
import os
import rospy
import rospkg
from std_msgs.msg import Bool
from robo_demo_msgs.srv import RunPlanningTest
rospack = rospkg.RosPack()
EE_CONTROL_PATH = rospack.get_path('end_effector_control')
PLANNING_DATA_PATH = os.path.join(EE_CONTROL_PATH, 'data', 'planning')
CO... | dwya222/end_effector_control | scripts/automate_testing_v2.py | automate_testing_v2.py | py | 1,922 | python | en | code | 0 | github-code | 6 |
32599097431 | from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class Hellocall(Resource):
def get(self,name,number):
return({'Name':name,'Age':number})
api.add_resource(Hellocall,"/Helloworld/<string:name>/<int:number>")
if __name__ == "__main__":
app.run(debug=... | somasundaram1702/Flask-basics | main.py | main.py | py | 330 | python | en | code | 0 | github-code | 6 |
40413480181 | import re
import requests
from bs4 import BeautifulSoup
from time import time as timer
__author__ = "Allen Roberts"
__credits__ = ["Allen Roberts"]
__version__ = "1.0.0"
__maintainer__ = "Allen Roberts"
def readfile():
with open('KY.txt') as file:
lines = file.readlines()
print(lines)
return line... | AllenRoberts/EmailScraper | main.py | main.py | py | 3,463 | python | en | code | 0 | github-code | 6 |
8568584883 | # Create class
from Tools.Scripts.treesync import raw_input
import datetime
from datetime import date
class Person:
def __init__(self, name,year,month,day):
self.__name=name
self.__year=year
self.__month=month
self.__day=day
def getage(self):
now = date... | iWanjugu/Personal-Development-II | Python/getAge.py | getAge.py | py | 673 | python | en | code | 0 | github-code | 6 |
6288317611 | #! /usr/bin/env python
import math
import rospy
from sensor_msgs.msg import Imu
from tf.transformations import euler_from_quaternion
def imuCallback(imu):
quat = [imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z]
roll, pitch, yaw = euler_from_quaternion(quat)
rospy.loginfo('{} {} {}'.f... | vigneshrajap/UNSW-work | imu_to_yaw/src/imu_to_yaw_node.py | imu_to_yaw_node.py | py | 558 | python | en | code | 2 | github-code | 6 |
39513139874 | from tkinter import *
from tkinter import ttk
class FileSaveFrame(Frame):
def __init__(self, master,filename,app):
ttk.Frame.__init__(self, master)# super class initialization
self.relief = GROOVE# tkinter relief attribute.
self.grid()# grid the frame
self.grid_columnconfig... | dnsmalla/Water-splitting-measurement-LCR-GUI | gui_frames/fileSaveFrameGUI.py | fileSaveFrameGUI.py | py | 2,144 | python | en | code | 0 | github-code | 6 |
28747708713 | from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
def index(request):
omi = "omprakash"
import urllib
import json
resp = urllib.urlopen('https://api.coursera.org/api/courses.v1?q=search&query=malware+undergroun... | aumiom/Educational-Website-Template-with-Coursera-Search-API-Integration | myproject/myapp/views.py | views.py | py | 1,090 | python | en | code | 1 | github-code | 6 |
71893897149 | from Board import Board
from User import User
from Server import Server
import sys
import os
import socket
import json
import threading as th
#-------------------------------------------------------------------------------------
'''
In class library phase you should implement your basic classes and write a command
... | e-hengirmen/ceng445-term-project | phase4/main.py | main.py | py | 6,994 | python | en | code | 0 | github-code | 6 |
17046267898 | import struct
class InvalidArgumentException(Exception):
pass
class Color:
def __init__(self, r, g, b):
self.red = r
self.green = g
self.blue = b
self._validate()
def _validate(self):
for v in [self.red, self.green, self.blue]:
if not(0 <= v <= 255):
... | meganehouser/kantencolors | project/gif.py | gif.py | py | 6,258 | python | en | code | 0 | github-code | 6 |
7323978481 | import enemy
from enemy import *
class CHero(CEnemy):
def clean(self,fair=True):
if fair:
self.skill = dice()+6
self.stamina = dice(2)+12
self.luck = dice()+6
else:
self.skill = 12
self.stamina = 24
self.luck = 12
self.maxskill = self.skill
self.maxstamina = self.stamina
self.maxluck = self... | Vo1t/sol | hero.py | hero.py | py | 657 | python | en | code | 0 | github-code | 6 |
17720876787 | import view as vw
import logger as log
import model as ml
import is_number as is_n
def run():
while True:
select_action = vw.select_action()
if is_n.is_number(select_action):
data_file = log.get_data()
if select_action == 1:
if not data_file:
... | tim24ktk/homework_8 | controller.py | controller.py | py | 3,079 | python | en | code | 0 | github-code | 6 |
15060558322 | import csv
import json
species_file = open('./data/union_list.json','r')
species_list = json.loads(species_file.read())
country_codes = [
"BG",
"HR",
"CZ",
"DK",
"NL",
"UK",
"EE",
"FI",
"FR",
"DE",
"GR",
"HU",
"IE",
"IT",
"LV",
"LT",
"MT",
"PL",... | eea/ias-dataflow | scripts/parse_common_names.py | parse_common_names.py | py | 1,330 | python | en | code | 0 | github-code | 6 |
9004329912 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'siscoer.views.home', name=... | clebersa/2014-1-gps-siscoer | src/siscoer/siscoer/urls.py | urls.py | py | 1,206 | python | en | code | 0 | github-code | 6 |
16312672546 | r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 <r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos podem formar um triângulo, ', end='')
if r1 == r2 == r3: # ou r1 == r2 and r2 == r3
print('EQUILÁTERO')
... | igorfreits/Studies-Python | Curso-em-video/Mundo-2/AULA12-Condições-Aninhadas/#042 - Analisando Triângulos v2.0.py | #042 - Analisando Triângulos v2.0.py | py | 485 | python | pt | code | 1 | github-code | 6 |
71429998588 | from django.db.models import Q
from django.shortcuts import get_object_or_404
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.excep... | izunaaaaa/CurB_Backend | letterlist/views.py | views.py | py | 5,352 | python | en | code | 0 | github-code | 6 |
17347679642 |
from django.urls import path, include
from .views import LoginView, RegisterView, \
LogoutView, DepartView, JobView, SetPwd, DepartEditView, JobEditView, \
JobRelateUserView, DepartRelateUserView, AppointWorkflowAdmin, IndexView, AppointCommon, AddDepartView, \
DepartRelateUserEditView, AddJobView, JobRela... | cuifeihe/django_WorkFlowProject | app_account/urls.py | urls.py | py | 2,353 | python | zh | code | 0 | github-code | 6 |
39839377690 | #Library
import datetime
import time
from tkinter import *
import tkinter.ttk as ttk
from urllib.request import urlretrieve
import serial
import os
import RPi.GPIO as GPIO
#End Library
#Firmwares
ultra1 = serial.Serial("/dev/ttyUSB0",baudrate=9600, timeout=1)
gsm = serial.Serial("/dev/ttyAMA0",baudrate=9600, timeout=1... | sinameshkini/python_samples | sajab4.py | sajab4.py | py | 16,045 | python | en | code | 0 | github-code | 6 |
38045683002 | from plugin_format import PluginFormat
class PlugIn(object):
def __init__(self, name, version, plugin_format, file_path):
self.name = name
self.version = version
self.plugin_format = plugin_format
self.file_path = file_path
def __str__(self):
name = f"name={self.name}"... | adrianswiatek/py-plugins | plugin.py | plugin.py | py | 1,420 | python | en | code | 0 | github-code | 6 |
21480310570 | import bpy
import re
def get_group_name_from_data_path(data_path):
m = re.match(r'^pose\.bones\[\"([^\"]+)"\]', data_path)
if m:
return m[1]
# For pose blender. Should probably not be hardcoded
m = re.match(r'^\[\"([^\"]+)"\]$', data_path)
if m and m[1].endswith("_pose"):
... | greisane/gret | anim/channels_auto_group.py | channels_auto_group.py | py | 2,546 | python | en | code | 298 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.