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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74999826215 | # -*- coding:utf-8 -*-
import cv2 as cv
import numpy as np
import mahotas
import utils
import os
#全局阈值
def threshold_demo(gray):
#直接阈值化是对输入的单通道矩阵逐像素进行阈值分割。
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
cv.namedWindow("binary0", cv.WINDOW_NORMAL)
cv.imshow("binary0", bi... | yjesefcu/meter_ocr | binary.py | binary.py | py | 2,701 | python | en | code | 2 | github-code | 90 |
18488262229 | N,M=map(int,input().split())
def primes(n):
d=[]
for i in range(1, int(n**0.5) + 1):
if n%i==0:
d.append(i)
if n//i!=i:
d.append(n//i)
d.sort()
return d
d=primes(M)
for i in d[::-1]:
if M//i>=N:
ans=i
break
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p03241/s426371620.py | s426371620.py | py | 306 | python | en | code | 0 | github-code | 90 |
71774381098 | """
Create a single JSON-L file for evaluation results on 1k test examples.
- update
- 3 backgrounds (human, Flan-T5, GPT-3.5)
- BUS (GPT and human) questions and answers
- BW evaluation: best sys, worst sys, and justifications
"""
import argparse
import json
import logging
from collections import defaultdict
from pat... | amazon-science/background-summaries | src/prepare_human_eval_jsonl.py | prepare_human_eval_jsonl.py | py | 10,991 | python | en | code | 0 | github-code | 90 |
18572564139 | from collections import deque
n, m = map(int, input().split())
tree = [[] for _ in range(n)]
for _ in range(m):
L, R, D = map(int, input().split())
tree[L - 1].append((R - 1, D))
tree[R - 1].append((L - 1, -D))
visited = [None for _ in range(n)]
def bfs(u):
q = deque([[u, 0]])
visited[u] = 0
... | Aasthaengg/IBMdataset | Python_codes/p03450/s895817369.py | s895817369.py | py | 771 | python | en | code | 0 | github-code | 90 |
70240531497 | import heapq
# 일반적으로 heapsort의 시간복잡도는 O(NlogN)
def minheapsort(iterable):
h = []
result = []
# 모든 원소를 차례대로 힙에 삽입
for value in iterable:
heapq.heappush(h, value)
# 힙에 삽입된 모든 원소를 차례대로 꺼내어 담기.
for i in range(len(h)):
result.append(heapq.heappop(h))
return result
result = minhe... | Try615/MyCodingTestStudy | ThisisCodingTest/team_note/heapsort_using_heapq.py | heapsort_using_heapq.py | py | 886 | python | ko | code | 0 | github-code | 90 |
38993387014 | from ctc import evm
from ctc import rpc
from ctc.protocols import ens_utils
def get_command_spec():
return {
'f': async_owner_command,
'help': 'output owner of ENS name',
'args': [
{'name': 'name', 'help': 'ENS name'},
{'name': '--block', 'help': 'block number'},
... | 0xmzz/checkthechain | src/ctc/protocols/ens_utils/cli/ens/owner_command.py | owner_command.py | py | 581 | python | en | code | null | github-code | 90 |
73910383975 | from .base import BaseGeneratorDefinition
from AppKit import *
import wx
class TestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, evt):
dc = wx.PaintDC(self)
gc = wx.GraphicsContext.Create(dc)
... | yanone/ynglib | Lib/ynglib/generators/wxWindow.py | wxWindow.py | py | 4,603 | python | en | code | 1 | github-code | 90 |
36701684484 | import rospy
from humanoid_league_msgs.msg import GameState, RobotControlState
from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement
class CheckFallen(AbstractDecisionElement):
"""
Checks if robot is fallen
"""
def perform(self, reevaluate=False):
self.clear_debu... | MosHumanoid/bitbots_thmos_meta | bitbots_navigation/bitbots_localization/src/bitbots_localization/localization_dsd/decisions/decisions.py | decisions.py | py | 3,750 | python | en | code | 3 | github-code | 90 |
12948484147 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Flatten, Conv1D, MaxPool1D
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selecti... | Divyaansh313/Xebia_Hackathon | CustomerSatisfaction.py | CustomerSatisfaction.py | py | 3,355 | python | en | code | 0 | github-code | 90 |
43670382340 | import numpy as np
import torch
from torchvision import datasets, transforms
"""
This code will be used to process the data from the MNIST data set.
Data referring to images of zeros and ones digits will be considered.
"""
def dataMNIST2(ntrain,ntest):
'''
input
ntrain:(int) number of training data, for example, ... | lucasfriedrich97/Evolution-strategies-application-in-hybrid-quantum-classical-neural-networks | DATA.py | DATA.py | py | 1,938 | python | en | code | 3 | github-code | 90 |
29050232497 | #!/usr/bin/python3
from datetime import datetime
import time
import random
odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39,
41, 43, 45, 47, 49, 51, 53, 55, 57, 59]
right_this_minute = datetime.today().minute
for x in range(5):
if right_this_minute in odds:
... | realbadbytes/python_practice | head_first_python/odd.py | odd.py | py | 540 | python | en | code | 0 | github-code | 90 |
21311051231 | from __future__ import division
from pyomo.environ import *
import pandas as pd
from haversine import haversine, Unit
def haversine_distance_matrix(df):
# Create line list
all_lines = []
for id1 in list(df.B):
for id2 in list(df.B):
all_lines.append(f"{id1}_{id2}")
# Create node a... | rossmclane/demand_projection | src/distance_calc_utils.py | distance_calc_utils.py | py | 761 | python | en | code | 0 | github-code | 90 |
34010490123 | import pygame
class Laser:
def __init__(self, width, height, x, y):
self.width = width
self.height = height
self.x = x
self.y = y
self.velocity = 5
self.hitbox = (self.x + 9, self.y, 8, 32)
def draw(self, screen, image):
self.hitbox = (self.x + 9, self.y... | JFiedler23/PyInvaders | Source/laser.py | laser.py | py | 437 | python | en | code | 0 | github-code | 90 |
73820214697 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
stack =... | HarrrrryLi/LeetCode | 112. Path Sum/Python 3/solution.py | solution.py | py | 821 | python | en | code | 0 | github-code | 90 |
29005782781 | # Komodo Outings
# Komodo accountants need a list of all outings, the cost of all outings combined, and the
# cost of all types of outings combined.
# Here are the parts of an outing:
# Event Type:
# Golf, Bowling, Amusement Park, Concert
# Number of people that attended,
# Date,
# Total cost per person for the... | Rion5/Python_Gold_Badge_Challenges | challenge_3/ui.py | ui.py | py | 3,181 | python | en | code | 0 | github-code | 90 |
982525018 | from transformers import pipeline, set_seed
def generator(prompt, max_length):
model = pipeline('text-generation', model='xlnet-base-cased')
set_seed(42)
result = model(prompt, max_length=max_length, num_return_sequences=1)
return result
def pred(a, b):
nlp = pipeline("fill-mask", model='distilbert-base-cas... | fangyiyu/NLP_WebApplication | apps/predict.py | predict.py | py | 1,413 | python | en | code | 5 | github-code | 90 |
26399151337 | import json
import subprocess
import requests
from datetime import datetime
to_chatdownloader = "../../Twitch-Chat-Downloader/"
def extract_id(json_file, out_name):
counter = 0
with open (json_file, "r") as f, open (out_name, "w") as output:
data = json.load(f)
for video in data["videos"]:
... | Sotskin/Twitch-Chat-SA | data/downloader/util.py | util.py | py | 1,173 | python | en | code | 0 | github-code | 90 |
40502011730 | """
input: an image and text
output: an edited image
"""
import torch
from PIL import Image
import os
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler
from pipeline import StableEditPipeline
def main():
has_cuda = torch.cuda.is_a... | feizc/Stable-Edit | infer_recon.py | infer_recon.py | py | 3,071 | python | en | code | 21 | github-code | 90 |
19253860285 | from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 4)
stdin = open("./input.txt", "r")
num_of_friends, num_of_relations = map(int, stdin.readline().split())
graph = {}
answer = 0
for person in range(num_of_friends):
graph[person] = []
for _ in range(num_of_relations):
start, finish = map(int, s... | ag502/algorithm | Problem/BOJ_13023_ABCDE/main.py | main.py | py | 1,011 | python | en | code | 1 | github-code | 90 |
7336528212 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'luotianshuai'
# 一 enumerrate函数
#
# #一般情况下对一个列表话属组记要遍历所以又要遍历元素时,会这样写
check_list = [1, 2, 3, 4, 5, 6, 7]
for i in range(0, len(check_list)):
print(i, len(check_list))
# #但是这种方法有些累赘,使用内置的enumerrate函数会有更直接更优美的做法
'''
emumerate会降属组或列表组成一个索引序列,使我们在获取索引和索引内容的时候更加... | luotianshuai/notes-doemos | python/Guide_1/check_enumerate.py | check_enumerate.py | py | 1,597 | python | zh | code | 1 | github-code | 90 |
27306407715 | n = int(input())
matrix = []
for i in range(n):
matrix.append([str(i) for substring in input() for i in substring])
symbol = str(input())
exists = False
for i in range(n):
for j in range(n):
if matrix[i][j] == symbol:
exists = True
break
if exists:
break
if exist... | MEngMihailTodorov/Softuni_courses | Softuni_Advanced_2022/Advanced/Python_Advanced/03_Multidimensional_Lists_Matrices_Lab/06_Symbol_in_Matrix.py | 06_Symbol_in_Matrix.py | py | 398 | python | en | code | 0 | github-code | 90 |
17130447067 | from typing import List
import logging
logger = logging.getLogger(__name__)
def concat_7bits(byte_list: List[int]):
if len(byte_list) == 1:
return byte_list[0] & 0b01111111
reversed_byte_list = byte_list.copy()
reversed_byte_list.reverse()
logger.debug(reversed_byte_list)
number = revers... | GoYoshino/some_project | underrail_translation_kit/msnrbf_parser/math_/seven_bits.py | seven_bits.py | py | 1,574 | python | en | code | 0 | github-code | 90 |
26587518671 | from typing import List
from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter
from sqlalchemy.orm import Session
from .. import models, schemas
from ..database import get_db
router = APIRouter(
prefix= "/posts",
tags=['posts']
)
# Fetch all posts
@router.get("/", response_model=Lis... | ram8545/FASTAPI | app/routers/post.py | post.py | py | 2,123 | python | en | code | 0 | github-code | 90 |
7656915206 | """Launch realsense2_camera node."""
import copy
import os
import sys
import pathlib
import yaml
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription,DeclareLaunchArgument
from launch_ros.actions import Node
from launch.su... | iamchoking/raibo-smd_ros | launch/head_launch.py | head_launch.py | py | 5,085 | python | en | code | 3 | github-code | 90 |
22612927845 | # coding=utf-8
# https://leetcode-cn.com/problemset/algorithms/
class Solution:
def kidsWithCandies(self, candies, extraCandies):
"""
:param candies:
:param extraCandies:
:return:
"""
result_list = []
for candy in candies:
candy += extraCandies
... | zhuyuanwang/Leetcode_study | leetcode.py | leetcode.py | py | 1,170 | python | en | code | 0 | github-code | 90 |
24999060133 | #*******************************************************************************#
# Fecha Creación: 02 Abril 2021. #
# Autor: Iván Fonseca Castro #
# ... | ivandeveloper506/Code-Data-Modeling-Instagram | src/models.py | models.py | py | 3,222 | python | es | code | 0 | github-code | 90 |
37876375360 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return head
length = 0
... | haneehareshpatel/Leetcode-problems | my-folder/problems/rotate_list/solution.py | solution.py | py | 861 | python | en | code | 0 | github-code | 90 |
36845058865 | #written by me
"""""
pizza_type = input("which type of pizza do you want? S, M or L?")
if pizza_type == "S":
bill = 15
pep_small = input("Do you want peproni? Y or N? ")
if pep_small == "Y":
bill+= 2
extra_cheese= input("Do you want extra cheese? Y or N ")
if extra_cheese == "Y":
... | asadid-17/1pycode | day3/pizza.py | pizza.py | py | 1,665 | python | en | code | 1 | github-code | 90 |
4536130608 | import pandas as pd
from pandas import DataFrame
from BaseTools import createConnect, updateTable, createEngine
from datamodel.Data import DataBase, DataTable
def saveUser(dataFrame: DataFrame, tableName):
con = createConnect(DataBase.General)
sql = "show global variables like 'max_allowed_packet';"
con.... | laozeng1982/workoutDB | ExcerciseDataHelper.py | ExcerciseDataHelper.py | py | 1,456 | python | en | code | 0 | github-code | 90 |
4122887424 | from concurrent.futures import ProcessPoolExecutor
from Mdp.at_high_model_components.at_high_policy_player import HighPolicyPlayer
from inverse_reinforcement_learning.compare_processor import CompareProcessor
from inverse_reinforcement_learning.get_model_probas import ModelProbasGetter
from inverse_reinforcement_learn... | bartekwojcik/DataPreprocessingMasters | src/inverse_reinforcement_learning/process_file.py | process_file.py | py | 4,022 | python | en | code | 0 | github-code | 90 |
37349038440 | import copy
import functools
import itertools
import os
from tempfile import mkstemp
from taichi._lib import core as _ti_core
from taichi.lang import cc, cpu, cuda, gpu, metal, opengl, vulkan
from taichi.lang.misc import is_arch_supported
import taichi as ti
# Helper functions
def get_rel_eps():
arch = ti.cfg.a... | josephgalestian/taichiV2-master | tests/test_utils.py | test_utils.py | py | 6,371 | python | en | code | 0 | github-code | 90 |
17975698869 | import sys
stdin = sys.stdin
mod = 1000000007
inf = 1 << 60
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda x: [na() for _ in range(x)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda x: [ns() for _ in range(x)]
nas = lambda: stdin.readline().split()
ab = na()
ab.appe... | Aasthaengg/IBMdataset | Python_codes/p03657/s447696278.py | s447696278.py | py | 475 | python | en | code | 0 | github-code | 90 |
41736525206 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
#%matplotlib inline
class Regression:
def __init__(self, train1, x_train, x_test, y_train, y_test, label... | habib09/House-Rent-Prediction | HouseRentPredictor.py | HouseRentPredictor.py | py | 5,598 | python | en | code | 0 | github-code | 90 |
17993030539 | def actual(x, y):
group1 = {1, 3, 5, 7, 8, 10, 12}
group2 = {4, 6, 9, 11}
group3 = {2}
for group in [group1, group2, group3]:
if x in group and y in group:
return 'Yes'
return 'No'
x, y = map(int, input().split())
print(actual(x, y)) | Aasthaengg/IBMdataset | Python_codes/p03711/s891158241.py | s891158241.py | py | 276 | python | en | code | 0 | github-code | 90 |
9505526314 | # !/usr/bin/env python
# -- coding: utf-8 --
# @Time : 2021/1/8 16:31
# @Author : liumin
# @File : yolov5_backbone.py
import torch
import torch.nn as nn
# from ..modules.yolov5_modules import parse_yolov5_model
from ..modules.yolov5_modules import Focus, Conv, C3, SPP
class YOLOv5Backbone(nn.Module):
... | yunwuhen/CvPytorch | src/models/backbones/yolov5_backbone.py | yolov5_backbone.py | py | 3,597 | python | en | code | null | github-code | 90 |
3461927532 | import itertools
import os
import sys
from pathlib import Path
from shutil import rmtree
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import metrics
from sklearn.metrics import precision_score, recall_score, roc_auc_score, roc_curve, confusion_matrix, accura... | 09Raghu09/A1_projects | Machine learning/Transcriptomics/NB_classifier/Naive_Bayes.py | Naive_Bayes.py | py | 12,466 | python | en | code | 0 | github-code | 90 |
33758386164 | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
from app.service.product_post_service import ProductPostService
from app.service.product_put_service import ProductPutService
from app.models.product import Product, product_schema
from unittest.mock import MagicMoc... | bibek-bhattacharya/online-store | tests/test_product_post_service.py | test_product_post_service.py | py | 1,613 | python | en | code | 0 | github-code | 90 |
41654840737 | #file: proj2.py
#author: John Larson
#Date: 5/3/2014
#Section: 1
#Email: larson3@umbc.edu
#Description:
#This file contains code which will display a bookstore's inventory by title, author and allow changes to be made to the inventory
#greeting() prints a greeting for the user
#input: none
#output: greeting
def greet... | larson3/GL | 201/Projects/proj2/proj2.py | proj2.py | py | 16,985 | python | en | code | 0 | github-code | 90 |
24267619544 | class City:
#citys ejhsdskdfhf
def __init__(self, n_rows, n_columns, n_vehicles, n_rides, ride_bonus, n_steps):
self.n_rows = n_rows
self.n_columns = n_columns
self.n_vehicles = n_vehicles
self.n_rides = n_rides
self.ride_bonus = ride_bonus
self.n_steps = n_steps
... | veselypeta/HashCode2018 | City.py | City.py | py | 337 | python | en | code | 2 | github-code | 90 |
18537104559 | n, m = map(int, input().split())
p = list(map(int, input().split()))
xy = [list(map(int, input().split())) for _ in range(m)]
from collections import defaultdict
g = defaultdict(list)
for x, y in xy:
x, y = x - 1, y - 1
g[x].append(y)
g[y].append(x)
visited = [0] * n
ans = 0
for i in range(n):
if vis... | Aasthaengg/IBMdataset | Python_codes/p03354/s958011513.py | s958011513.py | py | 767 | python | en | code | 0 | github-code | 90 |
36260976399 | from flask import Flask
import sqlite3
app = Flask(__name__)
@app.route("/insert")
def main():
connect = sqlite3.connect("db.db")
cursor = connect.cursor()
cursor.execute("INSERT INTO Loger (type, message, date, time, url) VALUES (?, ?, ?, ?, ?)", (1, "test", "2020-12-05", "11:11:11", "/ures/add"))
con... | klmax123/loger | main.py | main.py | py | 360 | python | en | code | 0 | github-code | 90 |
11028370213 | # -*- coding: utf-8 -*-
import json
from datetime import datetime
from dateutil.parser import parse
from data.logs_model.datatypes import AggregatedLogCount, Log, LogEntriesPage
def _status(d, code=200):
return {"status_code": code, "content": json.dumps(d)}
def _shards(d, total=5, failed=0, successful=5):
... | quay/quay | data/logs_model/test/mock_elasticsearch.py | mock_elasticsearch.py | py | 9,303 | python | en | code | 2,281 | github-code | 90 |
42256453787 | import os
import pyproj
from qgis.PyQt.QtCore import QVariant, QUrl
from qgis.PyQt.QtGui import QIcon
from qgis.core import (
QgsFields, QgsField, QgsFeature, QgsWkbTypes, QgsCoordinateReferenceSystem,
QgsCoordinateTransform, QgsProject, QgsPoint, QgsGeometry)
from qgis.core import (
QgsProcessing,
Qgs... | NationalSecurityAgency/qgis-latlontools-plugin | ecef.py | ecef.py | py | 11,694 | python | en | code | 283 | github-code | 90 |
70694248618 |
import click
import zmq
import struct
from time import sleep, time
class zmq_env:
def __init__(self):
self.context = zmq.Context()
self.trdbox = self.context.socket(zmq.REQ)
self.trdbox.connect('tcp://localhost:7766')
self.sfp0 = self.context.socket(zmq.REQ)
self.sfp0.co... | tdietel/alicetrd-python | src/dcs/minidaq.py | minidaq.py | py | 2,437 | python | en | code | 0 | github-code | 90 |
17948605189 | S = input()
flag = 0
k = "YAKI"
if len(S)<4:
print("No")
flag = 1
else:
for i in range(4):
if S[i] != k[i]:
flag = 1
print("No")
break
if flag == 0:
print("Yes") | Aasthaengg/IBMdataset | Python_codes/p03591/s879744612.py | s879744612.py | py | 221 | python | en | code | 0 | github-code | 90 |
17983303499 | n=int(input())
a=[0]
for i in range(n):
a.append(int(input()))
m=1
ans=0
for i in range(n):
if m==2:
print(ans)
exit()
else:
m=a[m]
ans+=1
print(-1)
| Aasthaengg/IBMdataset | Python_codes/p03680/s847555932.py | s847555932.py | py | 206 | python | en | code | 0 | github-code | 90 |
18581363129 | #33 2020/07/14
A, B = input().split(' ')
A = int(A)
B = int(B)
S = input()
if not '-' in S:
print('No')
else:
S = S.split('-')
if '-' in S[0] or '-' in S[1]:
print('No')
elif len(S[0]) == A and len(S[1]) == B:
print('Yes')
else:
print('No')
| Aasthaengg/IBMdataset | Python_codes/p03474/s806766721.py | s806766721.py | py | 263 | python | en | code | 0 | github-code | 90 |
18418454039 | import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
a,b = map(int, input().split())
c = a - 1
d = b - 1
print(max(a + c, b + d, a + b))
| Aasthaengg/IBMdataset | Python_codes/p03071/s952076927.py | s952076927.py | py | 154 | python | en | code | 0 | github-code | 90 |
9139850333 | from pathlib import Path
import sys
import re
import json
def is_plural(definition):
"""
checks definition to see if word is plural.
if so - changes to singular
"""
regex = re.compile('^[ \-а-яёй.,]+ (ед.)')
singular = regex.findall(definition)
return len(singular) != 0
def is_noun(defin... | alexonov/wordle-ru | scripts/extract_words_from_slovar.py | extract_words_from_slovar.py | py | 1,995 | python | en | code | 0 | github-code | 90 |
5150938106 | from datetime import datetime as dt
import pandas as pd
from cassandra.cluster import Cluster
from order import Order
class DBWorker(object):
def __init__(self, address, db ):
self.cluster = Cluster([address])
self.session = self.cluster.connect(db)
self.cluster.register_user_type('marke... | sandra-sto/market-analysis | market_analysis/deep_q_learning/data_api/db_worker.py | db_worker.py | py | 3,533 | python | en | code | 0 | github-code | 90 |
37151124460 | # set 에 저장
# set 에 있을 때, 전의 값이랑 같으면 통과
# set 에 있는데, 전의 값이랑 다르면 나가리
n = int(input())
result = 0
for _ in range(n):
s = input()
hash_set = set()
flag = True
for i in range(len(s)):
if s[i] not in hash_set:
hash_set.add(s[i])
i += 1
elif s[i] in hash_set:
... | camel-man-ims/coding-test-python | problems/backjoon_혼자풀어보기/구현/정리3/그룹단어체커.py | 그룹단어체커.py | py | 555 | python | ko | code | 0 | github-code | 90 |
1478181577 | from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def head():
first = "This is my first conditional experience in Flask"
return render_template("index.html", mesaj = first) # Burada msjı silersek else condition çalışır (index.html'deki)
@app.route("/sec")
def for_structure():
... | polymerr/Clarusway-aws-devops-workshop | python/hands-on/Hands-On-2/app-hands-on2.py | app-hands-on2.py | py | 496 | python | en | code | 0 | github-code | 90 |
13773316307 | from commons.constants import CANDLE_CLOSE_COLUMN
from indicator.overlap import ma
def bbands(df, col=CANDLE_CLOSE_COLUMN, period=200, width=2, ma_method='sma'):
"""布林带指标"""
period = int(period)
width = float(width)
series = df[col]
df['BBM'] = ma(ma_method, series, period)
std = series.rollin... | sean-liang/crypto-quant-toolkit | indicator/volatility.py | volatility.py | py | 519 | python | en | code | 0 | github-code | 90 |
23729371994 | import json
import os
from pathlib import Path
from typing import Any, Dict, Tuple
from pydantic import BaseSettings, PostgresDsn
from pydantic.env_settings import SettingsSourceCallable
class Settings(BaseSettings):
database_dsn: PostgresDsn
class Config:
@classmethod
def customise_sources(... | rifatrakib/practical-pydantic | settings/customise-settings-sources.py | customise-settings-sources.py | py | 2,188 | python | en | code | 0 | github-code | 90 |
34626314515 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import albumentations as A
import numpy as np
import cv2
from albumentations.pytorch import ToTensorV2
import timm
import nltk
nltk.download("punkt")
# Unwieldy amount of Code: Because it's not in a Jupyter Notebook.
devi... | ShaoA182739081729371028392/Machine-and-Deep-Learning-Mini-Projects | Image Captioning and Heroku/React Files/captioner.py | captioner.py | py | 10,215 | python | en | code | 0 | github-code | 90 |
4124036061 | #!/usr/bin/env python3
""" TODO: docstring """
import numpy as np
# np.random.seed(42)
import lie_algebra as lie
from landmark_detection import landmark_detection
landmarks = np.array([
[1.0, 5.0, 0.0],
# [1.0, 10.0, 0.0],
# [1.0, -5.0, 0.0],
# [1.0, -10.0, 0.0],
[-5.0, 5.0, 0.0],
[5.0, 5.0,... | Butakus/landmark_placement_optimization | lpo/metrics.py | metrics.py | py | 4,124 | python | en | code | 1 | github-code | 90 |
12593285783 | import ctypes
from cwrap import BaseCClass
from ecl import EclPrototype
from ecl.util.geometry import CPolyline
class CPolylineCollection(BaseCClass):
TYPE_NAME = "geo_polygon_collection"
_alloc_new = EclPrototype("void* geo_polygon_collection_alloc( )" , bind = False)
_free ... | OPM/ResInsight | ThirdParty/Ert/python/ecl/util/geometry/cpolyline_collection.py | cpolyline_collection.py | py | 3,556 | python | en | code | 151 | github-code | 90 |
31419253478 |
import torch.nn as nn
import torch
from torchvision import models
device = 'cuda' if torch.cuda.is_available() else 'cpu'
def get_model():
model = models.resnet18(pretrained=True)
for param in model.parameters():
param.requires_grad = False
model.avgpool = nn.AdaptiveAvgPool2d(output_size=(1,1))... | kosicsd12176/Covid-19-Detection | src/Covid_model.py | Covid_model.py | py | 605 | python | en | code | 0 | github-code | 90 |
20563077907 | import os
listofiledict={}
directoryName=""
path=""
def showfiles():
directoryName=input("Enter your directory name with full path")
#print(os.system(('ls %s -l')% directoryName))
listFiles=os.listdir(directoryName)
i=1;
for f in listFiles:
path=directoryName + "/" + f
#print(i,os.system(('ls -l %s')% '"'+pat... | tahashinegp/taskautomation | listoffiles.py | listoffiles.py | py | 1,204 | python | en | code | 0 | github-code | 90 |
39848766593 | import os
from setuptools import setup, find_packages
execfile(os.path.join('antbkp', 'version.py'))
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name=PACKAGE,
version=VERSION,
author='Zikzakmedia SL',
author_email='zikzak@zikzakmedia.com',
... | NaN-tic/python-antbkp | setup.py | setup.py | py | 1,264 | python | en | code | 0 | github-code | 90 |
20040811786 | #!/usr/bin/env python3
import sys, json, os, random, subprocess, time
from housepy import config, log, osc, crashdb
from braid import *
# cuefile = sys.argv[1] if len(sys.argv) > 1 else None
# if cuefile is None:
# cuefile = os.path.abspath(input("Cuefile: "))
# log.info("Reading %s" % cuefile)
cuefile = "cues/fi... | brianhouse/videoscore | composition.py | composition.py | py | 3,964 | python | en | code | 0 | github-code | 90 |
40298354359 | import json, requests
from bs4 import BeautifulSoup
from random import randint
api_key = "Your API"
def main():
places = searchPlace()
# Print places name
for i in range(len(places)):
print(f"{i + 1}. {places[i]['name']}")
print()
# Get user's choice
userChoice = getUserNumber(len(places))
... | LittleStar21/Place-Finder | place_finder.py | place_finder.py | py | 2,847 | python | en | code | 0 | github-code | 90 |
24414891672 | # coding=utf-8
from __future__ import division
import numpy as np
def linearBlend(img1, img2, overlap, backgroundColor=None):
'''
Stitch 2 images vertically together.
Smooth the overlap area of both images with a linear fade from img1 to img2
@param img1: numpy.2dArray
@param img2: n... | radjkarl/imgProcessor | imgProcessor/transform/linearBlend.py | linearBlend.py | py | 2,799 | python | en | code | 28 | github-code | 90 |
23999402262 | import time
from datetime import datetime
from datetime import timedelta
from dateutil.relativedelta import *
from mx import DateTime
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import tools, api
import logging
from openerp import SUPERUSER_ID
_logger = logging.getLogger(__na... | OpenAT/cu_hofe | cam_hr_overtime/cam_hr_overtime.py | cam_hr_overtime.py | py | 44,644 | python | en | code | 0 | github-code | 90 |
11684767874 | from rest_framework import serializers
from api.models import Image, ExpirableLink, Thumbnail, ThumbnailSize
class ExpirableLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ExpirableLink
fields = '__all__'
def to_representation(self, instance):
representation = super(... | Arcimiendar/ImageHostingAPI | api/serializers.py | serializers.py | py | 1,608 | python | en | code | 0 | github-code | 90 |
21662801085 | import argparse
import os, sys
import time
import tabulate
import yaml
import torch
import torch.nn.functional as F
import torchvision
import numpy as np
sys.path.append('../../')
from swag import data, models, utils, losses
from swag.posteriors import SWAG
parser = argparse.ArgumentParser(description='SGD/SWA trai... | victor-amblard/bml-project | experiments/swag_regression/eval_multiswag.py | eval_multiswag.py | py | 3,474 | python | en | code | 0 | github-code | 90 |
72555167978 | import glob
import itertools
from datetime import datetime
import os
from os.path import join
import numpy as np
import pandas as pd
import pyarrow as pa
from pyarrow.parquet import ParquetFile
from patbert.data import utils
class BaseCreator():
def __init__(self, config, test=False):
self.config: dict =... | kirilklein/patbert | patbert/data/sequence_creators.py | sequence_creators.py | py | 5,009 | python | en | code | 1 | github-code | 90 |
24242169461 | import sys
import os
import argparse
from PIL import Image, ImageChops
parser = argparse.ArgumentParser(description = "Argument parser")
parser.add_argument("filepath", help = "location of the images to be de-watermarked")
parser.add_argument("-s", "--separate", action='store_true', help = "separate the strip... | Sgordon4/IFunnyBegone | IFunnyBegone.py | IFunnyBegone.py | py | 1,836 | python | en | code | 0 | github-code | 90 |
30442460671 | import psycopg2
import random
conn = psycopg2.connect(database="postgres",
user="kanat",
password="kanat123",
host="localhost",
port="5432")
cur = conn.cursor()
types = {
1: "trousers",
2: "jackets",
3: "three... | getylman/3-4_sem_in_mipt | 4_sem/DB_2023_project/analysis/p_gen.py | p_gen.py | py | 1,692 | python | en | code | 0 | github-code | 90 |
38626680837 | from collections import deque
def sum_numbers(num1, num2):
return num1 + num2
seats = input().split(", ") # ['17K', '20B', '3C', '15D', '31Z', '28F']
seat_matches = []
first_sequence = deque(map(int, input().split(", ")))
second_sequence = deque(map(int, input().split(", ")))
rotations = 0
... | slambeca/SoftUni-Python-Advanced-May-2023 | Final Exams/Stacks and queues/stewards.py | stewards.py | py | 1,195 | python | en | code | 0 | github-code | 90 |
41898976991 | """
This file contains code from dialog_box.ui file with modifications.
When this file is called through the app, it is supplied with the dialog message
and title which is then displayed in the dialog box.
"""
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_dialog(object):
def setupUi(self, dialog, title, la... | ankit27kh/Internshala-Python-Project | final_dialog_box.py | final_dialog_box.py | py | 2,592 | python | en | code | 0 | github-code | 90 |
18165472989 | n = int(input())
A = list(map(int,input().split()))
smallest = A[0]
ans = 0
for x in range(len(A)-1):
if A[x] > A[x+1]:
ans += A[x] - A[x+1]
A[x+1] = A[x]
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p02578/s431009167.py | s431009167.py | py | 178 | python | en | code | 0 | github-code | 90 |
36454546271 | import discord
status_text = None
status_type = None
# Chat managment
async def del_messages(how_many_words_deleting, which_channel):
await which_channel.purge(limit = int(how_many_words_deleting))
# Check if person has certain role
async def check_role(person_roles, desired_role):
for role in p... | smravec/Crown-Bot | Other.py | Other.py | py | 796 | python | en | code | 1 | github-code | 90 |
9754908227 | #!/usr/bin/env python3
# encoding: utf-8
from glob import glob
import argparse
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
import time
import datetime
#Python2/3 compat code for iterating items
try:
dict.iteritems
except AttributeError:
# Python 3
def ite... | widelands/widelands | regression_test.py | regression_test.py | py | 11,980 | python | en | code | 1,844 | github-code | 90 |
40329036575 |
# 我们正常dump一次 所以load一次就好了
# 若dump了两次 则要load两次才能把数据读出来
# pickle模块是python中用来将Python对象序列化和解序列化的一个工具。“pickling”是将Python对象转化为字节流的过程,而“unpickling”是相反的过程(将来自“binary file或bytes-like object”的字节流反转为对象的过程)。
#
# 5种协议
# Protocol version 0 是最原始一种协议,它向后与以前的Python版本兼容。
# Protocol version 1 是一种老的二进制格式,它也兼容以前版本的Python。
# Protocol versi... | gswyhq/hello-world | python某些包用法/序列化python对象——pickle.py | 序列化python对象——pickle.py | py | 3,126 | python | zh | code | 9 | github-code | 90 |
70881504618 | from datetime import datetime, timedelta
from threading import Thread
from time import sleep
from modules.voice import Voice
# Сделать:
# -- реализовать напоминание, которое предложит выключить пекарню
# просто для красоты
if '__main__' != __name__:
print('{0}: активирован'.format(__name__))
cl... | davy1ex/trillian | modules/dream_control.py | dream_control.py | py | 3,114 | python | ru | code | 0 | github-code | 90 |
15835109848 | import tests.env_setup
import pytest
from fastapi.testclient import TestClient
from moto import mock_dynamodb # type: ignore
from datetime import datetime
import os
from dataclasses import dataclass
import boto3 # type: ignore
from config import Config, get_settings, base_config
from main import app
from typing impor... | provena/provena | job-api/tests/test_functionality.py | test_functionality.py | py | 24,898 | python | en | code | 3 | github-code | 90 |
39489396045 | class Ville:
def __init__(self, nom):
self.nom = nom
self.routes = {}
def ajouter_route(self, ville, distance, vitesse):
temps = distance / vitesse
self.routes[ville] = {'distance': distance, 'temps': temps}
class Carte:
def __init__(self):
... | celianlb/data-structure | partie6/4.py | 4.py | py | 1,688 | python | fr | code | 0 | github-code | 90 |
2141925777 | """Class for implementing entropy based error correction"""
from data_models import EntropyModel
from typing import Any
from algo import CorrectionAlgorithm, AlgorithmType
from typing import Union
class EntropyAlgorithm(CorrectionAlgorithm):
"""This Algorithm assumes a known unique structure for data, although se... | YairMZ/NR_Error_Correction | algo/entropy_algorithm.py | entropy_algorithm.py | py | 1,604 | python | en | code | 1 | github-code | 90 |
27094295758 | from spack import *
class PyPybind11(CMakePackage):
"""pybind11 -- Seamless operability between C++11 and Python.
pybind11 is a lightweight header-only library that exposes C++ types in
Python and vice versa, mainly to create Python bindings of existing C++
code. Its goals and syntax are similar to th... | matzke1/spack | var/spack/repos/builtin/packages/py-pybind11/package.py | package.py | py | 2,005 | python | en | code | 2 | github-code | 90 |
8970732726 | import csv
from amaascore.assets.interface import AssetsInterface
from amaascore.parties.interface import PartiesInterface
from amaascore.books.interface import BooksInterface
from amaascore.corporate_actions.interface import CorporateActionsInterface
from amaascore.market_data.interface import MarketDataInterface
fro... | amaas-fintech/amaas-core-sdk-python | amaascore/csv_upload/utils.py | utils.py | py | 4,054 | python | en | code | 0 | github-code | 90 |
18533881939 | N = int(input())
A = [int(input()) for _ in range(N)]
cnt = 0
if(A[0] != 0):
cnt = -1
else:
cur = A[0]
for i in range(1,N):
if(A[i] - A[i-1] > 1):
cnt = -1
break
elif(A[i] - A[i-1] == 1):
cnt += 1
cur = A[i]
else:
cnt += A[i... | Aasthaengg/IBMdataset | Python_codes/p03347/s970644682.py | s970644682.py | py | 355 | python | en | code | 0 | github-code | 90 |
31729278738 | from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
specialCodes = ["0", "Dziel/0!", "Nierzeczywista!"]
def showDialogBox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Podano nieprawidłową wartość.")
msg.setWindowTitle("Błąd!")
msg.setStandardButtons(QMessageBox.Ok)
... | nicknickeryt/agh_homework | python/A5/utils.py | utils.py | py | 336 | python | uk | code | 0 | github-code | 90 |
18987273365 | import pyodbc
import pandas as pd
import ctypes
import os
import re
# Parâmetros de conexão com o banco de dados SQL Server
server = 'SVRERP,1433'
database = 'PROTHEUS12_R27'
username = 'coognicao'
password = '0705@Abc'
driver = '{ODBC Driver 17 for SQL Server}'
def ler_variavel_ambiente_codigo_desenho():
# Recup... | eliezermoraesss/solidworks-erp-totvs-integration | PYTHON/python-test_005.pyw | python-test_005.pyw | pyw | 5,222 | python | pt | code | 0 | github-code | 90 |
23046806091 | '''
139. Word Break
Medium
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume... | aditya-doshatti/Leetcode | word_break_139.py | word_break_139.py | py | 1,840 | python | en | code | 0 | github-code | 90 |
17007648491 | import sys
import gc
import json
import time as tm
try:
from ompl import util as ou
from ompl import base as ob
from ompl import geometric as og
except ImportError:
# if the ompl module is not in the PYTHONPATH assume it is installed in a
# subdirectory of the parent directory called "py-bindings."
... | josuehfa/System | CoreSystem/OptimalClass.py | OptimalClass.py | py | 28,809 | python | en | code | 3 | github-code | 90 |
651348208 | ##### DNNTrackLengthPredict Tool Script
import numpy
import tensorflow
import random
import sys
import glob
import numpy as np
import pandas #as pd
import tempfile
import csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot #as plt
from array import array
from sklearn import datasets
from sklearn import... | KValantis/ToolAnalysis | UserTools/DNNTrackLengthPredict/DNNTrackLengthPredict.py | DNNTrackLengthPredict.py | py | 10,955 | python | en | code | 0 | github-code | 90 |
32684656373 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers... | ray7yu/asl-recognition | train.py | train.py | py | 4,366 | python | en | code | 0 | github-code | 90 |
10400551188 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 21 09:03:04 2019
@author: admin
"""
'''
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:使用 O(1... | k8godzilla/-Leetcode | 1-100/L186.py | L186.py | py | 2,593 | python | en | code | 0 | github-code | 90 |
15041097089 | """
Pokemon Fight Game by Jocelyn, Anita, Joshua, Junyu, Lily
2022-05-01
"""
# import needed modules for Pokemon Platform
import random
import time
# a class to create Pokemon heros
class Pokemon:
def __init__(self, name, health, level, power, magic, energy):
self.name = name
self.health = heal... | Ethanlinyf/Pokemon-Park | Backup/pokemon_platform.py | pokemon_platform.py | py | 4,908 | python | en | code | 4 | github-code | 90 |
17963265689 | n = int(input())
A = list(map(int, input().split()))
import collections
C = collections.Counter(A)
D = sorted(list(set(A)))[::-1]
t = 0
s = 0
for i in D:
if C[i] >= 4 and t == 0:
print(i ** 2)
s = 1
break
elif C[i] >= 2 and t == 0:
t = i
elif C[i] >= 2 and t != 0:
... | Aasthaengg/IBMdataset | Python_codes/p03625/s039399163.py | s039399163.py | py | 387 | python | en | code | 0 | github-code | 90 |
37358937641 | import sys
sys.stdin, sys.stdout = open('input.txt', 'r'), open('output.txt', 'w')
n = int(input())
h = [int(i) for i in input().split()]
for i in range(n):
ai = 0
if i < n - 1:
mx = max(h[i + 1:])
if h[i] <= mx:
ai = mx - h[i] + 1
print(ai, end=' ')
| sosnovskiim/Informatics | acm/766.py | 766.py | py | 292 | python | en | code | 0 | github-code | 90 |
4949822948 | import sys
def count_cases(n):
cnt3 = 4 # 모서리
cnt2 = (n - 2) * 4 + (n - 1) * 4
cnt1_top = (n - 2) ** 2
cnt1_bottom = (n - 2) * (n - 1) * 4
cnt1 = cnt1_top + cnt1_bottom
return cnt1, cnt2, cnt3
def get_case2(n_dice):
combination_2_not = [5, 4, 3, 2, 1, 0] # set([(0, 5), (1, 3... | sumi-0011/algo | 백준/Gold/1041. 주사위/주사위.py | 주사위.py | py | 1,669 | python | en | code | 0 | github-code | 90 |
3525489465 | import logging
import random
import time
from datetime import datetime
import pymongo
# create logger with 'spam_application'
from pymongo import MongoClient
# from models import scheduler_video, joining_group, connection, via_share
logger = logging.getLogger('application')
logger.setLevel(logging.DEBUG)
# create fi... | azvnit2003/facebook-tools-new | auto_share_v2/utils.py | utils.py | py | 4,641 | python | en | code | 2 | github-code | 90 |
13648852700 | # -*- coding: utf-8 -*-
import scrapy
class Zhongyiyao4Spider(scrapy.Spider):
name = 'zhongyiyao3'
allowed_domains = ['daquan.com']
start_urls = [f'https://www.daquan.com/cyzy/zy{page}.html' for page in range(1,6022)]
def parse(self, response):
name = []
piny = []
other_name =... | srx-2000/traditional_Chinese_medicine | zhongyiyaoSpider/zhongyiyaoSpider/spiders/zhongyiyao3.py | zhongyiyao3.py | py | 1,629 | python | en | code | 69 | github-code | 90 |
2809591848 | # udp server
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((ip, port))
# receive data from client
while True:
data, addr = serversocket.recvfrom(1024)
try :
data = int(data.dec... | 2205794866/GameSecurity | Homework7/src/udpServer.py | udpServer.py | py | 428 | python | en | code | 3 | github-code | 90 |
25301206316 | #
# @lc app=leetcode.cn id=105 lang=python3
#
# [105] 从前序与中序遍历序列构造二叉树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def ... | HughTang/Leetcode-Python | Tencent/105.从前序与中序遍历序列构造二叉树.py | 105.从前序与中序遍历序列构造二叉树.py | py | 929 | python | en | code | 0 | github-code | 90 |
18389582269 | n,m = map(int, input().split())
step = []
now = 0
for i in range(m):
next = int(input()) - 1
step.append(next - now)
now = next + 2
step.append(n-now)
step.sort()
def fibo():
s = []
a = 1
b = 1
s.append(a)
s.append(b)
for i in range(n):
c = a+b
a = b
b = c
s.append(c)
return s
... | Aasthaengg/IBMdataset | Python_codes/p03013/s157913992.py | s157913992.py | py | 432 | python | en | code | 0 | github-code | 90 |
15309561855 | import math
import matplotlib.pyplot as plt
import mcda as circle
import meda as ellipse
import bresenham as line
def entercircle(): #Input function for Circle
xc=int(input("Enter x center coordinate: "))
yc=int(input("Enter y center coordinate: "))
r=int(input("Enter radius of the circle: "))
return xc,yc,r
def ... | cbiswajeet89/Computer-Graphics-Mini-Project | MiniProject/miniproj.py | miniproj.py | py | 8,239 | python | en | code | 0 | github-code | 90 |
18183256579 | H,W,K = map(int,input().split())
array = [ list(input()) for k in range(H)]
ans = 0
for bit_row in range(2**H):
for bit_line in range(2**W):
count = 0
for i in range(H):
for j in range(W):
if ( bit_row >> i ) & 1 == 0 and ( bit_line >> j ) & 1 == 0:
if array[i][j] == '#':
c... | Aasthaengg/IBMdataset | Python_codes/p02614/s514523200.py | s514523200.py | py | 376 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.