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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
21268856479 | import uuid
import os
from installed_clients.DataFileUtilClient import DataFileUtil
from installed_clients.KBaseReportClient import KBaseReport
from installed_clients.WorkspaceClient import Workspace
from shutil import copyfile
class htmlreportutils:
def __init__(self):
pass
def create_html_report(se... | kbasecollaborations/kb_gsea | lib/kb_gsea/Utils/htmlreportutils.py | htmlreportutils.py | py | 1,435 | python | en | code | 0 | github-code | 1 |
31129089057 | #!/usr/bin/env python
"""dec07-2.py: Solution to Advent of Code December 7th, part 2
"""
import string
def read_input(filename: str) -> list:
data = list()
new_entry = list()
try:
with open(filename) as f:
for line in f.readlines():
if line != "\n":
... | kyleburnette/adventofcode2020 | solutions/dec07/dec07-2.py | dec07-2.py | py | 710 | python | en | code | 0 | github-code | 1 |
38018413084 | import ccxt
from django.db import models
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils import timezone
from django.db.models import Q, Avg, Sum
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from capital.methods... | Capital-Digital/Trading | trading/models.py | models.py | py | 47,937 | python | en | code | 1 | github-code | 1 |
29831680533 | import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from ..builder import NECKS
def gen_dx_bx(xbound, ybound, zbound):
# xbound: [low_bound, upper_bound, size]
# 'xbound': [-51.2, 51.2, 0.8]
# 'ybound': [-51.2, 51.2, 0.8]
# 'zbound': [-10.0, 10.0, 20.0]
dx = torch.Tensor([row[2] ... | jjw-DL/Code_Analysis | BEVDet/mmdet3d/models/necks/view_transformer.py | view_transformer.py | py | 10,709 | python | en | code | 1 | github-code | 1 |
69795467234 | class ApiError(Exception):
"""Base class for exceptions in this module."""
"""
TODO:add error codes fast names and not hardcode them
"""
class HTTPError(Exception):
BAD_REQUEST = 400
NOT_AUTHENTICATED = 401
FORBIDDEN = 403
NOT_FOUND = 404
GONE=410
... | byldocoder/VK-Clone | Application/Api/ApiError.py | ApiError.py | py | 10,077 | python | en | code | 0 | github-code | 1 |
4540268334 | from crear_functions import *
# Se define una clase Navesita para poder guardar los datos de posicion y rotacion.
class Navesita:
def __init__(self, pipeline): # Se entrega un pipeline en el que dibujar el nodo
self.pos = [0,0,0]
self.xRot = 0 # Grado... | Bysholo/dcc-modelacion-grafica | Tarea 4/navesita.py | navesita.py | py | 2,201 | python | es | code | 0 | github-code | 1 |
8138869558 | from itertools import combinations
class Solution:
def readBinaryWatch(self, num: int) -> list:
hours = [8, 4, 2, 1]
mins = [32, 16, 8, 4, 2, 1]
ans = []
for i in range(num+1):
if num - i > 6: continue
hour = list(combinations(hours, i))
minute... | MinecraftDawn/LeetCode | Easy/401. Binary Watch.py | 401. Binary Watch.py | py | 632 | python | en | code | 1 | github-code | 1 |
72239822113 | # !/usr/bin/env python3
# @file example2_drawing_circle.py
# SCRP: Example 2 - Drawing Circle
# Daryl Dang
"""
Example 2 - Drawing Circle
--------------------------
This example goes over a simple way to draw a circle with the pygame.draw library.
"""
import pygame
# GLOBALS
WHITE = (255, 255, 255)
# Initialize pyg... | dellod/pygame_examples | Session2/example2_drawing_circle/example2_drawing_circle.py | example2_drawing_circle.py | py | 1,157 | python | en | code | 1 | github-code | 1 |
23787064831 |
import logging
def get_logger(name, path):
logger = logging.getLogger(name)
if len(logger.handlers) > 0:
return logger # Logger already exists
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(message)s")
console = logging.StreamHandler()
file_handl... | venzino-han/graph-transfer | igmc/utils.py | utils.py | py | 2,872 | python | en | code | 1 | github-code | 1 |
2716085105 | ################################################### END ########################################################
################################################### SET PATH ########################################################
# Filter results of WGS
import glob
import os
from Bio import SeqIO
from Bio.Seq import S... | caozhichongchong/snp_finder | snp_finder/scripts/vcf_process_Jay.py | vcf_process_Jay.py | py | 4,504 | python | en | code | 2 | github-code | 1 |
37369940242 | from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
GUEST = 0
OPERATOR = 1
LAWYER = 2
ADMIN = 99
ROLE_CHOICES = (
(GUEST, "guest"),
(LAWYER, "lawyer"),
(OPERATOR, "operator"),
(ADMIN, "admin"),
)
phone ... | wujiapei/alldata | dataHub/backend/common/models.py | models.py | py | 733 | python | en | code | 3 | github-code | 1 |
8966512697 |
from pos.kernal.models import Product
from pos.kernal.models import InStockBatch, InStockRecord
from pos.kernal.models import OutStockRecord
from pos.kernal.models import Product
from pos.kernal.models import Product
# import the logging library
import logging
# Get an instance of a logger
logger = logg... | 13devlin247/py-pos | kernal/store.py | store.py | py | 2,618 | python | en | code | 0 | github-code | 1 |
39917897402 | import os
import sublime
import unittest
from ..consts import INFO, WARNING, ERROR
from ..utils import (
find,
get_default_python_command,
get_severity_status_string,
get_error_count,
)
def merge_two_lists(fst, snd):
return fst + list(set(snd) - set(fst))
class TestUtils(unittest.TestCase):
... | figure0/sublime-plugin | tests/test_utils.py | test_utils.py | py | 3,179 | python | en | code | 0 | github-code | 1 |
73767652832 | import json, pytz
from dotenv import load_dotenv
from datetime import datetime
from dagster import sensor, RunRequest, SkipReason, get_dagster_logger
from models.cancel_queue import CancelQueue
from ops.helpers.db_config import db_conn
conn = db_conn()
load_dotenv()
my_logger = get_dagster_logger()
@sensor(job_name... | aman-saleem-qbatch/dagster-cloud-dev | sensors/amz_submit_cancel_order_sensor.py | amz_submit_cancel_order_sensor.py | py | 2,125 | python | en | code | 0 | github-code | 1 |
6257677316 | from turtle import Turtle, Screen
import random
scr = Screen()
scr.setup(width=500, height=400)
user_bet = scr.textinput(title="Make your bet", prompt="Which color turtle will win the race? red,orange,yellow,"
"green,blue,purple: ")
colors = ["red", "orange", "yel... | wintermute111/100DaysOfPython | Day019/turtle-race/main.py | main.py | py | 1,036 | python | en | code | 0 | github-code | 1 |
16557923955 | # https://leetcode.com/problems/jump-game/
# Solved Date: 20.04.25.
def fast_can_jump(nums):
# https://leetcode.com/problems/jump-game/discuss/596266/Python-simple-O(N)-time-O(1)-space-solution
max_pos = 0
for index in range(len(nums)):
max_pos = max(max_pos, index + nums[index])
if max_po... | imn00133/algorithm | LeetCode/Apr20Challenge/Week4/day25_jump_game.py | day25_jump_game.py | py | 1,028 | python | en | code | 0 | github-code | 1 |
2601733208 | """Command line interface"""
import os
import os.path
import time
import buildver
from buildver import error
__all__ = []
HELP = """\
Build and versioning tool for Python projects.
Check a project
===============
$ buildver check
Set a new version
=================
$ buildver set <version>
Build your project
=... | pyrustic/buildver | buildver/cli/__init__.py | __init__.py | py | 5,414 | python | en | code | 3 | github-code | 1 |
439382080 | """
Contains the abstract class of a probability distrobution and associated marginals.
"""
import numpy as np
from ..utilities import utils
from ..utilities.profiler import profile
from .variable import RandomVariableCollection
from . import variable_sort
from functools import reduce
import math
from ..utilities.const... | tcfraser/quantum_tools | code/quantum_tools/statistics/probability.py | probability.py | py | 9,480 | python | en | code | 1 | github-code | 1 |
71913968353 | import tornado.web
import mallory
class HeartbeatHandler(tornado.web.RequestHandler):
def initialize(self, circuit_breaker):
self.circuit_breaker = circuit_breaker
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
if self.circuit_breaker.is_tripped():
self.set_st... | braintree/mallory | mallory/heartbeat_handler.py | heartbeat_handler.py | py | 580 | python | en | code | 57 | github-code | 1 |
24946949793 | from selenium import webdriver
from time import sleep
import csv
from selenium.webdriver.chrome.options import Options
import threading
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from MyClasses impo... | Namgiangvt12/Upwork | 40.0065.py | 40.0065.py | py | 1,495 | python | en | code | 0 | github-code | 1 |
36806627348 | import requests
from bs4 import BeautifulSoup
import time, uuid
from datetime import datetime, timedelta
from database import connectToDatabase
def time24hrsback(): #gives the timestamp before 24 hrs
before24Hours = datetime.today() - timedelta(days=1)
return before2... | AgrawalRiya/python-web-crawler | crawler.py | crawler.py | py | 2,483 | python | en | code | 0 | github-code | 1 |
36795695184 | import PySimpleGUI as sg
from signup import sign_up_gui
def driver_gui(db):
sg.theme('LightGrey1') # Add a touch of color
# All the stuff inside your window.
# get the list of cars that belong to the driver
username = db.get_username()
print(username)
user_data = db.get_driver_info(username)
... | ardaa/CS281 | driver.py | driver.py | py | 3,780 | python | en | code | 0 | github-code | 1 |
70983109473 | from django.urls import path
from . import views
app_name = "api"
urlpatterns = [
path("create/", views.create, name="create"),
path("read/", views.read, name="read"),
path("update/", views.update, name="update"),
path("delete/", views.delete, name="delete"),
path("read/<int:transaction_id>/", vie... | tranlong58/django_mysql_project | api/urls.py | urls.py | py | 357 | python | en | code | 0 | github-code | 1 |
44691722041 | import speech_recognition as sr # recognise speech
import playsound # to play an audio file
from gtts import gTTS # google text to speech
import random
from time import ctime # get time details
import webbrowser # open browser
import ssl
import certifi
import time
import os # to remove created audio files
import dateti... | NidhalBB/Back-end-iCareApp | icare/main.py | main.py | py | 4,635 | python | en | code | 2 | github-code | 1 |
40054794098 | # Task 29 - 05/08/2022
""" Write a Python program to input a natural number and check whether the
number is palindromic or not. """
# Vevan O Narain S6- C
n = input("Enter a natural number: ")
if (n == n[::-1]):
print("Number is a palindrome.")
else:
print("Number is not a palindrome.")
| vevanonarain/Practical-Report-File---1 | task29.py | task29.py | py | 303 | python | en | code | 0 | github-code | 1 |
39206629033 | from operator import itemgetter
from utils import *
memo = []
if __name__ == '__main__':
img_src = cv2.imread('files/adv.jpg')
size = img_src.shape
cap = cv2.VideoCapture("files/foglio.MOV")
vid_writer = cv2.VideoWriter("result_lines.avi", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 28, #(int(cap.ge... | loredeluca/Virtual-Advertising-with-Homography | HomographywithLines.py | HomographywithLines.py | py | 6,027 | python | en | code | 1 | github-code | 1 |
15797910187 | #!/usr/bin/python3
"""
prints the first State object from the database hbtn_0e_6_us
"""
from model_state import Base, State
from sqlalchemy import (create_engine)
from sys import argv
from sqlalchemy.orm import sessionmaker
if __name__ == "__main__":
engine = create_engine(
'mysql+mysqldb://{}:{}@localhost... | Just-Akinyi/alx-higher_level_programming | 0x0F-python-object_relational_mapping/9-model_state_filter_a.py | 9-model_state_filter_a.py | py | 635 | python | en | code | 2 | github-code | 1 |
72895042593 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | CiscoSystems/avos | openstack_dashboard/dashboards/project/data_processing/clusters/tabs.py | tabs.py | py | 6,455 | python | en | code | 47 | github-code | 1 |
43736645697 | import streamlit as st
import cv2
from PIL import Image
import numpy as np
import copy
st.markdown("<h1 style='text-align: center; color: white;'>Color Image</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: white; letter-spacing: 2px'>Praktikum 1 Pengolahan Citra Digital</p>", unsafe_a... | wwdnn/PCD_STREAMLIT | Pages/🎒Pertemuan1.py | 🎒Pertemuan1.py | py | 1,654 | python | en | code | 0 | github-code | 1 |
26672751741 | from collections import OrderedDict
from collections import namedtuple
from itertools import product
from numpy.random import gamma
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
import time
from tensorboardX import SummaryWriter
# Hyper Parameters
params = OrderedDict... | IDayday/DQN-pytorch | DQN-CartPole.py | DQN-CartPole.py | py | 7,066 | python | en | code | 0 | github-code | 1 |
16557402095 | #
# Solved Date: 20.04.22.
import sys
import collections
sys.setrecursionlimit(10 ** 4)
read = sys.stdin.readline
DXY = ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1))
def dfs(land, y, x):
land[y][x] = 0
count = 1
for dy, dx in DXY:
new_y = y + dy
new_x = x + dx
... | imn00133/algorithm | BaekJoonOnlineJudge/CodePlus/600Graph/Main/baekjoon_4963.py | baekjoon_4963.py | py | 1,667 | python | en | code | 0 | github-code | 1 |
71015543395 | # Title: 내 생각에 A번인 단순 dfs 문제가 이 대회에서 E번이 되어버린 건에 관하여(Easy)
# Link: https://www.acmicpc.net/problem/18251
import sys
sys.setrecursionlimit(10 ** 6)
read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
INF = 10**10
MIN = -INF
... | yskang/AlgorithmPractice | baekjoon/python/easy_dfs_my_think_18251.py | easy_dfs_my_think_18251.py | py | 1,371 | python | en | code | 1 | github-code | 1 |
72512669155 | from datetime import datetime, timedelta
from discord import Embed
from discord.ext import commands
import re
import discord
from discord.ext.commands import Cog
from discord.ext.commands import command, has_permissions
from ..db import db
time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {'h': 3600... | LazyBuds/tommy-discord | lib/cogs/reactions.py | reactions.py | py | 6,421 | python | en | code | 0 | github-code | 1 |
34166943718 | #!/usr/bin/python3
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import system
import compute
import heat_capacity
import styles
import glob
from mytimer import Timer
T = np.linspace(0.001, 0.01, 175)
max_interesting_E = -1.442360888736597957e-01
E = np.linspace(-system.h_small, max_intere... | droundy/sad-monte-carlo | two-wells/convergence-for-proposal.py | convergence-for-proposal.py | py | 9,203 | python | en | code | 4 | github-code | 1 |
31817702158 | from flask import Flask
import requests
import json
import requests
from bs4 import BeautifulSoup
from flask_restful import Api, Resource
from flask_cors import CORS
#Api inicializacion
app = Flask(__name__)
CORS(app)
api = Api(app)
#headers
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Ap... | MercinQ/SimillarNewsSearcher | SNS.WEBSCRAPER/main.py | main.py | py | 10,462 | python | en | code | 1 | github-code | 1 |
7998906160 | #---------------------------------IMPORT MODULES----------------------------------
#user modules
import modules.common as common
#built-in modules
import random
#Assigning variables
mode=''
word=''
hidden_word=''
hint=''
rand=0
hintGiven=''
#Creating lists
Index=[]
hidden_word_list=[]
guessed=[]
... | Nazeefa-Anees/SimpleHangmanGame | Hangman/modules/game.py | game.py | py | 9,254 | python | en | code | 0 | github-code | 1 |
39376454288 | class Salary:
def __init__(self, name, monry):
self.name = name
self.money = monry
def __str__(self):
return self.name + ' ' + str(self.money)
def __add__(self, n):
self.money = self.money + n
if __name__ == '__main__':
s1 = Salary('Mary', 40000)
s2 = Salary('Jhon', ... | NaiNew/yzu_python1 | lesson07/OO_6.py | OO_6.py | py | 390 | python | en | code | 0 | github-code | 1 |
72241429155 | import csv
class InputExample(object):
def __init__(self, text_a, text_b=None, label=None):
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeature(object):
def __init__(self, input_ids, attention_mask, token_type_ids, label):
self.input_ids = input_id... | yangdechuan/toy-bert | utils.py | utils.py | py | 2,515 | python | en | code | 0 | github-code | 1 |
36447598427 | from tkinter import *
from tkinter import ttk as ttk
from tkinter import messagebox as mb
import datetime
import sqlite3
from tkcalendar import DateEntry
# list all the expenses
def listAllExpenses():
# global ... | cenjatwit/BudgetBudgetBudget | main.py | main.py | py | 16,173 | python | en | code | 0 | github-code | 1 |
4384097616 | import socket
# SERVER IP, PORT
IP = "192.168.0.195"
PORT = 8086
client = True # We create a while loop so the client keep asking the user for entering new values for new future connections once the server has finished the previous one
while client:
# Here we have created a menu to inform the user about the pr... | helenyaben/2018-19-PNE-practices | P3/client.py | client.py | py | 2,745 | python | en | code | 0 | github-code | 1 |
18700705323 | import numpy as np
import pandas as pd
from fit import transform_distribution
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn import feature_selection
from sklearn import model_selection
fro... | landon/MachineLearning | kaggle/preprocess.py | preprocess.py | py | 5,703 | python | en | code | 0 | github-code | 1 |
36655416891 | import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import KMeans
from skopt import gp_minimize
class ProcessMissingValues(BaseEstimator, TransformerMixin):
def __init__(self,
columns,
cat_columns,
type_columns='categor... | jonysalgado/Competition_Porto_Seguro | pipeline/pipeline_functions.py | pipeline_functions.py | py | 7,539 | python | en | code | 0 | github-code | 1 |
45238512961 | """
Created on Mar, 2021
@author: Morteza Moghaddassian
@Project: ECE1508 - NetSoft Course
"""
# paho is a client library to communicate with Mosquitto broker that implements MQTT V3.1.1
import paho.mqtt.client as paho
import time
from datetime import datetime
from multiprocessing import Process, Manager
import os
impo... | janenxiao/ECE1508-labs-code | lab7/subscriber.py | subscriber.py | py | 10,466 | python | en | code | 0 | github-code | 1 |
13337014695 | class ListNode:
def __init__ (self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def gcd(self, a, b):
while b:
a, b = b, a%b
return a
def insertGCDs(self,head):
"""
:type head: Optional[ListNode]
:rtype: Optional... | Hk669/DSA | algorithms/linkedlists/insertGCD.py | insertGCD.py | py | 706 | python | en | code | 0 | github-code | 1 |
30598209481 | import whisper
import numpy as np
class WhisperModel():
def __init__(self, model_type="large"):
print("loading whisper")
self.model = whisper.load_model(model_type, download_root="/app/model/whisper/")
self.language = 'en'
self.task = 'transcribe'
async def set_model_settings(s... | ricard-inho/live_translator | backend/app/model/whisper/model.py | model.py | py | 857 | python | en | code | 0 | github-code | 1 |
10528614349 | #!/user/bin/env python3
'''
* make `data_set`, dict object {index: data}
`data` is dict object, whose keys are:
* 'label' : `label_vector`, list object subset in [0,...,L-1]
* 'feature': `feature_vector`, dict object {coordinate index: value}
'''
class FileReader(object):
def __init__(self):
s... | snaka0213/Python-GPT | src/scripts/file_reader.py | file_reader.py | py | 1,407 | python | en | code | 0 | github-code | 1 |
24580224778 | #Machine Vision and Robotics Course Project
#Fire detection using Image Processing
#import modules
import cv2#Computer vision module for video capture and image processing
import numpy as np#Python numbers module for matrix manipulation
import time#time module to measure time for pauses
import winsound# windows sound m... | shrutivasave/Fire-Detection-With-Image-Processing | main.py | main.py | py | 2,106 | python | en | code | 2 | github-code | 1 |
35807394488 | import json
import os
import re
def read_json_file(file):
if os.path.isfile(file):
print(f'file {file}')
else:
exit()
log = json.load(open(file, 'r'))
return log
def flat_json_to_kv(an_object, key, kv_result, layer) -> object:
'''
:param key:
:param layer:
:param a... | stonelzhang/log_analytics | flat_json.py | flat_json.py | py | 1,165 | python | en | code | 0 | github-code | 1 |
15858709562 | ''' Inference for the DreamBooth model. '''
import os
import zipfile
import predictor
import runpod
from runpod.serverless.utils import download, upload, validator, rp_cleanup
MODEL = predictor.Predictor()
MODEL.setup()
def run(job):
'''
Run inference on the model.
input format:
{
"instanc... | sascha1337/serverless-workers | dreambooth-v1/infer.py | infer.py | py | 4,027 | python | en | code | null | github-code | 1 |
25090609331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from datetime import datetime
file_in = "RngStream.cpp funclass.cpp RngStreamSupp.cpp driverLTM_mpi_mod.cpp"
file_out = "mpi_ltm"
file_time = "ResultTime"
max_np = 6
max_ntest = 10
date = datetime.now().strftime('%d-%m-%Y')
hour = datetime.now().strftime('%H-%M... | ChristopherBric/CPD-Proyecto | P_CPD_MPI.py | P_CPD_MPI.py | py | 1,720 | python | en | code | 0 | github-code | 1 |
14089843475 | import imp
import time
import json
import uvicorn
from threading import Thread
from datetime import datetime
from kafka import KafkaProducer
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.config.settings import config
from app.config.docs import documentation_config
from app.c... | OrwellMonitoring/orwell-middleware | middleware/app/main.py | main.py | py | 5,265 | python | en | code | 0 | github-code | 1 |
35582790150 | import requests
from lxml import etree
def get_mhname():
try:
url = 'https://18comic.live/'
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
}
res = requests.get(url, headers=header... | yulate/AKA | api/cartoons/comic.py | comic.py | py | 3,229 | python | en | code | 1 | github-code | 1 |
8691258449 | from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
map = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r",... | songkuixi/LeetCode | Python/Letter Combinations of a Phone Number.py | Letter Combinations of a Phone Number.py | py | 754 | python | en | code | 1 | github-code | 1 |
12707933989 | from pathlib import Path
from libdotfiles.packages import has_installed, try_install
from libdotfiles.util import (
HOME_DIR,
PKG_DIR,
create_symlink,
distro_name,
run,
)
FZF_DIR = HOME_DIR / ".fzf"
if distro_name() == "arch":
try_install("fzf") # super opener
try_install("ripgrep") # s... | rr-/dotfiles | cfg/search/__main__.py | __main__.py | py | 1,157 | python | en | code | 16 | github-code | 1 |
45084585781 | import logging
import pickle
import sys
from pathlib import Path
from timeit import timeit
import pandas as pd
import yaml
from nyx_space.cosmic import Cosm, Orbit, Spacecraft, SrpConfig
from nyx_space.mission_design import (
Event,
SpacecraftDynamics,
StateParameter,
TrajectoryLoader,
propagate,
... | gwbres/nyx | tests/python/test_mission_design.py | test_mission_design.py | py | 11,201 | python | en | code | null | github-code | 1 |
35773694168 | TYPES = {
'double': float,
'float': float,
'int32': int,
'int64': int,
'uint32': int,
'uint64': int,
'sint32': int,
'sint64': int,
'fixed32': int,
'fixed64': int,
'sfixed32': int,
'sfixed64': int,
'bool': bool,
'string': str
}
WIRE_TYPES = {
'double': 1,
... | vtarasovaaa/protobuf | protobuf/typed.py | typed.py | py | 1,070 | python | en | code | 0 | github-code | 1 |
1281712623 | import random
import time
def search_lineal(list, objective):
match = False
for element in list: # O(n)
print(f"Iterable times {time.time()} ")
if element == objective:
match = True
print(f"Iterable times {time.time()} END")
break
return match
def main():
list_size = int(input("W... | dereksamuel/python-crud | busqueda_lineal.py | busqueda_lineal.py | py | 654 | python | en | code | 0 | github-code | 1 |
7371261819 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import networkx as nx
import torch
from torch.utils.data import Dataset
from dataloader import DataLoaderSubstructContext
from loader import graph_data_obj_to_nx, nx_to_graph_data_obj
class NewBioDataset(Dataset):
def __init__(self, l1, center):
... | melobio/Graphene | pretrain/new_dataloader/generate.py | generate.py | py | 3,385 | python | en | code | 4 | github-code | 1 |
4327023962 | import glob
list_files = glob.glob("C:\\Users\\nv.solomennikova\\Documents\\pythonProject\\p4ne\\Lab1.5\\config_files\\*.txt")
str = " ip address "
list_result = []
for fl in list_files:
with open (fl) as f:
for s in f:
if str in s:
pos = s.find(str)
res_s = s... | shpinatashan/p4ne | Lab1.5/Lab.py | Lab.py | py | 468 | python | en | code | 0 | github-code | 1 |
14297376983 | lst = []
N = int(input())
A = list(map(int, input().split()))
sum_A = sum(A)
for j in A:
if (sum_A-j) % 7 == 0:
lst.append(j)
if len (lst)==0:
print("-1")
else:
print(A.index(min(lst))) | sahusaurabh65/hackerearth | BasicProgramming/Its_Magic.py | Its_Magic.py | py | 205 | python | en | code | 0 | github-code | 1 |
14246232189 | # coding: utf-8
import pytest
import numpy as np
from imageio import imread
from AxonDeepSeg.data_management.data_augmentation import *
class TestCore(object):
def setup(self):
# Remember that the stop value in "arrange" is not included
x = np.arange(0, 16, dtype='uint8')
y = np.arange(0,... | sophie685/newfileplzworklord | test/data_management/test_data_augmentation.py | test_data_augmentation.py | py | 3,908 | python | en | code | 0 | github-code | 1 |
18962706021 |
import os
import hashlib
import re
import traceback
from loguru import logger
def printe(e):
print(e)
logger.error(e)
traceback.print_exc()
def is_decimal_or_comma(s):
pattern = r'^\d*\.?\d*$|^\d*[,]?\d*$'
return bool(re.match(pattern, s))
# ================对文件算MD5================
def md5(path... | Projmix/MomoTranslator | src/utils.py | utils.py | py | 1,115 | python | en | code | null | github-code | 1 |
26365139405 | def isPalindrome(x):
if x==x[::-1]:
return True
def solution(s):
answer=0
for i in range(len(s)): #0~6
for j in range(i+1,len(s)+1): #1~7
if isPalindrome(s[i:j]):
if answer < j - i:
answer = j - i
return answer
def is_Palindrom(s):
if ... | junho2000/ps | Python/programmers/가장긴팰린드롬.py | 가장긴팰린드롬.py | py | 637 | python | en | code | 0 | github-code | 1 |
38432786064 | import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import arc as arc
import numpy as np
import scipy.constants as consts
from scipy.stats import maxwell
import os, sys
from functools import partialmethod
###########################################################################################... | seba2390/Python-projects | LaserCooling/my_classes.py | my_classes.py | py | 18,809 | python | en | code | 0 | github-code | 1 |
38356239503 | import discountpy.shift_scanner as s
from discountpy.motif import *
from discountpy import encode
class MotifSpace:
""" MotifSpace: create the priority lookup table from which
priority/rank of each Motif can be accessed easily
"""
__slots__ = ('width', '_maxMotifs', 'scanner', 'byPriority', 'priori... | Umesh-JNU/DiscountPy | discountpy/motif_space.py | motif_space.py | py | 1,809 | python | en | code | 2 | github-code | 1 |
35835074666 | import os
import subprocess
from IPython.core.magic import register_cell_magic
from IPython.display import SVG
__title__ = "iplantuml"
__description__ = "Package which adds a PlantUML cell magic to IPython."
__uri__ = "https://github.com/jbn/iplantuml"
__doc__ = __description__ + " <" + __uri__ + ">"
__license__ = "M... | Ledenel/IPlantUML | iplantuml/__init__.py | __init__.py | py | 2,099 | python | en | code | null | github-code | 1 |
25161316064 | import cv2
from time import sleep
# Load the cascade
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# To use a single image as input
img = cv2.imread("testAI.jpg")
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect the faces
faces = fa... | cKaliban/DSP-Architecture-Lab | Python-WSL/lib/vidFace-stillimg.py | vidFace-stillimg.py | py | 573 | python | en | code | 0 | github-code | 1 |
22934181500 | '''
Template module that provides an user with privileges to read the CloudFormation
stack definition. You usually want such an user when doing advanced operations
with Metadata (i.e. using the cfn-init utils)
@author: David Losada Carballo <david@tuxpiper.com>
'''
from _context import stack
from cloudcast.template i... | tuxpiper/cloudcast | cloudcast/library/stack_user.py | stack_user.py | py | 931 | python | en | code | 4 | github-code | 1 |
8207152514 | import cmaps
import sys
sys.path.append("lib")
from Taylor_Draw import Figure4wrf
scale,dpi=10,180 #泰勒图的大小,dpi
title='泰勒图示意图' #图题
title_size,title_y=12,1.03 #标题大小以及高度
r_small, r_big, r_interval=0,1.6,0.25 #半径r的始末以及间隔
tick_size=8
rad_list=[0,0.2,0.4,0.6,0.7,0.8,0.85,0.9,0.95,0.99,1] #需要显示数值的主要R的值
minor... | Cat7102/WRF_post_processing_Scripts | draw_taylor.py | draw_taylor.py | py | 2,941 | python | en | code | 11 | github-code | 1 |
37637132484 | # A Python program to show different ways to create
# Counter
from collections import Counter
# With sequence of items
print(type(Counter([('k') * 2, 'B', 'A', 'B', 'C', 'A', 'B', 'B', 'A', 'C'])))
# with dictionary
print (Counter({'A':3, 'B':5, 'C':2}))
# with keyword arguments
print (Counter(A=3, B=5, C=2))
# Pyt... | mathekania/sum | venmachine/unpacking dict.py | unpacking dict.py | py | 877 | python | en | code | 0 | github-code | 1 |
36823429088 | #!/usr/bin/env python
# coding: utf-8
# In[64]:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error as mae
# In[65]:
data = pd.read_csv('/home/leon... | juvitus-soh/Data-Science | Concrete wall prediction/ML Catchup CA.py | ML Catchup CA.py | py | 1,417 | python | en | code | 0 | github-code | 1 |
35010637914 | from rest_framework import status
from rest_framework import exceptions
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from drf_yasg.utils import swagger_auto_schema
from apps.posts.models import Post, PostLike
class PostL... | Billionaire-Project/four_hours_service | apps/posts/views/post_like_id.py | post_like_id.py | py | 1,365 | python | en | code | 0 | github-code | 1 |
1372330657 | import pandas as pd
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def get... | helderrezende/agendamento_portugal | crawler.py | crawler.py | py | 4,429 | python | en | code | 0 | github-code | 1 |
11731956357 | import pickle
import argparse
import numpy as np
from keras.layers import Conv2D, Dense, Flatten, MaxPool2D, Dropout
from keras.layers import BatchNormalization, Activation, LeakyReLU
from keras.models import Model, Input, load_model
from keras.utils import to_categorical
from keras.callbacks import EarlyStopping, Mode... | hungchingliu/ML2018SPRING | final/src/method2/train_cnn.py | train_cnn.py | py | 4,592 | python | en | code | 0 | github-code | 1 |
72227770275 | # USAGE
# python scripts/crop-to-object.py -i images/output/uss-freedom-original.jpg
# import necessary packages
import argparse
import cv2
# construct the argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", type=str,
help="path to input image")
args = vars(ap.parse_args())
... | dmarcus-wire/image-data-pipeline | scripts/crop-to-object.py | crop-to-object.py | py | 659 | python | en | code | 0 | github-code | 1 |
9618296830 | from collections import Counter
mn = input()
m_n = mn.split(' ')
m = int(m_n[0])
n = int(m_n[1])
input_array = input()
input_array_list = input_array.split(' ')
input_array_set = set(input_array_list)
like_set = input()
input_like_set = set(like_set.split(' '))
dislike_set = input()
input_dislike_set = set(dislike_se... | hemantkgupta/Python3 | basics/genral_test.py | genral_test.py | py | 617 | python | en | code | 0 | github-code | 1 |
8971672116 | import io
import json
from dataclasses import dataclass
import avro
from avro.io import DatumWriter, DatumReader, BinaryDecoder
from kpong import PingPongMessage
from kpong.schema import PING_PONG_SCHEMA
def ping_pong_deserializer(message):
return deserializer(message, PING_PONG_SCHEMA, PingPongMessage.from_dic... | apmaros/kpong | src/kpong/serde.py | serde.py | py | 926 | python | en | code | 0 | github-code | 1 |
11191543330 | from __future__ import annotations
import logging
import click
import numpy as np
import vpype as vp
from .cli import cli
from .decorators import global_processor
try:
# noinspection PyUnresolvedReferences
import vpype_viewer
_vpype_viewer_ok = True
except ImportError: # pragma: no cover
_vpype_v... | abey79/vpype | vpype_cli/show.py | show.py | py | 8,379 | python | en | code | 618 | github-code | 1 |
10964870577 | #Oppgave3
def billett():
alder = int(input("Skriv inn alder på kjøperen."))
billettpris = 0
if alder <= 17:
billettpris = 30
elif alder > 17 and alder < 63:
billettpris = 50
elif alder >= 63:
billettpris = 35
print("Billetten din koster", billettpris, "kroner.")
billet... | john0605/IN1000 | Obligatorisk Innlevering 3/billettpris.py | billettpris.py | py | 472 | python | no | code | 0 | github-code | 1 |
28490365912 | import config
import pygame
import math
class static_shape_object:
def __init__(self, position, vertices) -> None:
''' vertices are relative to given position'''
self.vertices = vertices
self.position = position
self.colliding = False
self.color = config.DEFAULT_SHAPE_COLOR
... | XT60/Problem-with-collision-resolving-using-diagonals-method | shape.py | shape.py | py | 6,633 | python | en | code | 0 | github-code | 1 |
15098881405 | from flask import Blueprint, render_template, request, jsonify, session
import random, json
views = Blueprint(__name__, "views")
the_score = 0
board_data = []
hand_data = []
vowels = ['a', 'e', 'i', 'o', 'u']
# Define the letters with their corresponding values
letter_values = {
'a': 1, 'b': 3, 'c': 3, 'd': 2... | gsapoz/scrabble-py | views.py | views.py | py | 3,537 | python | en | code | 0 | github-code | 1 |
13005741374 | from glob import glob
import time
import os.path
import os
import numpy as np
from .utils import return_diff_structures, create_output_file
def check_structure(user: str,
session: str,
movement: str,
warping_paths: np.ndarray,
output_path... | xistva02/Classification-of-interpretation-differences | structure_checker/structure_checker.py | structure_checker.py | py | 4,734 | python | en | code | 0 | github-code | 1 |
31319847797 | from __future__ import print_function, division
import time
import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from torchnet.meter import ConfusionMeter
use_cuda = torch.cuda.is_available()
# Compute log sum exp in a numerically stable way for the forward algorithm
def... | jtang10/crf | utils.py | utils.py | py | 6,049 | python | en | code | 0 | github-code | 1 |
7729561847 | """
function that takes two nums as input and find the big of two nums
"""
#WRITE THE FUNCTION
def bigger(n1,n2):
if(n1>n2):
return n1
else:
return n2
#call the function
num1=10
num2=30
v1 = bigger(num1,num2)
print("bigger of {} and {} is {}".format(num1,num2,v1))
num1=80
num2=20
v2 = b... | murali-kotakonda/PythonProgs | PythonBasics1/basics/functions/Ex13.py | Ex13.py | py | 397 | python | en | code | 0 | github-code | 1 |
74072595552 | # completed DM-trajectory code with scattering added (in progress)
import numpy as np
import uproot_methods as urm
import matplotlib.pyplot as plt
# -------------------------DETECTOR GEOMETRY--------------------------------
# based on dimensions of DUNE detector -- sourced from TDR doc
# using scale of 12 x 14 x 58.2... | ethanrutledge/Macroscopic-Dark-Matter-Scattering-Simulation | Previous Scripts/trajectory-scattering-main.py | trajectory-scattering-main.py | py | 10,660 | python | en | code | 0 | github-code | 1 |
23901241876 | from datetime import datetime
from pyelasticsearch import ElasticSearch
from dbconnect import *
import argparse
import json
import os
es = ElasticSearch()
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--date", required = True, help = "date to index")
args = vars(ap.parse_args())
ad_mapping = {
'ad': {
... | cervere/scrapemall | es-exodus/indexer.py | indexer.py | py | 1,855 | python | en | code | 0 | github-code | 1 |
19416051550 | def isPalindrome(s: str):
left = 0
right = len(s) - 1
s = s.lower()
while left < right:
if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue
if s[left] != s[right]:
return False
... | shashilsravan/Programming | Programs/Valid Palindrome.py | Valid Palindrome.py | py | 425 | python | en | code | 0 | github-code | 1 |
17210184396 | import pandas as pd
from packaging import version
from typing import Union, List
is_deprecated_lexsorted_pandas = version.parse(pd.__version__) > version.parse("1.3.0")
def get_level_index(df: pd.DataFrame, level=Union[str, int]) -> int:
if isinstance(level, str):
try:
return df.index.names.... | SJTU-Quant/interpreters | src/dataset/utils.py | utils.py | py | 2,075 | python | en | code | 3 | github-code | 1 |
10299590444 | # Output all the prime multiplers of the given number and the degrees.
k = int(input())
A = []
for i in range(2, k + 1):
bool = True
if k % i == 0:
for j in range(2, i):
if i % j == 0:
bool = False
break
if bool == True: A.append(i)
print(A)
for i i... | lusineduryan/ACA_Python | Basics/Workshops/Workshop_3/Classwork_3_prime multipliers.py | Classwork_3_prime multipliers.py | py | 434 | python | en | code | 1 | github-code | 1 |
71734197474 | from requests import get
from bs4 import BeautifulSoup
def main():
res = get(
"https://medium.com/towards-data-science/the-5-basic-statistics-concepts-data-scientists-need-to-know-2c96740377ae"
)
soup = BeautifulSoup(res.content, "html.parser")
h1s = soup.find_all(name="h1", recursi... | tebohoxthapeli/20-python-projects | 18_web_scraper.py | 18_web_scraper.py | py | 438 | python | en | code | 0 | github-code | 1 |
42385272913 | from AutomationToolsLib import Logging, AutomationPreferences, SlackNotification
from datetime import date
from xml.etree import ElementTree
from sys import exit
try:
import requests
except:
print(
"The requests module is not installed. To install the request module, use the pip3 command: pip3 install ... | danengh/Python | Patch_Automation/jamfPatchPolicyUpdater.py | jamfPatchPolicyUpdater.py | py | 10,975 | python | en | code | 8 | github-code | 1 |
15576418274 | class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
start_n = 0
end_n = len(matrix) - 1
start_m = 0
end_m = len(matrix[0]) - 1 if len(matrix) > 0 else - 1
result = []
while sta... | quetzaluz/codesnippets | python/leetcode/spiral-matrix.py | spiral-matrix.py | py | 1,137 | python | en | code | 0 | github-code | 1 |
11782638726 | import os
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
f = open(os.path.join(__location__, 'input.txt'))
abc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
sum = 0
for line in f:
shared = []
line = line.rstrip()
print(f"\n{line}")
n = len(line... | eipiguy/adventofcode | 2022/3/3_1.py | 3_1.py | py | 736 | python | en | code | 0 | github-code | 1 |
21340445362 | '''
130. Surrounded Regions
Medium
1297
576
Add to List
Share
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the boa... | kannanParamasivam/datastructures_and_algorithm | graph/problems/130_surrounded_regions.py | 130_surrounded_regions.py | py | 2,854 | python | en | code | 1 | github-code | 1 |
17790562559 | from plyer import notification
from rich.table import Table
from rich import print
from datetime import time
from config.config import *
from requests import get
import json
import os
import rich
import psutil
import platform
import pyaudio
import pyttsx3
import datetime
import requests
import random
import requests
... | wendellast/Sara-IA-QT | config/config_dados.py | config_dados.py | py | 9,261 | python | pt | code | 4 | github-code | 1 |
41330435237 | """migration_1
Revision ID: ccba048477df
Revises:
Create Date: 2022-11-05 09:54:52.229725
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'ccba048477df'
down_revision = None
branch_labels = None
depends_on = None
def... | zxc322/fast_api_app | alembic/versions/ccba048477df_migration_1.py | ccba048477df_migration_1.py | py | 879 | python | en | code | 0 | github-code | 1 |
72399313954 |
import unittest
import sys
import os
sys.path.append("../")
sys.path.append("../../")
from job_visualization import FileIndex, DepExtractor
test_data = 'test/test_call_graph/test_data/'
class TestGetIncludes(unittest.TestCase):
def setUp(self):
self.file_index = FileIndex(test_data)
self.file_... | OSLL/jabba | jabba/test/test_dep_extractor/test_get_includes.py | test_get_includes.py | py | 784 | python | en | code | 2 | github-code | 1 |
28568908531 | a = list(map(int, input().split()))
max_pos = 0
min_pos = a[0]
for elem in a:
if elem > 0 and elem % 2 == 0:
if max_pos < elem: max_pos = elem
if min_pos > elem: min_pos = elem
if max_pos == 0:
print('Нет четных положительных')
else:
print(f'Максимальный четный положительный {max_pos}')
... | danfimov/work-projects | 2784354/1.7/1.py | 1.py | py | 457 | python | ru | code | 0 | github-code | 1 |
37084697848 | #!/usr/bin/python3
"""
Defines a Square Class
"""
class Square:
"""
A Class called Square with an attribute:
size: the size of the Square.
"""
def __init__(self, size=0, position=(0, 0)):
"""
Instantiated with size.
"""
self.size = size
self.position = posit... | jsjimenez51/holbertonschool-higher_level_programming | 0x06-python-classes/6-square.py | 6-square.py | py | 1,942 | python | en | code | 0 | github-code | 1 |
38266638212 | import numpy as np
from itertools import combinations
from math import *
import pdb
file = open('tsp.txt', 'r+')
i = -1
for line in file:
if i == -1:
n = int(line.rstrip('\t'))
coor = np.empty((n, 2))
i += 1
else:
[x, y] = line.rstrip('\t').split(' ')
coor[i][:] = np.arr... | Qiaochu-Song/Algorithms | Section_4_NP/Algorithm_4.2.py | Algorithm_4.2.py | py | 3,258 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.