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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18335497129 | N = int(input())
A = list(map(int, input().split()))
dct = dict(enumerate(A))
ad = sorted(dct.items(), key=lambda x:x[1])
ans = []
for i in ad:
j = i[0] + 1
ans.append(j)
a = map(str, ans)
b = ' '.join(a)
print(b) | Aasthaengg/IBMdataset | Python_codes/p02899/s145751975.py | s145751975.py | py | 221 | python | en | code | 0 | github-code | 90 |
34562093604 | import numpy as np
import unittest
from caffe2.python import core, workspace, muji, test_util
@unittest.skipIf(not workspace.has_gpu_support, "no gpu")
class TestMuji(test_util.TestCase):
def RunningAllreduceWithGPUs(self, gpu_ids, allreduce_function):
"""A base function to test different scenarios."""
... | facebookarchive/AICamera-Style-Transfer | app/src/main/cpp/caffe2/python/muji_test.py | muji_test.py | py | 2,632 | python | en | code | 81 | github-code | 90 |
4663994456 | from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import os
from_email = os.getenv('sg_from_email')
gift_template_id = "d-4158ee9a983f496cbd4bff994f818192"
purchase_template_id = "d-a7cd129a71744a30ac219698fb4a6ae9"
sg = SendGridAPIClient(os.getenv('sendgrid_api_key'))
def send_email(act... | FirstCoder1/Dorks | server/service/email_service.py | email_service.py | py | 1,502 | python | en | code | 0 | github-code | 90 |
40689596030 | from selenium import webdriver
from fixtures.contact import ContactHelper
from fixtures.group import GroupHelper
from fixtures.session import Session
class Application:
def __init__(self, browser, base_url):
if browser == "firefox":
self.driver = webdriver.Firefox()
elif browser == "c... | shuradrozd/webProject | fixtures/application.py | application.py | py | 1,030 | python | en | code | 0 | github-code | 90 |
18325710909 |
def resolve():
n = int(input())
for i in range(1, 10):
a = n // i
if n % i == 0 and a < 10:
print('Yes')
return
print('No')
if __name__ == "__main__":
resolve()
| Aasthaengg/IBMdataset | Python_codes/p02880/s024786774.py | s024786774.py | py | 219 | python | en | code | 0 | github-code | 90 |
74340486377 |
# Method based on L. N. Trefethen,Spectral Methods in MATLAB(SIAM,2000) and http://blue.math.buffalo.edu/438/trefethen_spectral/all_py_files/
import numpy as np
import math
pi = math.pi
#It builds the Chebyshev grid and a differentiation matrix in a general domain (a, b)
def chebymatrix(Ncheb,a,b):
range_... | cjoana/GREx | SPBHS/Dmatrix.py | Dmatrix.py | py | 712 | python | en | code | 1 | github-code | 90 |
22237355494 | ### 13023
def dfs(p,res):
if res >= 5:
print(1)
exit()
for a in r[p]:
if visit[a] == 0:
visit[a] = 1
dfs(a,res+1)
visit[a] = 0
n, m = map(int, input().split())
r = [[] for _ in range(n)]
for _ in range(m):
i,j = map(int, input().spl... | happysang/baekjoon_algorithm | 코딩테스트준비2023/dfs.py | dfs.py | py | 1,711 | python | en | code | 0 | github-code | 90 |
29981098775 | import sys
import time
import struct
import json
from pprint import pprint
from datetime import datetime
import os
import shutil
import fnmatch, re
import wotdecoder
# Returns the list of .extension files in path directory. Omit skip file. Can be recursive.
def custom_listfiles(path, extension, recursive, skip = None... | raszpl/wotdecoder | findplayer.py | findplayer.py | py | 15,816 | python | en | code | 35 | github-code | 90 |
5759849265 | import time
import inspect
# Use as function decorator for printing the execution time of a function
# eg.
# @PrintExecutionTime
# async def on_step(self, iteration):
# ...
#
# will print
# on_step: 0.495ms
# whenever on_step is called
def PrintExecutionTime(func):
def calculate_execution_time(start):... | Scottdecat/SwarmLord | bot/debug/debug_utils.py | debug_utils.py | py | 1,670 | python | en | code | 0 | github-code | 90 |
28489808662 | #!/usr/bin/python
import os
import cv2
import numpy as np
def SGBM(left, right):
kernel_size = 3
smooth_left = cv2.GaussianBlur(left, (kernel_size,kernel_size), 1.5)
smooth_right = cv2.GaussianBlur(right, (kernel_size, kernel_size), 1.5)
window_size = 9
left_matcher = cv2.StereoSGBM_create(
numDisparities=... | ImaCVer/SGBM | SGBM.py | SGBM.py | py | 1,111 | python | en | code | 1 | github-code | 90 |
24827376192 | from helpers import alphabet_position, rotate_character
def encrypt(text, rot_key):
lister = list(rot_key)
iterate = 0
rot = 0
result = ""
addition = ""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
ALPHA_bet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for char in text:
if char in alphabet or char... | p-fannon/Crypto | vigenere.py | vigenere.py | py | 840 | python | en | code | 0 | github-code | 90 |
27097400018 | from spack import *
import glob
class Vardictjava(Package):
"""VarDictJava is a variant discovery program written in Java.
It is a partial Java port of VarDict variant caller."""
homepage = "https://github.com/AstraZeneca-NGS/VarDictJava"
url = "https://github.com/AstraZeneca-NGS/VarDictJava/rel... | matzke1/spack | var/spack/repos/builtin/packages/vardictjava/package.py | package.py | py | 761 | python | en | code | 2 | github-code | 90 |
16448338230 | from arl.env import BaseEnv, EnvSpaceType
import gymnasium as gym
from typing import Dict, Any, List, Tuple, Union, Optional
import numpy as np
class GymEnv(BaseEnv):
def __init__(
self, env_name: str, env_params: dict = {}, seed: Optional[int] = None
) -> None:
super().__init__(env_name, env_... | noobHuKai/arl | arl/env/gym_env.py | gym_env.py | py | 2,485 | python | en | code | 0 | github-code | 90 |
9914010818 | '''
# -*- coding: UTF-8 -*-
# Interstitial Error Detector
# Version 0.2, 2013-08-28
# Copyright (c) 2013 AudioVisual Preservation Solutions
# All rights reserved.
# Released under the Apache license, v. 2.0
# Created on Aug 6, 2014
# @author: Furqan Wasi <furqan@avpreserve.com>
'''
from PySide.QtCore import... | WeAreAVP/interstitial | GUI/AboutInterstitialGUI.py | AboutInterstitialGUI.py | py | 4,910 | python | en | code | 9 | github-code | 90 |
7819942656 | ### util functions for parsing all the moonshot data
### matthew.robinson@postera.ai
# general imports
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Descriptors
from chembl_structure_pipeline import standardizer
# get parent path of file
from pat... | postera-ai/COVID_moonshot_submissions | lib/utils.py | utils.py | py | 5,136 | python | en | code | 18 | github-code | 90 |
43690412082 | import discord
from discord.ext import commands, tasks
import requests
from datetime import datetime
def get_data():
json = requests.get('https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/ncov_cases/FeatureServer'
'/2/query?f=json&where=1%3D1&returnGeometry=false&spatialRe... | nwithan8/Arca | general/coronavirus.py | coronavirus.py | py | 2,356 | python | en | code | 22 | github-code | 90 |
10921173712 | #!/usr/bin/env python3
"""
Description:
This script will launch ``middle_bed_enrichment`` for every bed in a given folder
"""
import os
import subprocess
import argparse
def main(trna_launcher, folder_bed, fasterdb_bed, output):
"""
:param trna_launcher: (string) file corresponding to the tRNA launche... | LBMC/Fontro_Aube_2019 | clip_analysis/src/middle_bed_launcher.py | middle_bed_launcher.py | py | 2,817 | python | en | code | 0 | github-code | 90 |
40606337848 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = None
temp = None
add = ... | ajaydeep300/leet | 2-add-two-numbers/2-add-two-numbers.py | 2-add-two-numbers.py | py | 1,437 | python | en | code | 0 | github-code | 90 |
13046639626 | from neural_network import *
from text_parser import Parser
from tkinter import *
import drawer as dr
"""
Klasa Menu odpowiedzialna jest za wyświetlanie i obsługę menu - wywoływanie metod sieci neuronowej i parsera.
"""
class Menu:
root = Tk()
network = None
parser = Parser()
text_entry = None
ou... | KowalDrzo/LanguageDetector | gui.py | gui.py | py | 4,022 | python | en | code | 0 | github-code | 90 |
10527452022 | # © 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2014 initOS GmbH & Co. KG <http://www.initos.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models, api
from odoo.exceptions import Warning as UserError
class HrPublicHolidaysLine(models.Model):
... | JoryWeb/illuminati | poi_hr_public_holidays/models/hr_public_holidays_line.py | hr_public_holidays_line.py | py | 2,221 | python | en | code | 1 | github-code | 90 |
10680771102 | import numpy as np
import matplotlib.pyplot as plt
import src.util.utl as utl
def nat_spline_interpolation(x: np.ndarray, y: np.ndarray, x_int: np.ndarray) \
-> np.ndarray:
'''
natürliche kubische Spline Interpolation für n+1 Stützpunkte
Parameters:
x: Zeilenvektor mit x der Stützpunkte, läng... | merlinio2000/seppi | src/hm2/interpolation.py | interpolation.py | py | 5,404 | python | de | code | 0 | github-code | 90 |
15836449468 | from SharedInterfaces.RegistryAPI import *
from SharedInterfaces.ProvenanceAPI import *
from tests.helpers.general_helpers import *
from tests.helpers.datastore_helpers import *
from tests.helpers.prov_helpers import *
from tests.helpers.registry_helpers import *
from tests.helpers.link_helpers import *
from resources.... | provena/provena | tests/integration/tests/workflows/test_workflows.py | test_workflows.py | py | 16,675 | python | en | code | 3 | github-code | 90 |
44158407599 | # -*- coding: utf-8 -*-
import os
import base64
import time
from datetime import timedelta
from proj.celery import celery_app
from messaging.sms import SmsSubmit
from django.utils import timezone
from email.utils import formataddr
from celery.utils.log import get_task_logger
import asterisk.manager
from django.conf i... | denispan1993/vitaliy | applications/sms_ussd/tasks.py | tasks.py | py | 10,370 | python | en | code | 0 | github-code | 90 |
45858587209 | import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np # to create the lambda grid
import pandas as pd
from sklearn import linear_model
from sklearn.linear_model import Lasso # for lasso regression only
# #############################################################################
col... | alexlee2000/LASSO_and_Ridge_Regression | Part6.py | Part6.py | py | 2,420 | python | en | code | 1 | github-code | 90 |
37712882382 | import numpy as np
import pandas as pd
from sklearn import linear_model
from scipy import signal
import argparse
#==============================================================================
# COMMAND LINE ARGUMENTS
# Create parser object
cl_parser= argparse.ArgumentParser(
description="Filter data and compute d... | Faaizz/covid_19_analysis | src/features/build_features.py | build_features.py | py | 5,120 | python | en | code | 0 | github-code | 90 |
17941648849 | import sys
import math
from collections import defaultdict
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
if row <= 0:
return [[] for _ in range(col)]
elif c... | Aasthaengg/IBMdataset | Python_codes/p03569/s253004695.py | s253004695.py | py | 801 | python | en | code | 0 | github-code | 90 |
73061944936 | from misc import dp, bot
from aiogram.types import Message
from aiogram.types.message import ContentType
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
import logging
from .states import AdminState, ShowSearch, cancel_keyboard, admin_keyboard
from .menu import show_search
from us... | katustrica/bot_twitt | handlers/admin.py | admin.py | py | 2,153 | python | ru | code | 0 | github-code | 90 |
28407545687 | class Solution(object):
def minPathSum(self, grid):
n,m = len(grid), len(grid[0])
# f[i][j] - minimal cost to get to the i-th field
f = [[0 for _ in range(m)] for _ in range(n )]
f[0][0] = grid[0][0]
for i in range(1,n):
f[i][0] = f[i-1][0] + gri... | psp515/LeetCode | 64-minimum-path-sum/64-minimum-path-sum.py | 64-minimum-path-sum.py | py | 585 | python | en | code | 1 | github-code | 90 |
29154139127 | from datetime import datetime
def get_days_from_today(date):
list = []
date_1 = date.split("-")
date_now = datetime.now()
for i in date_1:
i = int(i)
list.append(i)
date_2 = datetime(year=list[0], month=list[1], day=list[2])
result = date_now - date_2
return result.days
p... | LeadShadow/hw8-autocheck | 1ex.py | 1ex.py | py | 359 | python | en | code | 0 | github-code | 90 |
3939023320 | def read_input(path):
instructions = []
with open(path) as f:
for line in f:
tmp = line.split()
instructions.append((tmp[0], int(tmp[1])))
return instructions
def calc_position(instructions):
x = 0
y = 0
for operation, distance in instructions:
if opera... | 95ep/AoC | y2021/day02.py | day02.py | py | 1,134 | python | en | code | 0 | github-code | 90 |
5417748598 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 12 16:35:51 2021
@author: jsy18
"""
# vary the probability of flipping the bit
import numpy as np
import matplotlib.pyplot as plt
from errcorrect_sigma2 import QR,rng, bit_flip_code
import scipy as sp
from scipy.optimize import curve_fit
#%%
#noisePar... | JieSing/BScproject | vary_bitflip.py | vary_bitflip.py | py | 4,259 | python | en | code | 0 | github-code | 90 |
8798311869 | import bs4
import json
import parse
import argparse
import requests
import pandas as pd
import alive_progress as ap
from os import path
def get_mod_gitlinks(path: str):
links = []
with open(path) as f:
for line in f.readlines():
matches = parse.findall("{:s}github.com/{}{:s}v{:d}.{:d}.{:d}... | DeveloperChaseLewis/scripts | gitscrape.py | gitscrape.py | py | 4,147 | python | en | code | 0 | github-code | 90 |
21694077720 | def file_to_list(filename):
fin = open(filename, "rt", encoding="utf-8")
names = fin.readlines()
fin.close()
return names
def order_name(names):
return names.sort()
def list_to_file(names):
messages = {"total": "Total of {} names"}
fout = open("41_out.txt", "wt", encoding="utf-8")
p... | jbaltop/57_Challenges | part7/41.py | 41.py | py | 790 | python | en | code | 29 | github-code | 90 |
5291662838 | from __future__ import annotations
import logging
import pathlib
from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Sequence, Tuple, Union
from composer.profiler.json_trace_handler import JSONTraceHandler
from composer.profiler.marker import Marker
from composer.profiler.profiler_action import Profiler... | mosaicml/composer | composer/profiler/profiler.py | profiler.py | py | 14,764 | python | en | code | 4,712 | github-code | 90 |
70361217897 | from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
# creating a new user model by inheriting AbstractUser model and changing username to email
# Also updating a few extra fields like phone, gender and session token
class CustomUser(AbstractUser):
name = mode... | thej123/ecom | ecom/api/user/models.py | models.py | py | 888 | python | en | code | 1 | github-code | 90 |
23722324267 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
问题描述:
给定一个数组和一个目标值,在数组中找出三个数,使它们的和为目标值(two_sum的升级问题)
https://leetcode-cn.com/problems/3sum/
示例:
输入[-1,0,1,2,-1,-4] 0 输出[[-1,0,1], [-1,-1,2]]
说明:
输出为数组元素的值,而不是元素的下标,不能包含重复的三个数的组合
"""
def three_sum(arr, target):
"""
算法思路:
排序后从头到尾遍历数组元素,如取第一个元素,则在剩下的数组元素中取另... | sharevong/algothrim | three_sum.py | three_sum.py | py | 2,096 | python | zh | code | 0 | github-code | 90 |
16214561095 | # methods to work with the Google Spreadsheet
# tutorial: https://youtube.com/watch?v=aruInGd-m40
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
from config import your_email
# Connect to Google
# Scope: Enable access to specific links
scope = ['ht... | Trionyx/albion_price_parser | data_handler.py | data_handler.py | py | 5,851 | python | en | code | 0 | github-code | 90 |
16623080786 | # https://adventofcode.com/2022/day/4
import pathlib
import time
script_path = pathlib.Path(__file__).parent
input = script_path / "input.txt" # 524 // 798
input_test = script_path / "test.txt" # 2 //
def parse(puzzle_input):
"""Parse input"""
with open(puzzle_input, "r") as file:
... | TragicMayhem/advent_of_code | aoc_2022/day04/aoc2022d04.py | aoc2022d04.py | py | 2,765 | python | en | code | 0 | github-code | 90 |
18429238249 | import sys
N=int(input())
b=list(map(int,input().split()))
ans=[]
for i in range(N):
for j in range(N-1-i,-1,-1):
if b[j]==j+1:
ans.append(b.pop(j))
break
elif j==0:
print('-1')
sys.exit()
else:
continue
for i in range(N-1,-1,-1):... | Aasthaengg/IBMdataset | Python_codes/p03089/s318452993.py | s318452993.py | py | 338 | python | en | code | 0 | github-code | 90 |
34039951158 | import os
import json
import cv2
import numpy as np
#########################################################################################
# GLOBAL VARIABLES
# Total amount of keypoints presented in the new OpenPose model
KEYPOINTS_TOTAL = 25.0
# A keypoint is considered as a valid one if its score is greater tha... | gsbiel/python-stuff | filtro_confiabilidade.py | filtro_confiabilidade.py | py | 7,588 | python | en | code | 0 | github-code | 90 |
6936466111 | from lxml import etree
from . import node
import re
class Stage(object):
XMLNS = "http://tail-f.com/ns/config/1.0"
XML = "{%s}" % XMLNS
XMLNSMAP = {None : XMLNS}
NCSNS = "http://tail-f.com/ns/ncs"
NCS = "{%s}" % NCSNS
NCSNSMAP = {None : NCSNS}
name_instance = 0
def __init__(self, sch... | NSO-developer/drned-xmnr | drned/drned/stage.py | stage.py | py | 3,271 | python | en | code | 6 | github-code | 90 |
3974792169 |
def word_count(str):
counts = dict()
word = str,split('')
for word in words:
if word in counts:
counts[word] =+ 1
else:
return count
word_count('the quick brown fox jumps over the lazy dog.')
| priyankang/Debbug | bas_ek_galti.py | bas_ek_galti.py | py | 248 | python | en | code | 0 | github-code | 90 |
24107171808 | class Solution():
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
n=len(matrix)
for i in range(n):
for j in range(i):
matrix[i][j],matrix[j][i]=matrix[j][i... | Snobin/CompetitiveCoding | rotateimage.py | rotateimage.py | py | 545 | python | en | code | 2 | github-code | 90 |
2206663160 | import pandas as pd
import pdfkit
import os
import subprocess
import sys
pdflocation = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') + '\\App\\PDFFiles'
def exceltopdf(input, output):
filename = input.split('\\')[-1].split('.')[0] + '.pdf'
df = pd.read_excel(input)#input
df.t... | narasimha193/pdf_generator | py/exceltopdf.py | exceltopdf.py | py | 869 | python | en | code | 0 | github-code | 90 |
17984987439 | from collections import Counter
S = list(input())
abc = [chr(ord('a') + i) for i in range(26)]
ans = 100000
for s in abc:
result = S
count = 0
while len(set(result)) > 1:
count += 1
tmp = ["dd"] * (len(result) - 1)
for i in range(len(result)-1):
if result[i] == s or resu... | Aasthaengg/IBMdataset | Python_codes/p03687/s936990406.py | s936990406.py | py | 472 | python | en | code | 0 | github-code | 90 |
17160935530 | from dataclasses import dataclass, asdict
import os
from amplitude_experiment import Experiment, User, LocalEvaluationConfig
class CustomError(Exception):
pass
@dataclass
class UserProperties:
org_id: str = None
org_name: str = None
username: str = None
email: str = None
plan: str = None
... | LambdaTest/lambda-featureflag-python-sdk | localEvaluation.py | localEvaluation.py | py | 2,745 | python | en | code | 0 | github-code | 90 |
18310587729 | import sys
# sys.setrecursionlimit(100000)
def input():
return sys.stdin.readline().strip()
def input_int():
return int(input())
def input_int_list():
return [int(i) for i in input().split()]
def main():
n = input_int()
A = input_int_list()
MOD = 10**9 + 7
cnt = 1
x, y, z = 0, 0,... | Aasthaengg/IBMdataset | Python_codes/p02845/s253205788.py | s253205788.py | py | 891 | python | en | code | 0 | github-code | 90 |
16762188600 | import dataclasses
from typing import Collection, Iterable, List, Type
from unittest import TestCase
from harmony import OnePair, HarmonyMode, TwoPairs
from .game import PlayerCards, CommunityCards
from .winner import winner
class TestWinner(TestCase):
@dataclasses.dataclass
class TestData:
players: ... | ehsundar/foldem | judge/test_winner.py | test_winner.py | py | 2,310 | python | en | code | 0 | github-code | 90 |
73241970537 | '''
- 30분 고민하고 1시간 30분 구현
- 시간 복잡도 생각 안함, N이 100이하여서 구현만 하면 맞을 것이라고 생각함
- 가장 중요한 점은 어항을 어떻게 저장할 것인가 -> 행렬을 회전하고 붙이려면 어느 형태가 편할까에 대한 고민을 함
- 그래서 백준에 나온 그림 기준 아래와 같이 리스트에 저장
3 5 [[3, 3],
3 14 9 11 8 -> [14, 5],
[9],
[11... | kyeong8/CodingTestStudy | twowindragon/bj23191.py | bj23191.py | py | 5,114 | python | ko | code | 0 | github-code | 90 |
4174000041 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FinanceFeed'
db.create_table('newsconnector_financefeed', (
('rssfeed_ptr', se... | miltontony/newsconnector | newsconnector/migrations/0002_auto__add_financefeed__add_entertainmentfeed__add_sportsfeed__add_news.py | 0002_auto__add_financefeed__add_entertainmentfeed__add_sportsfeed__add_news.py | py | 7,319 | python | en | code | 1 | github-code | 90 |
73827937898 | from typing import Optional, Callable, Dict, Tuple, List
from collections import defaultdict
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision.datasets import CocoDetection
def default_collate_fn(samples):
fetched_data = defaultdict(list)
for sample in samples:
... | borhanMorphy/object-as-points | centernet/dataset/coco.py | coco.py | py | 3,863 | python | en | code | 2 | github-code | 90 |
11609469546 | import gzip
from fastai.text import *
def build_lm(data_path, model_name):
with gzip.open(data_path, "rt", encoding="UTF-8") as fin:
data = fin.readlines()
n_data = len(data)
print(f"load {n_data} texts")
data_lm = TextLMDataBunch.from_tokens("", trn_tok=data, trn_lbls=[0]*n_data,
... | seantyh/GWA2019 | scripts/build_lm.py | build_lm.py | py | 512 | python | en | code | 0 | github-code | 90 |
43486663487 | import gspread
import numpy as np
# define data, and change list to array
x = [3,21,22,34,54,34,55,67,89,99]
x = np.array(x)
y = [2,22,24,65,79,82,55,130,150,199]
y = np.array(y)
def model(a,b,x):
return a*x + b
def loss_function(a,b,x,y):
num = len(x)
prediction = model(a,b,x)
return (0... | VenchasS/DA-in-GameDev-lab2 | task2.py | task2.py | py | 1,483 | python | en | code | 0 | github-code | 90 |
29061573383 | """Useful functions for matrix transformations"""
import cv2
import numpy as np
def order_points(pts):
"""
Helper function for four_point_transform.
Check pyimagesearch blog for an explanation on the matter
"""
# Order: top-left, top-right, bottom-right and top-left
rect = np.zeros((4, 2), d... | tempdata73/tic-tac-toe | utils/imutils.py | imutils.py | py | 1,822 | python | en | code | 10 | github-code | 90 |
2461885141 | class Solution(object):
def cellsInRange(self, s):
"""
:type s: str
:rtype: List[str]
"""
start_stop = s.split(":")
start, stop = start_stop[0], start_stop[1]
start_num = int(start[1:])
end_num = int(stop[1:])
start_col = (start[:1])
en... | petrosDemetrakopoulos/Leetcode | code/Python/2194-CellsInARangeOnAnExcelSheet.py | 2194-CellsInARangeOnAnExcelSheet.py | py | 557 | python | en | code | 0 | github-code | 90 |
30893094852 | import ctypes
import datetime
import decimal
import sys
from peewee import ImproperlyConfigured
from peewee import sqlite3
from playhouse.sqlite_ext import *
sqlite3_lib_version = sqlite3.sqlite_version_info
# Peewee assumes that the `pysqlite2` module was compiled against the
# BerkeleyDB SQLite libraries.
try:
... | theotherp/nzbhydra | libs/playhouse/berkeleydb.py | berkeleydb.py | py | 4,138 | python | en | code | 559 | github-code | 90 |
20850894532 | """
Given a number n, find length of the longest consecutive 1s in its binary representation.
Examples :
Input : n = 14
Output : 3
The binary representation of 14 is 1110.
The idea is based on the concept that if we AND a bit sequence with a shifted version of itself, we’re effectively
removing the trailing 1 from e... | Harishkumar18/data_structures | cracking_the_coding_interview/bit_manipulation/count_consecutive_1s.py | count_consecutive_1s.py | py | 814 | python | en | code | 1 | github-code | 90 |
35816924725 | #!/usr/bin/env python3
'''
Library for 74HC595 shiftregister
Based on similar script for raspberry pi https://github.com/mignev/shiftpi
'''
import RPi.GPIO as GPIO
from time import sleep
class SH74HC595:
# Define pins
_DATA_pin = 40 # pin 14 (DS) on the 75HC595 GPA0
_LATCH_pin = 38 # pin 12 (STCP) o... | Brent-rb/University | master/networking-and-interfacing-iot-platforms/practica/2/3.1-shift-gpio/main.py | main.py | py | 3,290 | python | en | code | 0 | github-code | 90 |
24107139528 | class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=merge... | Snobin/CompetitiveCoding | mergetwosortedlists(2).py | mergetwosortedlists(2).py | py | 1,451 | python | en | code | 2 | github-code | 90 |
26062575924 | import sys
import os
import json
import logging
from coffee_machine import CoffeeMachine
def file_sanity_check():
file_data = None
if len(sys.argv) > 1:
file_path = sys.argv[1]
if os.path.exists(file_path):
with open(file_path) as file_ptr:
file_data = json.load(fil... | hakimkartik/CoffeeMachine | main.py | main.py | py | 1,856 | python | en | code | 0 | github-code | 90 |
529515492 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`graphical_maze` module
:author: Coignion Tristan, Tayebi Ajwad, Becquembois Logan
:date: 15/11/2018
This module provides function which help display the maze from the Maze module in a window
Uses:
- maze.py
- square.py (Dependancy)
- tkinter
""... | Saauan/Maze | src/graphical_maze.py | graphical_maze.py | py | 8,762 | python | en | code | 0 | github-code | 90 |
34731504427 | #!/usr/bin/env python3
""" Defines `train_transformer` """
import tensorflow.compat.v2 as tf
Dataset = __import__('3-dataset').Dataset
create_masks = __import__('4-create_masks').create_masks
Transformer = __import__('5-transformer').Transformer
def train_transformer(N, dm, h, hidden, max_len, batch_size, epochs):
... | keysmusician/holbertonschool-machine_learning | supervised_learning/0x12-transformer_apps/5-train.py | 5-train.py | py | 4,428 | python | en | code | 1 | github-code | 90 |
2510262102 | from pyspark.sql import SparkSession
import pyspark.sql.functions as F
import pyspark.sql.types as T
spark = SparkSession.builder.master("local[*]").getOrCreate()
# Create dataframes
# 1. from raw source_data sources - files ( spark.read)
df = spark.read.format("json").load("source_data/flight-source_data/json/201... | VladyslavPodrazhanskyi/learn_spark | code/my_practice/4.Creating_dataframes.py | 4.Creating_dataframes.py | py | 1,228 | python | en | code | 0 | github-code | 90 |
11597579671 | # @file tweeting_ucrocontroller.c
# @author Gregório da Luz
# @date January 2021
# @brief file to tweet through microcontroller
import serial
import tweepy
#Here you put the key, secret, token and, token secret from your Twitter Developer account
key = "x90redHO7n2gRHn1IpSc8Vcor"
secret = "CmxFBjpo6uuqFhCGi6NRFAo2... | gregorio1212/tweet-machine | Python/tweeting_ucontroller.py | tweeting_ucontroller.py | py | 1,180 | python | en | code | 0 | github-code | 90 |
23221680228 | import time
import numpy as np
from lib.hands.hands import Hands, MediapipeHands
from lib.hands.detector import HandDetModel
from lib.hands.pose import PoseLandmark
from lib.utils.draw import (
draw_point,
draw_rectangle,
draw_rotated_rect,
draw_text,
copy_past_roi,
Draw3dLandmarks,
draw_ge... | Daming-TF/Mediapipe-hands | lib/hands/hand_tracker.py | hand_tracker.py | py | 5,087 | python | en | code | 3 | github-code | 90 |
18470742259 | import sys
input = sys.stdin.readline
def main():
S = input().rstrip()
ans = 0
n_white = 0
for s in S[::-1]:
if s == "W":
n_white += 1
else:
ans += n_white
print(ans)
if __name__ == "__main__":
main()
| Aasthaengg/IBMdataset | Python_codes/p03200/s714533700.py | s714533700.py | py | 272 | python | en | code | 0 | github-code | 90 |
40564911848 | from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
class KhatavahiBookServiceSetting(Document):
pass
def setup_custom_fields():
custom_fields = {
"Item": [
dict(... | Khatavahi-BI-Solutions/bookingapp | bookingapp/booking_service_app/doctype/khatavahi_book_service_setting/khatavahi_book_service_setting.py | khatavahi_book_service_setting.py | py | 1,482 | python | en | code | 26 | github-code | 90 |
11995234376 | #!"./venv/Scripts/python.exe"
import cv2
import numpy as np
import os
from scipy import ndimage
cv2_base_dir = os.path.dirname(os.path.abspath(cv2.__file__))
haar_model = os.path.join(cv2_base_dir, 'data/haarcascade_frontalface_default.xml')
print(" ")
print(haar_model)
blue = (255,0,0)
red = (0,0,255)
green = (0,25... | jakem68/Python-OpenCV | tutorial/09_faceDetection.py | 09_faceDetection.py | py | 793 | python | en | code | 0 | github-code | 90 |
73397745256 | #
# @lc app=leetcode.cn id=46 lang=python3
#
# [46] 全排列
#
# https://leetcode-cn.com/problems/permutations/description/
#
# algorithms
# Medium (65.30%)
# Total Accepted: 13.9K
# Total Submissions: 21.3K
# Testcase Example: '[1,2,3]'
#
# 给定一个没有重复数字的序列,返回其所有可能的全排列。
#
# 示例:
#
# 输入: [1,2,3]
# 输出:
# [
# [1,2,3],
# [... | elfgzp/Leetcode | 46.permutations.py | 46.permutations.py | py | 1,373 | python | en | code | 1 | github-code | 90 |
13328505893 | import math
from tkinter import *
from random import randint, shuffle, sample
from time import sleep
root = Tk()
root.title("Sorting Algorithms Visualiser")
sortType = StringVar()
menuText = StringVar()
colourOptions = ["Red", "Green", "Blue", "Monochrome", "Random"]
#Initialises the necessary functions based on ente... | jjdshrimpton/PythonJunk | Sorting Visualiser2.py | Sorting Visualiser2.py | py | 8,472 | python | en | code | 0 | github-code | 90 |
23858064439 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
import os
import os.path
import cv2
import sys
fname = sys.argv[1]
vc = cv2.VideoCapture(fname)
n = -1
rval = True
if not vc.isOpened():
print("Unable to open", fname, file=sys.stderr)
while rva... | mvsjober/pair-annotate | scripts/midframe.py | midframe.py | py | 1,051 | python | en | code | 2 | github-code | 90 |
10828506062 | import os
import cv2
import shutil
from pycocotools.coco import COCO
def copy_some_imgs(json, class_name, path, to_path):
annFile = json
coco = COCO(annFile)
catIds = coco.getCatIds(catNms=[class_name])
imgIds = coco.getImgIds(catIds=catIds)
imgs = coco.loadImgs(ids=imgIds)
AnnIds = coco.getAn... | ZHUXUHAN/Python-Tools | coco_img_copy.py | coco_img_copy.py | py | 822 | python | en | code | 1 | github-code | 90 |
26050686125 | import logging
from rest_framework import generics, status
from rest_framework.response import Response
from .models import ArticlesModel
from .serializers import ArticleSerializer
logger = logging.getLogger(__name__)
class ArticleListCreateAPIView(generics.ListCreateAPIView):
'''
Allowed methods: POST a... | preitychib/AnimoAPI | articles/views.py | views.py | py | 2,719 | python | en | code | 0 | github-code | 90 |
70510731177 | import weakref
import math
import numpy as np
import py_trees
import shapely
import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.timer import GameTime
from srunner.scenariomanager.traffic_events import TrafficEvent, TrafficEventType
class Criterion(py_... | yixiao1/Action-Based-Representation-Learning | scenario_runner/srunner/scenariomanager/scenarioatomics/atomic_criteria.py | atomic_criteria.py | py | 44,084 | python | en | code | 13 | github-code | 90 |
4124049511 | #!/usr/bin/env python3
""" This is a utility module to read PGM image files that represent a map of the environment.
It can handle ascii (P2) and binary (P5) PGM file formats.
The image data is converted to a numpy array.
"""
import numpy as np
def read_line(pgm_file):
""" Read a line from the pgm file.... | Butakus/landmark_placement_optimization | lpo/pgm.py | pgm.py | py | 3,488 | python | en | code | 1 | github-code | 90 |
1497915572 | """
Created on Sat Sep 19 10:18:34 2020
@author: Camilo
"""
import matplotlib.pyplot as plot
import numpy as np
def canicas(mat,vect,clicks):
res=[]
k=0
while k != clicks:
vect = mat*vect
k+=1
for i in range(len(vect)):
res = res + [int(vect[i])]
for i i... | camiloarchila/clasico_a_lo_cuantico | clasicoalocuantico.py | clasicoalocuantico.py | py | 1,423 | python | en | code | 0 | github-code | 90 |
25067316274 | import os
import random
def get_dirs_and_files(path):
dir_list = [directory for directory in os.listdir(path) if os.path.isdir(path + './' + directory)]
file_list = [directory for directory in os.listdir(path) if not os.path.isdir(path + './' + directory)]
return dir_list, file_list
def clas... | eamenier/CS2302Lab1OptionA | Main.py | Main.py | py | 1,525 | python | en | code | 0 | github-code | 90 |
40389706915 | # Time: O(nlogn)
# 随机的在数组中选择一个数key, 小于等于key的数统一放到key的左边, 大于key的数统一放到key的右边。
# 对左右两个部分,分别递归的调用快速排序的过程。
# 快速排序——划分过程(Partition过程): 即找到一个数后,小于等于它的数如何放到它的左边,大于它的数如何放到它的右边。
# 1、令划分值放在整个数组最后的位置
# 2、设计一个小于等于区间,初始长度为0,放在 整个数组的左边
# 3、从左到右遍历所有元素,
# 如果当前元素m大于划分值,继续遍历下一个元素;
# 如果当前元素m小于等于划分值,将当前元素m和小于等于区间(在整个数组的左边)的下一... | yuanswife/LeetCode | src/Sort/O(nlogn)_快速排序.py | O(nlogn)_快速排序.py | py | 2,905 | python | zh | code | 0 | github-code | 90 |
7994526347 | from datetime import datetime as dt
from datetime import date, timedelta
import numpy as np
import pandas as pd
from readlog import readlogline
import sys
import re
import subprocess
from scapy.all import *
import math
import pickle
def main(re_name):
apps = ['snort', 'suricata', 'Lastline', 'pa3220', 'ddi4100', '... | suuri-kyudai/Generating-Dataset-for-NIDS | mk_by_packet.py | mk_by_packet.py | py | 4,361 | python | en | code | 3 | github-code | 90 |
72905503657 | import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
# Create some test data for our catalog in the form of a list of dictionaries.
banks = {
123456789:
{'id': 123456789,
'Bank': 'NBP S.A.',
'Osoba': 'Aleksander Kociumaka',
'Numer': '8748374233'... | zadadam/AssecoHacakthon | AppApi/server.py | server.py | py | 990 | python | en | code | 0 | github-code | 90 |
18011946619 | from functools import lru_cache
@lru_cache
def comb(n, k):
if k == 0:
return 1
elif n == k:
return 1
else:
return comb(n-1, k) + comb(n-1, k-1)
N, A, B = map(int, input().split())
vs = sorted(map(int, input().split()), reverse = True)
print(sum(vs[:A]) / A)
v_replaceable = vs[A]
... | Aasthaengg/IBMdataset | Python_codes/p03776/s360145241.py | s360145241.py | py | 627 | python | en | code | 0 | github-code | 90 |
10214817532 | # https://www.hackerrank.com/contests/smart-interviews/challenges/si-path-in-a-matrix/copy-from/1321037246
'''Given a matrix, find the number of ways to reach from the top-left cell to the right-bottom cell. At any step, from the current cell (i,j) you can either move to (i+1,j) or (i,j+1) or (i+1, j+1). Please note t... | SheetanshKumar/smart-interviews-problems | Path in a Matrix.py | Path in a Matrix.py | py | 1,854 | python | en | code | 6 | github-code | 90 |
37248827870 | import sys
f = open(sys.argv[1])
data = f.read().strip().split(',')
data = [int(d) for d in data]
def calculate(nums, n):
i = 0
prev = nums[-1]
numbers = dict()
numbers[0] = list()
while i < n:
if i < len(nums):
numbers[nums[i]] = [i]
i += 1
else:
... | hmludwig/aoc2020 | src/day15.py | day15.py | py | 760 | python | en | code | 0 | github-code | 90 |
34840005574 | import numpy as np
def standardize_image(image):
image -= np.min(image)
image /= np.std(image)
return image
def ensemble_expand(image):
ensemble = np.zeros((8,) + image.shape)
ensemble[0] = image
ensemble[1] = np.fliplr(image)
ensemble[2] = np.flipud(image)
ensemble[3] = np.rot90(im... | jacobjma/nionswift-deep-learning | nionswift_plugin/nionswift_structure_recognition/utils.py | utils.py | py | 971 | python | en | code | 0 | github-code | 90 |
70904616937 | import sys; sys.setrecursionlimit(10**6); input = sys.stdin.readline
ans = {}
def find_giga(r):
global len_gd
if len(graph[r]) == 2:
r, d = graph[r][0]
len_gd += d
return find_giga(r)
else:
return r
def dfs(x, d, sum):
global len_gi
sum = max(sum, sum + d)
if l... | dohun31/algorithm | 2021/week_06/210811/20924.py | 20924.py | py | 905 | python | en | code | 1 | github-code | 90 |
72143629418 | from __future__ import print_function, unicode_literals
import json
import pytest
from gratipay.testing import Harness
from aspen import Response
class Tests(Harness):
def hit_members_json(self, method='GET', auth_as=None):
response = self.client.GET('/~Enterprise/members/index.json', auth_as=auth_as)
... | gratipay/gratipay.com | tests/py/test_members_json.py | test_members_json.py | py | 1,864 | python | en | code | 1,121 | github-code | 90 |
25255793822 | import sys
from collections import deque
T = int(sys.stdin.readline())
dx = [-2, -2, -1, -1, 1, 1, 2, 2]
dy = [1, -1, 2, -2, 2, -2, 1, -1]
def bfs(matrix, destination_x, destination_y, q):
while q:
x, y = q.popleft()
if x == destination_x and y == destination_y:
return
for i in... | choinara0/Algorithm | Baekjoon/Graph Algorithm/7562번 - 나이트의 이동/7562번 - 나이트의 이동.py | 7562번 - 나이트의 이동.py | py | 1,070 | python | en | code | 0 | github-code | 90 |
13468517790 | import os
import string
from contextlib import contextmanager
from pcg import PcgEngine
engine = PcgEngine()
alpha = string.ascii_letters
alpha_numeric = string.ascii_letters + string.digits
@contextmanager
def ctx_open(path: str, flags: int, mode: int = None):
if mode is None:
fd = os.open(path, flags... | Miravalier/CodeShare | src/utils.py | utils.py | py | 598 | python | en | code | 0 | github-code | 90 |
14154048063 | from collections import defaultdict
day = 2
def algo1(data):
twos = 0
threes = 0
for word in data:
freq = defaultdict(int)
for letter in word:
freq[letter] += 1
if 2 in freq.values():
twos += 1
if 3 in freq.values():
threes += 1
retu... | Surye/aoc2018.py | 2.py | 2.py | py | 1,543 | python | en | code | 0 | github-code | 90 |
40861287970 | import itertools
import unittest
from functools import partial
from typing import List, Type, Dict, Tuple, Callable, Union, Iterable
import torch
from pshape import pshape
from torch import Tensor
from torch.profiler import profile, ProfilerActivity
from torch_pconv import PConv2d
from pconv_guilin import PConvGuilin... | DesignStripe/torch_pconv | tests/test_pconv.py | test_pconv.py | py | 17,005 | python | en | code | 4 | github-code | 90 |
39735665543 | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
n_score = list(map(int, input().split()))
max_score = 0
max_person = 100000
for _ in range(m):
test = list(map(str, input().split()))
score = 0
test[0] = int(test[0])
for j,k in enumerate(test[1:]):
if k == 'O':
... | lyong4432/BOJ.practice | #15702.py | #15702.py | py | 548 | python | en | code | 0 | github-code | 90 |
73332712938 | # goorm / 기타 / 피타고라스 문제
# https://level.goorm.io/exam/43279/%ED%94%BC%ED%83%80%EA%B3%A0%EB%9D%BC%EC%8A%A4-%EB%AC%B8%EC%A0%9C/quiz/1
def find():
for c in range(1, 1000):
for a in range(1, 1000-c):
b = 1000 - a - c
if a**2 + b**2 == c**2:
print(a*b*c)
r... | devwithpug/Algorithm_Study | python/goorm/기타/goorm_43279.py | goorm_43279.py | py | 363 | python | en | code | 0 | github-code | 90 |
28560555508 | """
Кобзарь О.С. Хабибуллин Р.А.
Модуль для построения графиков через plotly
"""
import pandas as pd
import numpy as np
import sys
sys.path.append('../')
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from plotly.offline import plot, iplot
import re
def create_plotly_trace(data_x, data_y,... | unifloc/unifloc_py | uniflocpy/uTools/plotly_workflow.py | plotly_workflow.py | py | 11,948 | python | ru | code | 13 | github-code | 90 |
21985372364 | '''
Given a sorted array of integers A(0 based index) of size N, find the starting and ending position of a given integar B in array A.
Your algorithm’s runtime complexity must be in the order of O(log n).
Return an array of size 2, such that first element = starting position of B in A and second element = ending pos... | prashik856/cpp | InterviewBit/BinarySearch/2.SimpleBinarySearch/5.SearchForARange.py | 5.SearchForARange.py | py | 2,051 | python | en | code | 0 | github-code | 90 |
22553685973 | from matplotlib import pyplot as plt
import csv
import math
import numpy as np
#maks to 153.832040129247
#min to 43.2528741577922
def addVectors(a,b):
x = a[0] + b[0]
y = a[1] + b[1]
z = a[2] + b[2]
return [x,y,z]
def float2rgb(height,maksimum,min):
blue=0.0
green = 1.0 - (height-min)/(maksimum-... | KarolCee/Elevation-Map-Shader | map.py | map.py | py | 5,667 | python | pl | code | 0 | github-code | 90 |
18141895139 | #!usr/bin/env python3
import sys
def main():
r, c = [int(row_col) for row_col in sys.stdin.readline().split()]
sheet = [
[int(row_num) for row_num in sys.stdin.readline().split()]
for row in range(r)
]
sheet.append([0 for col in range(c)])
for row in rang... | Aasthaengg/IBMdataset | Python_codes/p02413/s257358553.py | s257358553.py | py | 535 | python | en | code | 0 | github-code | 90 |
34882545079 |
def find_vowel(word):
vowels = "aieou"
for i, letter in enumerate(word):
for vowel in vowels:
if letter in vowels:
return i
def capitalize(word, flag):
if flag:
return word[0].upper() + word[1:]
return word
def igpay(sentence):
words = sentence.split()
... | ilikepegasi/CSCI1133 | labs/lab08/pigLatin.py | pigLatin.py | py | 1,439 | python | en | code | 0 | github-code | 90 |
73323047657 | #For more information about this, watch this video: https://www.youtube.com/watch?v=2hfoX51f6sg
import math
import os
from svg.path import * #Thank you for using complex numbers as points
from p5 import *
def save_frame(filename,char="#"): #Sorta make a copy of saveFrame() since p5 doesn't have one
global n... | friedkeenan/Epicycles | Epicycles.py | Epicycles.py | py | 4,954 | python | en | code | 11 | github-code | 90 |
18552593579 | n = int(input())
a = [0]
a.extend(list(map(int,input().split())))
a.append(0)
cost = []
for i in range(n):
cost.append(abs(a[i+1]-a[i]))
cost.append(abs(a[-2]))
s_cost = sum(cost)
for i in range(n):
print(s_cost - cost[i]- cost[i+1] + abs(a[i+2]-a[i])) | Aasthaengg/IBMdataset | Python_codes/p03401/s151409513.py | s151409513.py | py | 259 | python | en | code | 0 | github-code | 90 |
41218302157 | # coding=utf-8
# 网页图片爬取
import urllib.request
import urllib
import re
def gethtml(url):
page = urllib.request.urlopen(url)
html1 = page.read()
return html1
def getimage(site):
reg = 'src="(.+?\.jpg)" alt='
imglist = re.findall(reg, site)
print(len(imglist))
x = 0
for imgurl in imgli... | crystal0913/AI | crawler/crawler.py | crawler.py | py | 833 | python | en | code | 1 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.