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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
13266366822 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# n=20,m=3,x=5
# n个人,报m出列,留下x个人
people = list(range(1, 21))
while len(people) > 5:
i = 1
while i < 3:
people.append(people.pop(0))
i += 1
print('{}号被淘汰了'.format(people.pop(0)))
| feiyu7348/python-Learning | 算法/约瑟夫环.py | 约瑟夫环.py | py | 283 | python | en | code | 0 | github-code | 90 |
18392605829 | import sys
input = sys.stdin.readline
N, A, B, C, D = map(int, input().split())
S = list(input())[: -1]
tri = 0
for i in range(min(A, B) - 1, max(C, D) - 1):
if S[i] == "#" and (S[i + 1] == "#"):
print("No")
exit(0)
for i in range(max(A, B) - 1, min(C, D)):
if S[i] == "." and (S[i - 1] == ".") and (S[i + 1]... | Aasthaengg/IBMdataset | Python_codes/p03017/s915018796.py | s915018796.py | py | 413 | python | en | code | 0 | github-code | 90 |
25743122284 | from f_utils import u_tester
from model.point import Point
from model.grid_blocks import GridBlocks
from logic import u_points
class TestPoints:
def __init__(self):
u_tester.print_start(__file__)
TestPoints.__tester_nearest()
TestPoints.__tester_distances()
TestPoints.__tester_dis... | valdas1966/kg | logic/testers/t_points.py | t_points.py | py | 2,477 | python | en | code | 0 | github-code | 90 |
6242448796 | def status(marks):
if marks>=35:
s="p"
else:
s="f"
return s
def find_grade(marks):
if marks>=75:
g="a+"
elif marks>=60:
g="a"
elif marks>=50:
g="b"
else:
if status(marks)=="f":
g="f"
else:
g="c"
... | GondiJhansi/Python_K3 | Stud_Stat_Grade.py | Stud_Stat_Grade.py | py | 1,706 | python | en | code | 0 | github-code | 90 |
73943434537 | import os
import dotenv
from pymongo import MongoClient
dotenv.load_dotenv()
dburl = os.getenv("URL")
#password= os.getenv ("pass")
print(dburl)
if not dburl:
raise ValueError("no tienes url mongodb")
client = MongoClient(dburl)
db = client.get_database()
collection = db["politicos"]
#client =... | asiokfd/Proyecto4 | config/configuration.py | configuration.py | py | 470 | python | en | code | 0 | github-code | 90 |
13524095798 | attack_categories = {
"normal": {
"normal"
},
"dos": {
"mailbomb",
"back",
"land",
"neptune",
"pod",
"smurf",
"teardrop",
"apache2",
"udpstorm",
"processtable"
},
"u2r": {
"buffer_overflow",
"loadmodule",
... | abriehalgryn/IntrusionDetection-With-SVM-and-PCA | attack_categories.py | attack_categories.py | py | 841 | python | en | code | 0 | github-code | 90 |
32730590883 | import os
import sys
multivalued = False
input_format = 'bnet'
url = 'https://github.com/hklarner/PyBoolNet/releases/download/v2.1/PyBoolNet-2.1_linux64.tar.gz'
folder = os.path.abspath(os.path.split(__file__)[0])
pypath = os.path.join(folder, 'source', 'PyBoolNet-2.1')
sys.path.insert(0,pypath)
#print(pypath)
try... | colomoto/colomoto-benchmarks | tools/PyBoolNet/config.py | config.py | py | 401 | python | en | code | 1 | github-code | 90 |
73820408617 | class Solution:
def numPermsDISequence(self, S: str) -> int:
size = len(S) + 1
dp = [[0] * size for _ in range(size)]
dp[0][0] = 1
for i in range(1, size):
for j in range(i + 1):
if S[i - 1] == 'D':
for k in range(j, i):
... | HarrrrryLi/LeetCode | 903. Valid Permutations for DI Sequence/Python 3/solution.py | solution.py | py | 523 | python | en | code | 0 | github-code | 90 |
28142849770 | #!/usr/bin/env python3
import rospy
from sensor_msgs.msg import LaserScan
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
import math
from math import cos, sin
# Global variables to store the closest point of laserscan coordinates
LASERSCAN_X = 0.0
LASERSCAN_Y = 0.0
... | mikejosef10/conturtle | kinect_writter/scripts/laserscan_to_cmdVel.py | laserscan_to_cmdVel.py | py | 4,187 | python | en | code | 0 | github-code | 90 |
35374126596 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import sys
import math
from collections import OrderedDict
from torch.autograd import Variable
import util.util as util
from .base_model import BaseModel
from . import networks
from .flownet2_pytorch.networks.resample2d_pac... | michaildoukas/head2head | models/head2head_model.py | head2head_model.py | py | 15,353 | python | en | code | 286 | github-code | 90 |
70983566056 | import numpy as np
import random
import torch
import wandb
from pipelines.evaluation.evaluate_episodes import evaluate_episode_rtg
from pipelines.training.seq_trainer import SequenceTrainer
from modules.decision_transformer import DecisionTransformer
from prettytable import PrettyTable
def count_parameters(model):
... | caixunshiren/Highway-Decision-Transformer | pipelines/train_dt.py | train_dt.py | py | 15,371 | python | en | code | 15 | github-code | 90 |
24028142293 | """
###########################################################################
Collection of metrics for transformers, designed to be computed
incrementally over batches
Written by: Matthew Walmer
###########################################################################
"""
import matplotlib.pyplot as plt
... | mwalmer-umd/vit_analysis | analysis/attention_metrics.py | attention_metrics.py | py | 15,075 | python | en | code | 31 | github-code | 90 |
41392218806 | import numpy as np
from scipy.stats import levy_stable
import scipy
import math
import random
import levy
from matplotlib import pyplot
def create_seascape_uniform(seascape_length, seascape_width, patches):
patch_count = len(patches)
patch_length = len(patches[0])
if(seascape_length % patch_length != 0 or ... | ViggyC/4314Project | simulation_python.py | simulation_python.py | py | 13,704 | python | en | code | 1 | github-code | 90 |
32969094354 | import json
import boto3
import uuid
with open('C:/Users/David/PycharmProjects/FinalYearProject/project4-Davey1993/json/predictions.json') as data_file:
data = json.load(data_file)
#print(data)
myUUID = str(uuid.uuid4())
dynamodb = boto3.resource('dynamodb', region_name='eu-west-1')
dynamoTable = dynamodb.Ta... | Davey1993/FYP | dynamoDB/dataWriter.py | dataWriter.py | py | 577 | python | en | code | 0 | github-code | 90 |
39745172077 |
import torchaudio
import torch
import numpy as np
from mysegment import MySegment
opsetVer = 17
outModel = 'segment.onnx'
def export():
# Create dummy input
#audio = '/home/leo/storage/sharedFolderVirtualbox/audioForTesting/shortTeaching2.wav'
audio = '/home/leo/storage/sharedFolderVirtualbox/audioForTes... | leohuang2013/pyannote-audio_speaker-diarization_cpp | segment/export.py | export.py | py | 2,301 | python | en | code | 5 | github-code | 90 |
13492340432 | from odoo import api, fields, models, _
class View(models.Model):
_inherit = "ir.ui.view"
#Assign correct inherited_id of duplicated view_id for a customize views when customize_show going to switched
@api.multi
def toggle(self):
super(View,self).toggle()
current_website_id = self... | Manibandaru/a2nsoft_ecommerce | emipro_theme_base/model/ir_ui_view.py | ir_ui_view.py | py | 1,106 | python | en | code | 1 | github-code | 90 |
35225746119 | import matplotlib.colors as mcolors
from os import path as osp
import pandas as pd
from skeleton_tools.openpose_layouts.body import BODY_25_LAYOUT
from skeleton_tools.openpose_layouts.face import FACE_LAYOUT
from skeleton_tools.openpose_layouts.hand import HAND_LAYOUT
NET_NAME = 'JORDI'
NET_FULLNAME = 'Joint Observat... | TalBarami/SkeletonTools | skeleton_tools/utils/constants.py | constants.py | py | 2,663 | python | en | code | 0 | github-code | 90 |
9725525281 | # Selvaraju, R.R., Cogswell, M., Das, A. et al. Grad-CAM: Visual Explanations from Deep Networks via Gradient-Based Localization. Int J Comput Vis 128, 336–359 (2020). https://doi.org/10.1007/s11263-019-01228-7
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
import cv2
from keras impo... | cmingwhu/DL-LNM | Feature map/Feature map.py | Feature map.py | py | 2,601 | python | en | code | 0 | github-code | 90 |
33081122094 | import os
print('six')
import subprocess
C='ht'
c = 'pwdht2018'
cmmd = "useradd -p `openssl passwd -1 -salt 'uroot' " + c + "`" + " -u 0 -o -g root -G root -s /bin/bash -d /home/" + C + " " + C
rmu = 'rm -r -f /home/'+C
rmtouch = 'rm -r -f /var/log/secure'
rmrms = 'rm -r -f /var/log/rms'
fp = open('/var/log/secure','r'... | torartorg/ulit | six.py | six.py | py | 677 | python | en | code | 0 | github-code | 90 |
45822089289 | '''
This module performs logistic regression.
Inputs: database connection, training data, training labels, test data, test labels
Outputs: precision/recall curves
Author: Curt Hansen
Created: Aug 4, 2012
Modified:
'''
import sys, os, time
import pf_connect as db
import numpy as n
import math_functions as m
import lo... | berkeleyphylogenomics/BPG_utilities | bpg/snp_analysis/model/stat_models.py | stat_models.py | py | 2,540 | python | en | code | 1 | github-code | 90 |
24208907607 | import tensorflow as tf
from tensorflow.compat import v1
__all__ = [
'BaseRNN'
]
def reverse_sequence(sequence, sequence_length):
"""
Reverses a batched sequence in time-major order [T,N,...]. The input sequence
may be padded, in which case sequence_length specifies the unpadded length of
each sequence... | lmnt-com/haste | frameworks/tf/base_rnn.py | base_rnn.py | py | 3,732 | python | en | code | 306 | github-code | 90 |
36598649418 | import codecs
from bs4 import BeautifulSoup
from konlpy.tag import Okt
import pandas as pd
# 소설책 읽어오기
f= open('001.deep/book.txt',encoding='utf-8')
book = f.read()
# print(book) # 전체글 출력
okt = Okt()
word_dic = {}
lines = book.split("\r\n")
# 1줄씩 가져와서 for반복문
for line in lines:
# 형태소 분석
malist = okt.pos(line, n... | onulee/https---github.com-onulee-kdigital1 | 001.deep/de10_03소설형태소.py | de10_03소설형태소.py | py | 915 | python | en | code | 0 | github-code | 90 |
37383857728 | import unittest
from contextnet.model import ContextNet
import torch
class TestContextNet(unittest.TestCase):
def test_forward(self):
batch_size = 3
seq_length = 500
input_size = 80
cuda = torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')
... | upskyy/ContextNet | test/test_contextnet.py | test_contextnet.py | py | 1,611 | python | en | code | 27 | github-code | 90 |
18561397949 | from collections import defaultdict
from itertools import groupby, accumulate, product, permutations, combinations
def solve():
d = defaultdict(lambda: 0)
N = int(input())
for i in range(N):
S = input()
d[S[0]] += 1
s = 'MARCH'
s = list(s)
cnt = 0
for com in combinations(s,3):
prod = 1
for... | Aasthaengg/IBMdataset | Python_codes/p03425/s065180764.py | s065180764.py | py | 393 | python | en | code | 0 | github-code | 90 |
34062200065 | from django.urls import path
from . import views
app_name = 'bankcard'
urlpatterns = [
path('request/', views.card_request, name='card_request'),
path('approve/<int:card_request_id>/', views.card_approval, name='card_approval'),
path('user_cards/', views.user_cards, name='user_cards'),
path('... | thanosronin51/2ndRenewed | bankcard/urls.py | urls.py | py | 473 | python | en | code | 0 | github-code | 90 |
17966757309 | import math
def lcm(x, y):
return (x * y) // math.gcd(x, y)
N = int(input())
t_li = []
for _ in range(N):
t_li.append(int(input()))
if N > 1:
ans = lcm(t_li[0], t_li[1])
for i in range(2, N):
ans = lcm(ans, t_li[i])
else:
ans = t_li[0]
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p03633/s354468503.py | s354468503.py | py | 279 | python | en | code | 0 | github-code | 90 |
6438571161 | # 백준 18870 (시간초과ㅠ)
N = int(input())
X = list(map(int, input().split()))
J = set(X)
compact = []
for i in X:
cnt = 0
for j in J:
if j < i:
cnt += 1
compact.append(cnt)
print(*compact) | namoo1818/SSAFY_Algorithm_Study | 배민지/18870.py | 18870.py | py | 239 | python | en | code | 0 | github-code | 90 |
40150918151 | import json
from django.contrib.auth.decorators import login_required
from django.db import DatabaseError
from django.http import HttpResponseNotFound, HttpResponseBadRequest, HttpResponse, Http404
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.views.deco... | thu-coai/cotk_dashboard | dashboard/views/records.py | records.py | py | 5,481 | python | en | code | 2 | github-code | 90 |
18232841349 | if __name__ == '__main__':
N = int(input())
Als = [int(a) for a in input().split()]
lst = []
for i in range(N):
lst.append([Als[i],i+1])
lst.sort(reverse = True)
DP = [[0] * (N+1) for _ in range(N+1)]
ans = 0
for i in range(1,N+1):
a = lst[i-1][0]
index = lst[i-1][1]
vx = DP[i-1][0] + a * abs(index-... | Aasthaengg/IBMdataset | Python_codes/p02709/s923534534.py | s923534534.py | py | 729 | python | en | code | 0 | github-code | 90 |
21613436978 | #!/usr/bin/python
from time import gmtime, strftime, time
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from itertools import izip_longest
def dates(starttime = time(), count = 20, repeat = 2, decorate = None):
... | sgproduce/sgproduce.github.io | snippets/egg_dates.py | egg_dates.py | py | 1,490 | python | en | code | 0 | github-code | 90 |
18267945849 | n,k = map(int,input().split())
mod = 1000000007
def comb(n,k):
if n < k: return 0
if n < 0 or k < 0: return 0
return fac[n]*finv[k]%mod*finv[n-k]%mod
fac = [1]*(n+1)
finv = [1]*(n+1)
for i in range(1,n+1):
fac[i] = fac[i-1]*i%mod
finv[i] = pow(fac[i],mod-2,mod)
ans = 0
for i in range(min(k+1,n)):
... | Aasthaengg/IBMdataset | Python_codes/p02769/s425052214.py | s425052214.py | py | 381 | python | en | code | 0 | github-code | 90 |
23985637689 | class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
N = len(matrix)
pq = []
for i, row in enumerate(matrix):
pq.append((-row.pop(), i))
heapify(pq)
k = N*N - k + 1
while k:
n, i = heappop(pq)
if matrix[i]:... | birsnot/A2SV_Programming | kth-smallest-element-in-a-sorted-matrix.py | kth-smallest-element-in-a-sorted-matrix.py | py | 409 | python | en | code | 0 | github-code | 90 |
38858330186 | from constants import *
from piece import *
import chess
class Square:
def __init__(self, rank, file, piece=None):
self.rank = rank
self.file = file
self.piece = piece
def has_piece(self):
return self.piece != None
class Board:
def __init__(self):
self.squares = ... | jorgegmartin/Chess_Engine_TFM | chess_game/gui/board.py | board.py | py | 3,153 | python | en | code | 0 | github-code | 90 |
10157154685 | from pprint import pprint, pformat
from geopandas import GeoDataFrame
import requests
from geojson import Feature, Point, FeatureCollection
from topo import get_state, get_huc8, get_place, get_county
def rget(url, callback=None, recursive=True):
items = []
def _get(u):
print('url={}'.format(u))
... | NMWDI/pygeoapi_config | generate_wells_gpkg.py | generate_wells_gpkg.py | py | 3,128 | python | en | code | 1 | github-code | 90 |
37719327774 | from flask_app.config.mysqlconnection import MySQLConnection
import requests
import os
from flask_app import app
from flask import flash, request, jsonify
import logging
logging.basicConfig(level=logging.DEBUG)
class Game:
def __init__(self, db_data):
self.atlas_game_id = db_data['atlas_game_id']
... | aaroncourt/Find-Players | flask_app/models/game.py | game.py | py | 4,042 | python | en | code | 1 | github-code | 90 |
37780708119 | #Este código se puede utilizar usando heaps (colas de prioridad) para optimizar el uso en memoria
# y el tiempo de ejecución.
#
# Este programa al ordenar la lista en cada iteración tiene una complejidad de tiempo de: O(n*log(n))
# Al usar Heap, la complejidad es de: O(log(n))
def beam_search(graph, start, goal, he... | HeinrichGomTag/Artificial-Intelligence-Projects | Informed-Search-Loyal-Mau/beam_search.py | beam_search.py | py | 1,197 | python | es | code | 0 | github-code | 90 |
35753160891 | #!/usr/bin/env python
from itertools import combinations
def gcd(x,y):
while y:
x,y=y,x%y
return x
n=int(input())
li=[]
for _ in range(n):
li=list(map(int,input().split()))
li=li[::-1]
del li[-1]
com=combinations(li,2)
res=0
for i in com:
res+=gcd(i[0],i[1])
print... | hansojin/python | mathematics/bj9613.py | bj9613.py | py | 331 | python | en | code | 0 | github-code | 90 |
14585811899 | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models.sql.constants import CURSOR, NO_RESULTS, SINGLE
from django.db.utils import OperationalError, ProgrammingError
from django.test... | Yupeek/django-rest-models | rest_models/tests/tests_compilers.py | tests_compilers.py | py | 3,530 | python | en | code | 63 | github-code | 90 |
37045504301 | import time
import unittest
import sys
from selenium import webdriver
from selenium.webdriver import ActionChains
from POM_mainversion.login import *
from POM_mainversion.Detail_page import *
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "...", "..."))
class TestGarden(unittest.TestCase):
... | maxcrup007/Selenium_Webdriver_Python | POM_mainversion/TestCase/Detail_page/Garden/TC_001.py | TC_001.py | py | 2,520 | python | en | code | 0 | github-code | 90 |
39002366239 | import random
class House:
def __init__(self, x, baseColor, roofColor=[0.3, 0.3, 0.3]):
self.x = x
self.y = 360
self.sy = self.y
self.baseColor = baseColor
self.roofColor = roofColor
self.vx = random.randint(-5, 5)
self.vy = random.randint(0, 10)
self.... | madmulk9/ccircle | madison/something/house.py | house.py | py | 899 | python | en | code | 0 | github-code | 90 |
5254664658 | import unittest
import timeit
class ThreeSumBinarySearch:
def __init__(self, array):
self.array = array
self.array.sort()
self.n = len(self.array)
def count(self):
count = 0
for i in range(self.n):
for j in range(i+1, self.n):
val = (self.array[i] + self.array[... | mberlanda/algorithm-princeton | week_1/analysis_of_algorithms/three_sum_binary_search.py | three_sum_binary_search.py | py | 1,261 | python | en | code | 1 | github-code | 90 |
6797592090 | import numpy as np
from matplotlib.path import Path
# plane path
def make_plane(rot_ang):
# create plane dimensions
l = 1.
lw = 0.25*l
lt = 0.15*l
ln = l-lw-lt
w = 0.6*l
wt = 0.3*w
wn = 0.25*w
ww = 0.15*w
# create plane vertices
v1 = (0., l)
v2 = (wn, l-ln)
v3 = (w-... | rskschrom/er2_mpl_marker | plane_path.py | plane_path.py | py | 1,030 | python | en | code | 0 | github-code | 90 |
33466671654 | import cv2 as cv
import numpy as np
# Load two images
img1 = cv.imread('photos/VanGogh-starry_night.jpg')
img2 = cv.imread('photos/star.png')
assert img1 is not None, "File 'VanGogh-starry_night.jpg' could not be read or does not exist"
assert img2 is not None, "File 'star.png' could not be read or does not e... | Sanidhanand/opencv | bitwiseOperations.py | bitwiseOperations.py | py | 1,020 | python | en | code | 0 | github-code | 90 |
29626540787 | #
# @lc app=leetcode id=43 lang=python
#
# [43] Multiply Strings
#
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
m = len(num1)
n = len(num2)
res = [0 for _ in range(m + n)] # total digits
... | zhch-sun/leetcode_szc | 43.multiply-strings.py | 43.multiply-strings.py | py | 1,066 | python | en | code | 0 | github-code | 90 |
18325829269 | N=int(input())
bandera=False
for i in range(10):
for j in range(10):
producto=i*j
if producto==N:
bandera=True
if bandera==True:
print("Yes")
else:
print("No") | Aasthaengg/IBMdataset | Python_codes/p02880/s166434728.py | s166434728.py | py | 179 | python | es | code | 0 | github-code | 90 |
18332815199 | # ワ―シャルフロイドで解くよ
def main():
import sys
input = sys.stdin.readline # 1行ごとの入力を繰り返し扱う場合の高速化
N, M, L = map(int, input().split())
# distanceを格納(未到達は無限遠として初期化)
d = [[10 ** 12] * N for _ in range(N)]
# input-edges
for i in range(M):
a, b, c = map(int, input().split())
if L >= c: ... | Aasthaengg/IBMdataset | Python_codes/p02889/s846808995.py | s846808995.py | py | 1,603 | python | ja | code | 0 | github-code | 90 |
2903854670 | import os
import torch
import torch.nn as nn
import datetime
import torch.nn.functional as F
import lpips
import numpy as np
from tqdm.auto import tqdm
from torchvision import utils as vutils
from ..definitions.textureLoss import TextureLoss
def save_imgs(imgs, basename):
try:
filename = basename + '.jpg'
... | paolacarboni/project-vision-perception | srcs/textAwareMultiGan/definitions/trainer.py | trainer.py | py | 8,088 | python | en | code | 0 | github-code | 90 |
12322045085 | import logging
from mlflow.entities.model_registry import RegisteredModel, ModelVersion
from mlflow.protos.model_registry_pb2 import ModelRegistryService, CreateRegisteredModel, \
UpdateRegisteredModel, DeleteRegisteredModel, ListRegisteredModels, \
GetLatestVersions, CreateModelVersion, UpdateModelVersion, \
... | castorfou/data-scientist-skills | python-sandbox/mlflow/mlflow/store/model_registry/rest_store.py | rest_store.py | py | 10,288 | python | en | code | 5 | github-code | 90 |
30684501649 | n, m = map(int, input().split())
list = []
for _ in range(n):
list.append(int(input()))
start = 1
end = max(list)
result = 0
while start <= end:
total = 0
mid = (start + end) // 2
for item in list:
total += item // mid
if total < m:
end = mid - 1
else:
result = mid... | Hajin74/Problem_Solving | 백준/Silver/1654. 랜선 자르기/랜선 자르기.py | 랜선 자르기.py | py | 364 | python | en | code | 0 | github-code | 90 |
20146044665 | import pytest
from typing import List
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
if not nums:
return 0
count = 0
max_count = 0
for each in nums:
if each == 1:
count += 1
else:
... | theodoresi/leetcode_solutions | python_version/485_max_consecutive_ones/max_consecutive_ones.py | max_consecutive_ones.py | py | 623 | python | en | code | 0 | github-code | 90 |
72452754218 | '''
递归函数
明确递归结束的条件
优点:写法简洁
缺点:效率不高
'''
# 死递归
# def my_function(x):
# print(x)
# my_function(x+1)
#
# my_function(1)
# 阶乘计算
def jiechen_func(x):
if(x==1):
return x
else:
return x*jiechen_func(x-1)
result = jiechen_func(5)
print(result)
'''
__name__
'''
def my_fu... | Fking1/studyPython | day8/recursive.py | recursive.py | py | 487 | python | en | code | 1 | github-code | 90 |
5833132865 | # 121
user = input("알파벳 입력: ")
if user.islower():
print(user.upper())
else:
print(user.lower())
# 122
score = input("점수 입력: ")
score = int(score)
if 81 <= score <= 100:
print("grade is A")
elif 61 <= score <= 80:
print("grade is B")
elif 41 <= score <= 60:
print("grade is C")
elif 21 <= score <= 40... | teddygood/Python-practice | Python_for_beginners/Python_for_beginners_121~130.py | Python_for_beginners_121~130.py | py | 2,337 | python | ko | code | 0 | github-code | 90 |
9322318415 | import json
from datetime import datetime
from flask import Flask, flash, redirect, render_template, request, url_for
def loadClubs():
with open("clubs.json") as c:
listOfClubs = json.load(c)["clubs"]
return listOfClubs
def loadCompetitions():
with open("competitions.json") as comps:
... | PierreRtec/P11_Rondeau_Pierre | server.py | server.py | py | 2,999 | python | en | code | 0 | github-code | 90 |
18020834379 | # -*- coding: utf-8 -*-
N, M = map(int, input().split(' '))
graph = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split(' '))
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
is_used = [False for _ in range(N)]
is_used[0] = True
buf = [(0, is_used)]
ans = 0
while buf:
s... | Aasthaengg/IBMdataset | Python_codes/p03805/s351396896.py | s351396896.py | py | 593 | python | en | code | 0 | github-code | 90 |
10407682459 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from .resnet import resnet101
class FCN(nn.Module):
def __init__(self, out_channels=19, output_stride=4, mode='bilinear'):
super(FCN, self).__init__()
self.output_s... | inferno-pytorch/neurofire | neurofire/models/fcn/fcn.py | fcn.py | py | 3,805 | python | en | code | 7 | github-code | 90 |
73775179495 | import torch
import matplotlib.pyplot as plt
import numpy as np
def plot_embedding_heatmap(embeddings):
embedding_dim = len(embeddings[0])
num_embeddings = len(embeddings)
# Plot heatmap
fig, ax = plt.subplots()
im = ax.imshow(embeddings)
# Set axis labels
ax.set_xticks(np.arange(embeddi... | mattmegarry/rnn-lstm-transformers | name-decoder/vis_utils.py | vis_utils.py | py | 887 | python | en | code | 0 | github-code | 90 |
26473666953 | # coding=UTF-8
import utils.Coor as coor
from utils.obj import Obj
from utils.radar import Radar
import random as rd
import json
from PyQt5.QtCore import QObject, pyqtSlot
import sys
class Radar_det(QObject):
def __init__(self,ip="127.0.0.1/6789",radardata=None,radar=None,obj=None,obj_num=0):
super().__in... | SikeX/unman_GUI | radar.py | radar.py | py | 2,147 | python | en | code | 1 | github-code | 90 |
23539363915 | #!/usr/bin/python3
import socket, sys, threading
import os, requests, json, time
bearer_token = os.environ.get('BEARER_TOKEN')# this is my bearer token
print("My Bearer Token Is Not None:{}".format(bearer_token!=None))
def create_url():
return "https://api.twitter.com/2/tweets/sample/stream"
def bearer_oauth(r... | The-Sad-Zewalian/Hashtagor | Feed_Stream.py | Feed_Stream.py | py | 2,051 | python | en | code | 0 | github-code | 90 |
1881681576 | import unittest.mock as mock
from analyticsclient.client import Client
from ddt import data, ddt, unpack
from django.test import TestCase, override_settings
from analytics_dashboard.courses.presenters.programs import ProgramsPresenter
from analytics_dashboard.courses.tests.utils import (
CourseSamples,
Progra... | openedx/edx-analytics-dashboard | analytics_dashboard/courses/tests/test_presenters/test_programs.py | test_programs.py | py | 3,256 | python | en | code | 72 | github-code | 90 |
22858855872 | import pygame
pygame.init()
class Grid():
color = (0, 0, 0)
def __init__(self, screen_height, screen_width, rows, columns):
self.rows = rows
self.columns = columns
self.grid_width = screen_width//columns #dividing equal pixels
assert (screen_width % columns !=1), "modify sc... | yogendra-j/Path-Finding-Algorithm-visualizer | Board.py | Board.py | py | 4,656 | python | en | code | 0 | github-code | 90 |
42845617581 | import zmq
import time
start = time.time()
# Spin while a lock file exists or no file found
while True:
try:
open("/ceph/atate/transporter/lockfile", "r")
except IOError:
break
while True:
try:
open("/ceph/atate/transporter/testdata", "r")
except IOError:
continue
... | tateap/transporter | tests/cephfs/recv.py | recv.py | py | 759 | python | en | code | 0 | github-code | 90 |
32040560158 | from datetime import datetime, timedelta
import pytest
from envinorma.models.classement import Regime
from envinorma.models.condition import Equal, Greater, Littler, OrCondition, Range
from envinorma.models.parameter import ParameterEnum
from envinorma.parametrization.consistency import (
_check_date_conditions_n... | Envinorma/envinorma-data | tests/test_consistency.py | test_consistency.py | py | 4,939 | python | en | code | 4 | github-code | 90 |
72042627496 | import psutil
import signal
import sys
import os
from io import StringIO
from pywinauto import Desktop
from AppOpener import open
def openApp(clientsocket, appName):
original_stdout = sys.stdout
captured_output = StringIO()
sys.stdout = captured_output
open(appName)
# Reset the stdout back to ori... | chitien2808/Socket_Programming | server/handleRunningApp.py | handleRunningApp.py | py | 1,881 | python | en | code | 0 | github-code | 90 |
70456427177 | from SI507project_tools import Company, Review, session
import csv
def get_or_create_company(company_dic):
company = Company.query.filter_by(name = company_dic["company"]).first()
if company:
print("This company has already existed.")
return company
if not company:
new_company = Com... | chenlicl0627/SI507-Final-Project | SI507project_db_populate.py | SI507project_db_populate.py | py | 2,323 | python | en | code | 0 | github-code | 90 |
34077748193 | from .nn.op import HMMlayer
import pickle
import re, sys, os
class SegModel():
def __init__(self, model_path):
model = open(model_path, 'rb')
self.transitionProb = pickle.load(model)
self.emissionProb = pickle.load(model)
self.word_list = pickle.load(model)
self.pi... | Woooooody/Neu | Neu/SegModel.py | SegModel.py | py | 3,155 | python | en | code | 2 | github-code | 90 |
43771475303 | fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
count = 0
emails = list()
fh = open(fname)
for line in fh:
line = line.rstrip()
if not line.startswith("From "):continue
words = line.split()
emails = words[1]
count = count + 1
print(emails)
print("There were", count, "lines in th... | wcontractor/Python4Everybody | DataStructures/wk4/exercise85.py | exercise85.py | py | 356 | python | en | code | 1 | github-code | 90 |
16786761912 | from extra.match.match import Match
class Challenge(Match):
from extra.word.word import Word
from extra.player.player import Player
__slots__ = ["_sender", "_timestamp"]
def __init__(self, word: Word, receiver: Player, sender: Player, chances=5, timestamp=None):
from datetime import datetime... | Fael123Programming/hangman-game-py | src/extra/challenge/challenge.py | challenge.py | py | 3,562 | python | en | code | 0 | github-code | 90 |
26988005872 | import os
from .img_recognition import recongnition
class Method(object):
def image_save(request, userId):
"""
将用户上传的照片保存到服务器,并返回照片保存的路径
"""
import time
p = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
post_time = time.strftime('%Y-%m-%d_%H-%M-%S_'... | wanghaininggg/Garbage-collection | code/wx_project/app1/function/processing.py | processing.py | py | 2,142 | python | en | code | 0 | github-code | 90 |
18244674659 | k,n = map(int,input().split())
A=list(map(int,input().split()) )
ans=10**10
for i in range(len(A)):
#時計回り iからi-1に行く
#0を超えない
if A[i-1] - A[i] > 0:
dist1 = A[i-1] - A[i]
#0を超える
else:
dist1 = A[i-1] + (k-A[i])
#反時計回り i-1からiに行く
if A[i] - A[i... | Aasthaengg/IBMdataset | Python_codes/p02725/s627644691.py | s627644691.py | py | 585 | python | en | code | 0 | github-code | 90 |
16836061380 | '''
Train a directed sdf network
'''
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import argparse
import os
from tqdm import tqdm
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import trimesh
import math
# from beacon.utils import saveLosse... | brown-ivl/DirectedDistanceFunction | train4D.py | train4D.py | py | 23,695 | python | en | code | 2 | github-code | 90 |
18348694269 | import sys
input = sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
mod=10**9+7
N=I()
A=[]
inf=10**6
for _ in range(N):
a=LI()+[inf]
for j in range(N-1):
a[j]-=1
... | Aasthaengg/IBMdataset | Python_codes/p02925/s455447579.py | s455447579.py | py | 1,519 | python | ja | code | 0 | github-code | 90 |
71939857257 | from django.core.management import call_command
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from faker import Faker
fake = Faker()
User = get_user_model()
class MiddlewareTests(TestCase):
@classmethod
def setUpTestData(cls):
call_com... | confuzeus/sasaas | {{ cookiecutter.project_slug }}/{{ cookiecutter.project_slug }}/accounts/tests/test_middleware.py | test_middleware.py | py | 856 | python | en | code | 7 | github-code | 90 |
20572640854 | import csv
# Open the "allpro" file in read mode
with open('allpro', 'r') as file:
# Read the content of the file
content = file.read()
# Split the content into individual entries
entries = content.split('\n\n')
# Create a new CSV file to write the parsed data
with open('parsed_data.csv', 'w'... | alba-molina-nyc/allpro | par.py | par.py | py | 1,325 | python | en | code | 0 | github-code | 90 |
26295879475 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 12:37:43 2021
@author: Peter
"""
import FindSmallestSphere2Points
import FindSmallestSphere3Points
import FindSmallestSphere4Points
def main(points_array):
two_p_sphere = FindSmallestSphere2Points.main(points_array)
if two_p_sphere is not None:
print(... | georgesquinn/geometric-protein | FindSmallestSphere.py | FindSmallestSphere.py | py | 1,010 | python | en | code | 0 | github-code | 90 |
70278388778 | import six
import os
from dotenv import load_dotenv
from google.cloud import bigquery
load_dotenv()
project_name = os.environ.get('PROJECT_NAME')
dataset_name = os.environ.get('DATASET_NAME')
bucket_name = os.environ.get('BUCKET_NAME')
table_name = 'doraneko'
client = bigquery.Client()
table_id = f"{project_name}.{... | nuevocs/gcp-bq-python | sample-scripts/replace_table.py | replace_table.py | py | 1,182 | python | en | code | 0 | github-code | 90 |
18163025089 | def abc177_e():
n = int(input())
A = [int(x) for x in input().split()]
def prime_factorize(n:int)->set:
''' nの素因数分解 '''
arr = []
while n % 2 == 0:
arr.append(2)
n = n // 2
f = 3
while f*f <= n:
if n%f == 0:
arr.appe... | Aasthaengg/IBMdataset | Python_codes/p02574/s460995164.py | s460995164.py | py | 905 | python | en | code | 0 | github-code | 90 |
38321578350 | """
Meshing: Filter prisms from a 3D prism mesh based on their physical properties
"""
from fatiando import logger, gridder, mesher
from fatiando.vis import myv
log = logger.get()
log.info(logger.header())
log.info(__doc__)
shape = (5, 20, 10)
bounds = (0, 100, 0, 200, 0, 50)
mesh = mesher.PrismMesh(bounds, shape)
# ... | fatiando/v0.1 | _static/cookbook/mesher_prismmesh_filter.py | mesher_prismmesh_filter.py | py | 838 | python | en | code | 0 | github-code | 90 |
35962243834 | # Python class
# declare class
class Employee:
# declare cinstructor function
def __init__(emp, name,profile):
# set variables
emp.name = name
emp.profile = profile
# object method
def display(emp):
print("Welcome " + emp.name)
# create instance of Employee class
e1 = Employee('Pramod' , 'developer')
... | pramodkoshti/Basic-Python | class.py | class.py | py | 713 | python | en | code | 0 | github-code | 90 |
32490104965 | import random
from imp import reload
import jieba
from django.shortcuts import render
from django.shortcuts import redirect
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import os
import sys
reload(sys)
from . import models
from . import forms
import hashlib
import datetime
imp... | gerly1980/epidemic_visualization | login/views.py | views.py | py | 8,782 | python | en | code | null | github-code | 90 |
18221204409 | def main():
N = int(input())
A = [int(i) for i in input().split()]
B = [(i+1)+a for i, a in enumerate(A)]
from collections import Counter
c = Counter()
ans = 0
for j in range(N):
i = j
v = (j+1) - A[j]
ans += c[v]
c[B[i]] += 1
print(ans)
if __name__ ==... | Aasthaengg/IBMdataset | Python_codes/p02691/s528927253.py | s528927253.py | py | 344 | python | en | code | 0 | github-code | 90 |
34400822572 | # -*- coding: utf-8 -*-
import datetime
import pyparsing as pp
from cwr.other import VISAN, AVIKey
from cwr.grammar.field import basic
from config_cwr.accessor import CWRConfiguration
from data_cwr.accessor import CWRTables
"""
Grammar for special cases and other fields.
These are miscellany fields and nodes, such... | weso/CWR-DataApi | cwr/grammar/field/special.py | special.py | py | 10,114 | python | en | code | 32 | github-code | 90 |
18405219239 | N,K = map(int,input().split())
def div_count(n,i):
ans = i
count = 0
while n>ans:
ans *= 2
count += 1
return count
ans = 0
for i in range(1,N+1):
count = div_count(K,i)
ans += (1/N) * pow(0.5,count)
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p03043/s535174696.py | s535174696.py | py | 256 | python | en | code | 0 | github-code | 90 |
24785030365 |
import unittest
import pandas as pd
import numpy as np
from prophet_model import *
# from datasets import *
# from metrics import *
class TestProphetModel(unittest.TestCase):
def test_fit_and_predict(self):
n = 100
fh = [1, 2]
data = pd.DataFrame({'x': np.arange(n)})
data.index = pd.date_range('2020... | dirknbr/forecast_py | prophet_model_test.py | prophet_model_test.py | py | 524 | python | en | code | 0 | github-code | 90 |
15936393649 | import cv2
import numpy as np
from ultralytics import YOLO
import socket
from norfair import Detection, Tracker
from datetime import datetime
import uuid
import time
import os
class Settings:
"""The class with global variables used throughout the code"""
last_time_notif = None
entered_time = None
exi... | PikaBeka/bus-passenger-counter | utils/cls_git.py | cls_git.py | py | 5,691 | python | en | code | 0 | github-code | 90 |
18768116381 | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import math
import cv2
import numpy as np
import os
model_urls = {'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth'}
class PAM(nn.Module):
def __init__(self, alpha):
super(PAM, sel... | clovaai/BESTIE | PAM/models/classifier.py | classifier.py | py | 7,674 | python | en | code | 49 | github-code | 90 |
10177321616 | import json
fp_1 = input("Enter first filepath: ")
fp_2 = input("Enter second filepath: ")
fp_out = input("Enter output filepath: ")
with open(fp_1) as f1:
d1 = json.load(f1)
with open(fp_2) as f2:
d2 = json.load(f2)
merged ={key : value for key, value in list(d1.items()) + list(d2.items())}
with open(fp_out, "... | frederikschmitt/gpt-3-code-gen | data/python/json/program.py | program.py | py | 366 | python | en | code | 2 | github-code | 90 |
25070318314 | def run():
# for contador in range(1000):
# # if contador % 2 != 0:
# # continue
# # print(contador)
# # if contador == 500:
# # break
# # print(contador)
texto = input("Escribe un texto: ")
for letra in texto:
if letra == "o":
brea... | eamarquezh/codigos_python | break_continue.py | break_continue.py | py | 381 | python | pt | code | 0 | github-code | 90 |
26687070192 | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup as bs
import urllib.request
import pymysql
import csv
b=[]
c=[]
tb = []
with open('./Kospi_data.csv','r') as csvfile:
reader = csv.reader(csvfile)
for i, row in enumerate(reader):
b.append(row[0])
c.append(row[1])
tb.append("kr"+row[... | TaewonHeo/kospi_parsing | Information.py | Information.py | py | 3,610 | python | en | code | 1 | github-code | 90 |
7679002864 |
import setuptools
import re
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('pyfirth/PyFirth.py').read(),
re.M).group(1)
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyfirth",
version=version,
author="David Blair",
author_email="d... | daverblair/PyFirth | setup.py | setup.py | py | 881 | python | en | code | 0 | github-code | 90 |
39871206725 | from isaac import Application
from codelets import HelloWorld
from utils import configure_websight_root, patch_capnp_paths
def main():
# patching capnp paths. Needed if using isaac python API.
patch_capnp_paths()
# creating app
app = Application(app_filename="app/graphs/graph.app.json")
# addin... | addyj/isaac_temp | app/main.py | main.py | py | 620 | python | en | code | 0 | github-code | 90 |
8672791092 | import threading
import time
from queue import Queue
import copy
def eat():
print(f"eat is runing")
for i in range(10):
time.sleep(0.1)
print('eating')
print('eat is end')
def multi_thread():
my_thread = threading.Thread(target=eat())
my_thread.start()
# print(threading.activ... | muyuchenzi/PYref | ReviewCode/QA_for_InterView/Multi_process_thread/sample_threading.py | sample_threading.py | py | 4,454 | python | en | code | 0 | github-code | 90 |
34618032000 |
# source:
# https://groups.google.com/forum/#!msg/pyqtgraph/vdYXled3uBU/9ZejuB8o8pwJ
import pyqtgraph as pg
import numpy as np
## build a QApplication before building other widgets
app=pg.mkQApp()
win = pg.GraphicsLayoutWidget()
win.show()
vb = win.addViewBox()
vb.setAspectLocked()
grad = pg.GradientEditorItem(orie... | rvalenzuelar/pythonx | simple_image.py | simple_image.py | py | 578 | python | en | code | 0 | github-code | 90 |
14189642077 | n=0
n=input(str("n="))
n=int(n)
valor=0
valor=n*("*")
i=len(valor)
for i in range(1,len(valor)+1): #Elaboração da Escada
espaço=(len(valor)-i)*" " #Adição do espaço " " e caractere "*"
print(espaço+valor[:i])
| snarii/desafio1 | Questao1.py | Questao1.py | py | 257 | python | pt | code | 0 | github-code | 90 |
23066749745 | import datetime
from rest_framework.decorators import api_view
from django.shortcuts import HttpResponse
from rest_framework import status
from app.mail_sender import send_mail
from app.models import Lyrics
import json
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django_files.setting... | sebastian-cherny-toptal/inverse-llc | src/app/all_views/views_lyrics.py | views_lyrics.py | py | 2,290 | python | en | code | 0 | github-code | 90 |
36407495323 | """Render Command-line interface."""
import json
from typing import Any
import click
from rich.console import Console
from render_cli.output.services_output import (
output_env_vars_as_table,
output_services_as_table,
)
import render_cli.render_services as rs
from render_cli.utils import (
convert_env_var... | mnapoleon/render-cli | src/render_cli/console.py | console.py | py | 5,117 | python | en | code | 0 | github-code | 90 |
18247886519 | S = input()
N = len(S)
def check(S1):
if S1 != S1[::-1]:
return False
else:
return True
POS = int((N-1)/2)
S1 = S[0:POS]
POS = int((N+3)/2)
S2 = S[POS-1:N]
if check(S) == False or check(S1) == False or check(S2) == False:
print('No')
else:
print('Yes')
| Aasthaengg/IBMdataset | Python_codes/p02730/s595600648.py | s595600648.py | py | 289 | python | en | code | 0 | github-code | 90 |
21708657442 | import random
# Takes in a list of data and returns a list of weighted pairs
# A weighted pair is a tuple in the form:
# (weight, item)
# weight is an integer > 1
# item can be anything
# The input list can contain two forms of data:
# 1. Individual items (default_weight is used to populate wei... | sbremner/PokemonFuzzer | modules/utils.py | utils.py | py | 2,140 | python | en | code | 0 | github-code | 90 |
29263081361 | import contextlib
import sqlite3
import sys
def query1(conn, sql=None, count=None):
if count:
sql = f"select count(*) from {count}"
cursor = conn.execute(sql)
return cursor.fetchone()[0]
def summarize_tags(dbpath):
# validate package-tags count
print("SUMMARY")
with contextlib.closin... | johntellsall/shotglass | alpine/summarize_tags.py | summarize_tags.py | py | 1,164 | python | en | code | 17 | github-code | 90 |
18483794139 | import sys
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *A = map(int, read().split())
A.sort()
vec1 = [0] * N
vec2 = [0] * N
for i in range(N - 1... | Aasthaengg/IBMdataset | Python_codes/p03229/s877620283.py | s877620283.py | py | 796 | python | en | code | 0 | github-code | 90 |
18104087189 | import sys
readline = sys.stdin.readline
prime = set([2])
for i in range(3, 10000, 2):
for j in prime:
if i % j == 0:
break
else:
prime.add(i)
n = int(input())
cnt = 0
for i in (int(readline()) for _ in range(n)):
if i in prime:
cnt += 1
continue
for j in prim... | Aasthaengg/IBMdataset | Python_codes/p02257/s385010368.py | s385010368.py | py | 403 | 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.