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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2598741828 | from git import Repo
import os, shutil
import pathlib
repos = ["C:/Users/jrami/VSCodeProjects/JoseRamirez", "C:/Users/jrami/VSCodeProjects/AlannaPasco"]
for repo_dir in repos:
repo = Repo(repo_dir)
readme_file = "C:/Users/jrami/VSCodeProjects/RHS_Helper_Scripts/README.md"
readme_filename = pathlib.Path(rea... | jramirez857/RHS_Helper_Scripts | push_file.py | push_file.py | py | 763 | python | en | code | 0 | github-code | 1 |
17011622040 | t=int(input())
while(t>0):
t-=1
n=int(input())
if(n<100):
print(n%10)
else:
m=n%10
while(n>0):
a=n%10
if(a<m):
m=a
n=n//10
print(m) | AnshikSahu/codeforces | cfA.py | cfA.py | py | 231 | python | ja | code | 0 | github-code | 1 |
3667530119 | from email.mime import image
import cv2
import numpy as np
from PIL import Image as image
def scaleImage(array : np.ndarray,old_wdith: int,old_height: int,new_width: int,new_height :int):
newarr = np.split(ary= array,indices_or_sections=[3,1],axis=2)
# split rgb and alpha
# opencv need GBk ,... | 1641585051/UVTexture | tools/uv_cv_tools.py | uv_cv_tools.py | py | 1,341 | python | en | code | 1 | github-code | 1 |
17971373698 | from controller import controller
from uartCommunication import MlinkCommunication
import time
if __name__ == "__main__":
print("starting program")
print("initializing")
mlink = MlinkCommunication(port = "COM9") # idk change if wrong
mlink.sendResetMessage()
mlink.readMessage()
mlink.sendStart... | JulianPinto/Tatsy | desktopApp/Controls/roverMain.py | roverMain.py | py | 689 | python | en | code | 0 | github-code | 1 |
4719188304 | import requests
import os
from twilio.rest import Client
API_KEY = os.environ["API_OWN"]
LAT = 19.432680
LONG = -99.134209
ENDPOINT = "https://api.openweathermap.org/data/2.5/onecall"
account_sid = "ACd913eab39082ec0af0593f7f6f8a4252"
auth_token = os.environ["AUTH_TOKEN"]
parameters = {
"lat": LAT,
... | tomagent/python-playground | twilio_bot.py | twilio_bot.py | py | 1,073 | python | en | code | 0 | github-code | 1 |
1420645747 | """Diagnose the feature model."""
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
class STATS(object):
"""Mesh object."""
def __init__(self, fname='xxx'):
"""
Init the MESH2D.
fname: str, filename of xxx_Species.csv.
"""
# s... | buckees/Langmuir | packages/Model/Feature2D/Feature2D_stats.py | Feature2D_stats.py | py | 3,441 | python | en | code | 0 | github-code | 1 |
18669463565 | import random
def quick_sort(array, Lb, Ub):
if Lb<=Ub:
pivot = create_pivot(array, Lb, Ub)
print(pivot)
quick_sort(array, Lb, pivot-1)
quick_sort(array, pivot+1, Ub)
def create_pivot(array,Lb,Ub):
pivot=random.randint(Lb,Ub)
array[Lb],array[pivot]=array[pivot],array[Lb]
... | kushagrapatidar/Competitive-Coding | Examples/quicksort.py | quicksort.py | py | 922 | python | en | code | 0 | github-code | 1 |
11651554942 | #!/usr/bin/python3
"""
DESCRIPTION:
Template code for the SECOND Advanced Question of the Hidden Markov Models
assignment in the Algorithms in Sequence Analysis course at the VU.
INSTRUCTIONS:
Complete the code (compatible with Python 3!) upload to CodeGrade via
corresponding Canvas assignment. Note t... | violehtone/HMM | advanced/viterbi_training.py | viterbi_training.py | py | 4,025 | python | en | code | 1 | github-code | 1 |
13786554227 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 10 16:32:02 2022
@author: Metehan
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
resim=cv2.imread("araba.png")
plt.imshow(resim)
plt.show()
cv2.imshow("orjinal",resim)
print(resim.shape)
yükseklik,genişlik,kanal=resim.shape
... | MetehanYildiz25/ImageProcessing | Görüntü İşleme/4_farkli_renkte_foto.py | 4_farkli_renkte_foto.py | py | 991 | python | tr | code | 0 | github-code | 1 |
13610057864 | import json
from asyncio import sleep
from contextlib import asynccontextmanager
from logging import getLogger
from os import remove
from pathlib import Path
import aiofiles
import aiohttp
from aiogram import Bot
from aiogram.types import Downloadable
from ..settings import get_settings
logger = getLogger("tools.fil... | Ramnck/stats_bot | app/src/tools/file_manager.py | file_manager.py | py | 2,348 | python | en | code | 0 | github-code | 1 |
27287405984 | import random
class Vector():
"""Programatic representation of vectors from linear algebra
Attributes
----------
dim : int
length of the vector
data : array
vector corrdiantes
Methods
-------
initalize(dim=2)
this method's description
randomize(vec)
... | Farooq-azam-khan/preceptron-learning-algorithm | src/vector/vector.py | vector.py | py | 3,735 | python | en | code | 0 | github-code | 1 |
7188099724 | ## pattern 1
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end="")
print()
## pattern 2
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(i, end="")
print()
## pattern 3
n =... | raushankcse/pythonbasics | loops1.py | loops1.py | py | 5,047 | python | en | code | 0 | github-code | 1 |
21002769573 | import re
from common.db import models
from django.conf import settings
from protobufs.services.file import containers_pb2 as file_containers
import service.control
def _safe_int(value):
if value is not None:
return int(value)
class File(models.UUIDModel, models.TimestampableModel):
as_dict_value_... | getcircle/services | file/models.py | models.py | py | 2,507 | python | en | code | 0 | github-code | 1 |
13923281365 | import csv
import re
os_prod_list = []
os_name_list = []
os_code_list = []
os_type_list = []
main_data = [['Изготовитель системы', 'Название ОС', 'Код продукта', 'Тип системы']]
def get_data():
for i in range(1, 4):
filename = f'info_{i}.txt'
with open(filename) as f:
data = f.read()
... | AndreKozlov96/GB_New-Chat | hometask_2/task_01.py | task_01.py | py | 1,440 | python | en | code | 0 | github-code | 1 |
20843298303 | #!/usr/bin/env python3
from __future__ import print_function
from bcc import BPF, USDT
import argparse
import ctypes as ct
import time
import os
import io
import ipaddress
import socket
from collections import defaultdict
# globals
SYSCALLS = ["socket", "socketpair", "bind", "listen", "accept", "accept4",
... | factorysh/PHP-tracing-tool | php_tool.py | php_tool.py | py | 18,131 | python | en | code | 29 | github-code | 1 |
4341262058 | # Databricks notebook source
# MAGIC %pip install pdfplumber
# MAGIC %pip install psycopg2-binary==2.9.5
# MAGIC %pip install sqlalchemy
# COMMAND ----------
containerName = "landing"
storageAccountName = "sharifstdataplatform"
sas = "?sv=2022-11-02&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2023-07-05T11:28:04Z&st=2023-07-... | shxr3f/DatabricksScripts | ges/test.py | test.py | py | 4,220 | python | en | code | 0 | github-code | 1 |
72253715234 | from wikiCat.data.data import Data
from wikiCat.processor.gt_graph_generator import GtGraphGenerator
from wikiCat.processor.gt_sub_graph_processor import SubGraphProcessor
from wikiCat.selector.selector_sub_graph import SubGraph
from wikiCat.selector.selector_snapshots import Snapshots
from wikiCat.selector.selector_cs... | bumatic/wikiCat | wikiCat/data/wikigraph.py | wikigraph.py | py | 9,100 | python | en | code | 0 | github-code | 1 |
25991320866 | # Function is a group of related statements that perform a specific task.
# Syntax :
'''
def function_name(parameters):
"""docstring"""
statement(s)
'''
# Funtion to add two numbers :
# Predefined
def addNumbers() :
result = 10 + 20
return result
# Add any two numbers :
def addAnyNumbers(x,y):
result = ... | srinibasbiswal/Hands-On-Python | functions_and_arguments/functions.py | functions.py | py | 578 | python | en | code | 6 | github-code | 1 |
18323895505 | def merge(A, B):
C = []
i = k = 0
while i < len(A) and k < len(B):
if A[i] <= B[k]:
C.append(A[i])
i += 1
else:
C.append(B[k])
k += 1
while i < len(A):
C.append(A[i])
i += 1
while k < len(B):
C.append(B[k])
... | akasht73/Test_from_SPb | merge_sort.py | merge_sort.py | py | 655 | python | en | code | 0 | github-code | 1 |
22651481501 | import random # for random module
# Global variable Player Stats
global health
global strength
global magic
global luck
health = 5
strength = 5
magic = 5
luck = 5 # Invisible Stat
# Frequently Reused Functions
def stats(): # prints stats
print(f"Your Stats \nHealth: {health} \nStrength: {strength} \nMagic: {ma... | jtrieu1992/Adventure | main.py | main.py | py | 41,588 | python | en | code | 0 | github-code | 1 |
17325736029 | k = int(input())
word = input()
decode = ""
for i in range(len(word)):
shift = 3 * (i + 1) + k
pos = ord(word[i]) - ord('A') - shift
while pos < 0:
pos += 26
decode += chr(ord('A') + pos)
print(decode)
| angelren1220/CCC | CCC_12_J4.py | CCC_12_J4.py | py | 226 | python | en | code | 0 | github-code | 1 |
70717520675 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 12:28:28 2018
@author: XPS 13 9350
"""
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
length=len(height)
if length<=2:
return 0
top=height.index(max(height))
... | yyyyyykkk/Algorithms-and-Data-Structures | LeetCode/Trapping Rain Water.py | Trapping Rain Water.py | py | 1,743 | python | en | code | 0 | github-code | 1 |
1706993556 | from sqlalchemy import CHAR, ForeignKey, String
from sqlalchemy.orm import relationship
from giges.db import db
from giges.models.mixins import UUIDMixin
class Ritual(db.Model, UUIDMixin):
name = db.Column(
String,
nullable=False,
unique=True,
index=True,
doc="Name of the... | tesselo/giges | giges/models/ritual.py | ritual.py | py | 883 | python | en | code | 0 | github-code | 1 |
408554590 | from models import db, Ingredient, Restaurant, Dish, Rating
import peewee
import sqlite3
def data_test():
db.connect()
return db.create_tables([Ingredient, Restaurant, Dish, Rating])
def data_writer():
db.connect()
restaurants = [["Vilacidro", 1992, "16:00", "23:00"], ["Zaika", 2005, "14:00", "23:... | lindavos-dot/hello_world | peewee-orm/making_data.py | making_data.py | py | 2,012 | python | en | code | 0 | github-code | 1 |
23273915225 | from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication, QWidget,
QHBoxLayout, QVBoxLayout,
QGroupBox, QButtonGroup, QRadioButton,
QPushButton, QLabel)
from random import shuffle, randint
class Question():
def __init__(self, question, right_answer, wrong1... | Sashapavl/MemoryCard | MemoryCard.py | MemoryCard.py | py | 8,000 | python | ru | code | 0 | github-code | 1 |
40785965866 | from typing import Any, Dict
from app.app import db
Model: Any = db.Model
class Camera(Model):
__tablename__ = 'cameras'
Name = db.Column(db.String(10), unique=True)
images = db.relationship('Image', backref='camera', lazy=True)
@classmethod
def from_dict(cls, camera_dict: Dict[s... | percurnicus/opportunity | app/app/models.py | models.py | py | 3,649 | python | en | code | 0 | github-code | 1 |
4848886573 | import subprocess
import tator
def test_video_clips(host, token, project, video):
# Run the example.
cmd = [
'python3',
'examples/video_clips.py',
'--host', host,
'--token', token,
'--video_id', str(video),
'--file_path', '/tmp/asdf',
]
subprocess.run(c... | cvisionai/tator-py | test/examples/test_video_clips.py | test_video_clips.py | py | 337 | python | en | code | 4 | github-code | 1 |
73571817314 | # random agent on Taxi-v2
import gym
env = gym.make("Taxi-v2")
P = env.env.P
# P[s][a] contains array of tuples.
# each of them is in form of (p, next_s, r, done)
# where "p" is the transition probability of
# going from "s" to "next_s" with action "a" getting "r" reward;
# "done" denotes whether the episode is finis... | Alef125/AI_and_Learning | AI/AI_HW4/Taxi.py | Taxi.py | py | 1,134 | python | en | code | 0 | github-code | 1 |
39481078969 | import os
import tweepy
def get():
with open(os.path.join(os.path.dirname(__file__), "template.html")) as f:
return f.read()
def post(screen_name=""):
CK = os.getenv("TW_CK")
CS = os.getenv("TW_CS")
AT = os.getenv("TW_AT")
AS = os.getenv("TW_AS")
auth = tweepy.OAuthHandler(CK, CS)
... | laddge/myapi | tw_sn2id/__init__.py | __init__.py | py | 745 | python | en | code | 1 | github-code | 1 |
11910532003 | from flask import jsonify, request
from app.models import Pharmaceutical_info, Token
from app import db
def updatePharmaceuticalInfo():
'''update pharmaceutical info record'''
data = request.get_json()
token = request.headers['TOKEN']
id=int(data['id'])
t=Token.query.filter_by(token=token).fi... | the1Prince/drug_repo | app/updates/updatePharmaceuticalInfo.py | updatePharmaceuticalInfo.py | py | 1,655 | python | en | code | 0 | github-code | 1 |
31602808719 | import numpy as np
import cv2
from matplotlib import pyplot as plt
import random
from PIL import Image
img = Image.open('original.jpg')
img1 = cv2.imread('original.jpg')
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
h, w, _ = img1.shape
print('width: ', w)
print('height:', h)
count = 0
w1 = w2 = int(w/20)
h1 = h2 = ... | XYZ121212/issre2020 | deadpixel200.py | deadpixel200.py | py | 919 | python | en | code | 0 | github-code | 1 |
18404151650 | #!/usr/bin/env python3
import csv
import glob
import os
import json
us_states_and_territories = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
... | llimllib/covidgraph | etl.py | etl.py | py | 4,851 | python | en | code | 4 | github-code | 1 |
4523232392 | import datetime
name = str(input('Name: '))
c = int(input('Age: '))
e = int(input("Number: "))
def years(age):
d = datetime.date.today().year
a = d+(100-c)
for i in range(e):
print("You're gonna be 100 yrs old the year:", a)
return(a)
def main():
return
if __name__ == '__main__':
... | gezdank/Pair-programming-excercises | years_module.py | years_module.py | py | 577 | python | en | code | 0 | github-code | 1 |
12631392820 | #!/usr/bin/env python
from brownie import accounts,SimpleStorage
def test_deploy():
# Arrage
account = accounts[0]
# Act
simple_storage = SimpleStorage.deploy({"from":account})
starting_value = simple_storage.get()
excepted = 777
# Assert
assert excepted == starting_value | 0x0OZ/smart_contracts | simple_storage/tests/test_simple_storage.py | test_simple_storage.py | py | 305 | python | en | code | 0 | github-code | 1 |
73033759393 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
from salt.utils import parsers
from salt.utils.verify import verify_env, verify_files
from salt.config import _expand_glob_path
import salt.cli.caller
class SaltCall(parsers.SaltCallOptionParser):
'''
... | shineforever/ops | salt/salt/cli/call.py | call.py | py | 2,215 | python | en | code | 9 | github-code | 1 |
25506044771 | #!/usr/bin/env python3
import unittest
from vec2 import Vec2
from person import Person
from unittest.mock import patch
class TestVec2(unittest.TestCase):
def test_add(self):
a = Vec2(5, 3)
a.add(Vec2(3, 7))
self.assertEqual(a.x, 8)
self.assertEqual(a.y, 10)
def test_scale(self)... | MarcoMeijer/cicd-example | test.py | test.py | py | 1,439 | python | en | code | 0 | github-code | 1 |
22942264952 | import json
import logging
import os
from typing import Dict
import lib.configs
from lib.activelearning import Last
from lib.infers.deepgrow_pipeline import InferDeepgrowPipeline
from lib.infers.vertebra_pipeline import InferVertebraPipeline
import monailabel
from monailabel.interfaces.app import MONAILabelApp
from m... | Project-MONAI/MONAILabel | sample-apps/radiology/main.py | main.py | py | 13,473 | python | en | code | 472 | github-code | 1 |
22863614907 | from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class MrpProduction(models.Model):
_inherit = "mrp.production"
def _default_mo_type_id(self):
return self.env["manufacturing.order.type"].search(
["|", ("company_id", "=", False), ("company_id", "=", self.... | ecosoft-odoo/esb | auto-addons/manufacturing_order_type/models/mrp_production.py | mrp_production.py | py | 1,856 | python | en | code | 2 | github-code | 1 |
26569116724 | from flask_restful import Resource, reqparse
from flask_jwt_extended import (
jwt_required,
jwt_optional,
get_jwt_claims,
get_jwt_identity,
fresh_jwt_required
)
from model import Item, Store
class ItemResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument(
'pric... | basurohan/flaskjwtextended | resource/item_resource.py | item_resource.py | py | 2,550 | python | en | code | 0 | github-code | 1 |
7029239081 | import asyncio
import dbus_next
from dbus_next.aio import MessageBus
import socket
import enum
import logging
import common
class BtConnectionRole(enum.Enum):
Master = 1
Slave = 2
NotConnected = 3
class BtClient(object):
BT_CONTROL_PORT = 17 # Service port - control port specified in the bluetooth HI... | BLeeEZ/rpi-kvm | rpi_kvm/bt_client.py | bt_client.py | py | 9,585 | python | en | code | 27 | github-code | 1 |
30422431342 | import c_a_parameters_bible as pb
import sqlite3
from sqlite3 import Error
conn = sqlite3.connect(pb.BIBLE_ID + '/f_c_db_'+pb.BIBLE_ID+'.sqlite')
cur = conn.cursor()
cur.execute(''' SELECT book,token, count(*) as 'count' FROM wordtokens GROUP BY book,token ORDER by 1,3 desc; ''')
old_book = ""
token_count = 0
line = ... | murillocjr/theophilusnlp | bible/f_e_print_word_frequency_by_book.py | f_e_print_word_frequency_by_book.py | py | 613 | python | en | code | 2 | github-code | 1 |
73152353635 | """
credit to https://github.com/PredatH0r/XonStat/blob/master/xonstat/elo.py .
ELO algorithm to calculate player ranks
"""
from datetime import datetime
import logging
import math
from botocore.exceptions import ClientError
import json
import boto3
from collections import namedtuple
import time as _time
log_level =... | donkz/rtcwprostats | lambdas/postprocessing/elo/elo_calc.py | elo_calc.py | py | 21,386 | python | en | code | 2 | github-code | 1 |
17617060348 | import json
with open("pokemons.json") as file:
pokemons = json.load(file)["results"]
# ACESSAR UMA CHAVE
# print(pokemons[0]["evolution"])
grass_type_pokemons = [
pokemon for pokemon in pokemons if "Grass" in pokemon["type"]
]
with open("grass_pokemons.json", "w") as file:
# json.dumps joga numa variav... | ricardorosa-dev/Curso-Trybe | 35.2_entrada_saida_arq/json_escrita.py | json_escrita.py | py | 523 | python | en | code | 0 | github-code | 1 |
27723118556 | import django_filters
from django_filters import CharFilter
from .models import *
class OrderFilter(django_filters.FilterSet):
note = CharFilter(field_name='nome', lookup_expr='icontains')
class Meta:
model = Pescado
fields = '__all__'
exclude = ['nome']
class UsuarioFilter(django_fil... | sergioroberto15/Pescaria_Django | accounts/filters.py | filters.py | py | 740 | python | en | code | 0 | github-code | 1 |
71786006115 | from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import Http404
from django.shortcuts import render
from .models import Movie
# data = {
# 'movies': [
# {
# 'id': 5,
# 'title': 'Jaws',
# 'year': 1669,
# },
# ... | anmolbansal7/django-init | movies/views.py | views.py | py | 1,362 | python | en | code | 0 | github-code | 1 |
11397140123 | from soc import debug_messages
from playing import get_all_messages
from collections import Counter
from edtext import clean
from more_itertools import unique_everseen
import json
def main():
messages_json = get_all_messages()
start = 3 * 1500
finish = start + 1500
messages_chunk = messages_... | komap2017/soc | debug.py | debug.py | py | 1,075 | python | en | code | 0 | github-code | 1 |
73111178594 | # -*- coding: utf-8 -*-
import scrapy
import time
from scrapy.http import Request
from loguru import logger
from urllib.parse import urljoin
from SafetyInformation.items import SafeInfoItem
from SafetyInformation.settings import SLEEP_TIME, TOTAL_PAGES
class Myhack58Spider(scrapy.Spider):
name = 'myhack58'
a... | Silentsoul04/SafetyInformation | SafetyInformation/spiders/myhack58.py | myhack58.py | py | 2,133 | python | en | code | 0 | github-code | 1 |
34232663100 | import numpy as np
def Euclidean(point1,point2):
distance = np.sqrt(np.sum(np.square(point1-point2)))
return distance
def assign_clusters(data, cluster_centers):
"""
Assigns every data point to its closest (in terms of Euclidean distance) cluster center.
:param data: An (N, D) shaped numpy array w... | mustafa-aygun/basic-machine-learning-algorithms-with-python | k-means/kmeans.py | kmeans.py | py | 3,543 | python | en | code | 0 | github-code | 1 |
4238972114 | class OrderedStream:
def __init__(self, n: int):
self.data = [None] * n
self.ptr = 0
def insert(self, idKey: int, value: str) -> List[str]:
self.data[idKey - 1] = value
res = []
if (idKey - 1) == self.ptr:
for i in range(self.ptr, len(self.data)):
... | allkong/LeetCode | 1656-design-an-ordered-stream/1656-design-an-ordered-stream.py | 1656-design-an-ordered-stream.py | py | 480 | python | en | code | 1 | github-code | 1 |
28233637616 | from math import sqrt
def divisor(n) :
i = 2
ans = []
while i <= sqrt(n):
if (n % i == 0) :
if (n // i == i) :
ans.append(i)
else :
ans.append(i)
ans.append(n//i)
i = i + 1
return ans
square = []
for i in range(2, ... | vishalagrawalit/50Tasks | TCS_Codevita/B.py | B.py | py | 690 | python | en | code | 3 | github-code | 1 |
3142224224 | ######################################################################
# File: retrieval_model.py
# Author: Vishal Dey
# Created on: 11 Dec 2019
#######################################################################
'''
Synopsis: Create w2v for corresponding string description of each problem
Reads in pretrianed Wor... | Phybiolo57/MathWordProblemSolver | 3_T-RNN_&_baselines/src/retrieval_model.py | retrieval_model.py | py | 5,525 | python | en | code | 18 | github-code | 1 |
16073390395 | from wall import views
from django.urls import path
urlpatterns = [
path('deer/',views.deerList.as_view(), name='deerlist'),
path('realwreath/',views.RealWreathView.as_view(), name ="realwreathview"),
path('ornament/',views.OrnamentView.as_view(), name ='ornament_list'),
path('solvequestion/',views.SolveQuestion.... | MinJae00/santa-back_distribute | wall/urls.py | urls.py | py | 481 | python | en | code | 0 | github-code | 1 |
9396199673 | from nltk.corpus import stopwords
from tensorflow.keras.preprocessing.text import Tokenizer
import gensim
import pandas as pd
from preprocess import process_text_data
from utils import load_epub
from word2vec import Word2Vec
def remove_stopword(book):
corpus = list()
stopword = stopwords.words('english')
... | dhsong95/the-catcher-in-the-rye | question3.py | question3.py | py | 2,342 | python | en | code | 0 | github-code | 1 |
25562473076 | """
File: expo.py
Project 3.4
Defines a function to raise a number to a given power.
Uses a recursive strategy to reduce the complexity to O(log n).
"""
def expo(base, exponent):
"""Raises base to exponent."""
if exponent == 0:
return 1
elif exponent % 2 == 1:
return base * expo(base, expo... | hieugomeister/ASU | CST100/Chapter_3/Chapter_3/Ch_3_Solutions/Ch_3_Projects/3.4/expo.py | expo.py | py | 579 | python | en | code | 0 | github-code | 1 |
27271986726 | # 실버 1
# 14716. 현수막
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
mtx = [list(map(int, input().split())) for _ in range(n)]
q = deque()
dx = [-1, 0, 1, 0, -1, 1, -1, 1]
dy = [0, -1, 0, 1, -1, 1, 1, -1]
def bfs(i, j):
q.append([i, j])
mtx[i][j] = 0
... | honggom/TIL | problem-solving/baekjoon/graph/14716-bfs.py | 14716-bfs.py | py | 722 | python | en | code | 0 | github-code | 1 |
25337349664 | import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
# Задаем цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Создаем игру и окно
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Star De... | anvartdinovtimurlinux/Star_Defender | game.py | game.py | py | 2,775 | python | en | code | 0 | github-code | 1 |
1499177429 | #!/usr/bin/env python3
# dpw@plaza.localdomain
# 2023-07-29 22:24:28
from gtts import gTTS
def say(text, fname):
tts = gTTS(text)
tts.save(fname)
if __name__ == "__main__":
fname = "tts.mp3"
tts = gTTS(
"this is a test; a, rather long test; of text 2 speach", lang="en", tld="ca"
)
t... | darrylwest/python-play | utils/text-to-speach.py | text-to-speach.py | py | 335 | python | en | code | 0 | github-code | 1 |
41201990332 | def solution(A):
A.sort()
n = len(A)
product1 = A[n - 1] * A[n - 2] * A[n - 3]
product2 = A[0] * A[1] * A[n - 1]
product3 = A[n - 1] * A[n - 2] * A[n - 3]
return max(product1, product2, product3)
A = [-3, 1, 2, -2, 5, 6]
result = solution(A)
print(result)
| Kamente/kata | maxproductofthree.py | maxproductofthree.py | py | 286 | python | en | code | 0 | github-code | 1 |
2960278008 | from astropy.io import fits
import numpy as np
import astropy.units as u
from agpy import cubes
from FITS_tools import cube_regrid
import agpy
#f2 = fits.open('H2CO_22_speccube.fits')
dpath = '/Volumes/128gbdisk/w51/'
#f2 = fits.open('Darray_H2CO_22_speccube_uniform_contsub_justspw19.image.fits')
f2 = fits.open(dpath+... | keflavich/w51evlareductionscripts | make_taucube_vla_ku_bd_22.py | make_taucube_vla_ku_bd_22.py | py | 2,920 | python | en | code | 0 | github-code | 1 |
39441347670 | from flask import Flask, render_template, request, redirect
from models import db, EmployeeModel
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
@app.before_first_request
def create_table():
db.create_all()
... | reinisdreska/flask-crud | app.py | app.py | py | 2,578 | python | en | code | 0 | github-code | 1 |
18598471871 | import board
import audioio
import audiobusio
import digitalio
import time
import array
import math
buf = bytearray(8000)
print(3)
time.sleep(1)
print(2)
time.sleep(1)
print(1)
time.sleep(1)
print("recording", time.monotonic())
trigger = digitalio.DigitalInOut(board.A1)
trigger.switch_to_output(value = True)
with aud... | notionparallax/sensicorn | indoorSoftware/CircuitPython/recordThenPlay.py | recordThenPlay.py | py | 1,234 | python | en | code | 1 | github-code | 1 |
16557493555 | # https://www.acmicpc.net/problem/10815
# Solved Date: 20.05.21.
import sys
read = sys.stdin.readline
def search(cards, number):
left = 0
right = len(cards) - 1
while left < right:
mid = (left + right) // 2
if cards[mid] < number:
left = mid + 1
else:
right... | imn00133/algorithm | BaekJoonOnlineJudge/CodePlus/800DivideAndConquer/Main/baekjoon_10815.py | baekjoon_10815.py | py | 1,252 | python | en | code | 0 | github-code | 1 |
16264945290 | ''' Chapter 5.11 '''
numberOfStudents = int(input("Enter number of students: "))
highScore = 0
secondHighestScore = 0
for i in range(0, numberOfStudents):
currentScore = int(input("Enter score: "));
if(highScore == 0):
highScore = currentScore;
if(currentScore > highScore):
secondHighest... | JMCSci/Introduction-to-Programming-Using-Python | Chapter 5/5.11/highscore/HighScore.py | HighScore.py | py | 485 | python | en | code | 0 | github-code | 1 |
74269632994 | """
Title : find_short.py
Source : Module 1 Remed Purwadhika no.1
Summary : Buatlah suatu fungsi yang mengembalikan panjang terpendek dari suatu string kata
yang terpisahkan oleh spasi (20 Point)
Feat Req : Note: Kembalikan panjang dari kata yang terpendek, bukan kata... | laksonodimitrij/Remedial-Modul-1 | Remed_01_find_short.py | Remed_01_find_short.py | py | 839 | python | id | code | 0 | github-code | 1 |
30267363694 | import json
import time
import psycopg
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from pgvector.psycopg import register_vector
from chatgpt import chatgpt_api
from ny_times import times_api
connection_string = ''
start_date = date(2020, 5, 27)
end_date = date(2000, 1, 1)
de... | TheItCrOw/VecTop | src/embedder/times_embedder.py | times_embedder.py | py | 4,512 | python | en | code | 0 | github-code | 1 |
32067083979 | import pathlib
import sys
import xml.etree.ElementTree as ET
from typing import Final
NAMESPACES: Final[dict[str, str]] = {
"": "http://www.w3.org/2000/svg",
"xlink": "http://www.w3.org/1999/xlink",
}
for prefix, uri in NAMESPACES.items():
ET.register_namespace(prefix, uri)
def urlize(s: str) -> str:
... | rpetchler/galant-schemata | src/postprocess/scores.py | scores.py | py | 1,249 | python | en | code | 0 | github-code | 1 |
5638412335 | from collections import deque
import numpy as np
import torch
import logging
logger = logging.getLogger(__name__)
def cem(agent, params):
"""PyTorch implementation of a cross-entropy method.
Params
======
agent (object) --- the agent to train
params (dict) --- a dictionar of pa... | dahlem/deep-reinforcement-learning-navigation | rl/mc/cem.py | cem.py | py | 2,100 | python | en | code | 0 | github-code | 1 |
35407682008 | '''
Problem Statement
Given an array, find the sum of all numbers between the K1’th and K2’th smallest elements of that array.
Example 1:
Input: [1, 3, 12, 5, 15, 11], and K1=3, K2=6
Output: 23
Explanation: The 3rd smallest number is 5 and 6th smallest number 15. The sum of numbers coming
between 5 and 15 is 23 (11+... | Rahul-Mewada/leetcode-grind | sum-of-elements/sum-of-elements.py | sum-of-elements.py | py | 806 | python | en | code | 0 | github-code | 1 |
73820024992 | ## 다종목 스윙(해당일 종가매수 해당일 종가매도) 백테스팅 템플릿
import create_data_base
import logic
import config
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import win32com
from datetime import datetime
import time
import sqlite3
resultdata = []
flag = 0
class Core():
## 파라미터 설정
... | lyy9257/Haymanbacktester | 0.1.0/swing_basket.py | swing_basket.py | py | 4,529 | python | ko | code | 9 | github-code | 1 |
7944129600 | import pandas as pd
import re
import numpy as np
# функция, которая чистит текст открытого исходного файла
def clean_schedule(line, file_path):
# создание нового файла
file = open(file_path, 'w', encoding = "UTF-8")
line_clean = []
count = len(line)
for i in range(count):
# удаление лишних... | AfanasyevAA6/Schedule_reader | lib/schedule_lib.py | schedule_lib.py | py | 6,343 | python | ru | code | 0 | github-code | 1 |
31990513040 | # mod1.py
# loop comprehensions
loop = [[(num1, num2) for num2 in range(5)] for num1 in range(5)]
print(type(loop))
print(loop)
loop2 = [i for i in range(0, 50)]
print(loop2)
# loop comprehension with mixed list/tuples
movies = [("Gump", 1941), ("Terry", 2001), ("Wind", 1986), ("Gary", 1976),
("Tom", 1934... | carlabbasi/essentials2 | mod1.py | mod1.py | py | 1,767 | python | en | code | 0 | github-code | 1 |
31851902810 | import pprint
import re # noqa: F401
import six
from asposeslidescloud.models.fill_format import FillFormat
class PictureFill(FillFormat):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key ... | aspose-slides-cloud/aspose-slides-cloud-python | asposeslidescloud/models/picture_fill.py | picture_fill.py | py | 11,032 | python | en | code | 0 | github-code | 1 |
6033750954 | import typing as t
# TODO: Good idea to maintain a count (length of ll) that gets updated with
# each operation
class IndexOutOfRangeError(Exception):
pass
class Node:
def __init__(self, value: t.Any) -> None:
self.value = value
self.next = None
class LinkedList:
def __init__(
... | EvgeniiTitov/coding-practice | coding_practice/data_structures/linked_lists/singly_ll_implementation_1.py | singly_ll_implementation_1.py | py | 6,944 | python | en | code | 1 | github-code | 1 |
839094565 | from sys import stdin
N, M = map(int, stdin.readline().rstrip().split())
li_arr = [0] * (N+1)
bool_isused = [0] * (N+1)
def test(k):
if k == M:
for i in range(1, M+1):
print(li_arr[i], end=' ')
print('\n', end='')
return 0
for j in range(1, N+1):
li_arr[k+1] = ... | smileostrich/algorithm-practice | problemSolving/Baekjoon/backtracking/15651.py | 15651.py | py | 385 | python | en | code | 0 | github-code | 1 |
24486020984 | import sys
import math
import string
sList = ['LOUISI', 'LOUISII', 'LOUISIII', 'LOUISIV', 'LOUISV', 'LOUISVI', 'LOUISVII', 'LOUISVIII', 'LOUISIX', 'LOUISX', 'LOUISXI', 'LOUISXII', 'LOUISXIII', 'LOUISXIV', 'LOUISXV', 'LOUISXVI']
n=16
sList = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN... | mw197hub/codingame | easy/Magic String/main.py | main.py | py | 991 | python | en | code | 0 | github-code | 1 |
42675725662 | """
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
"""
class Solution(object):
def reverseList(self, head):
"""
... | bholu14401/python | ReverseLinkedList.py | ReverseLinkedList.py | py | 566 | python | en | code | 0 | github-code | 1 |
13574528250 | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from highlight_text import ax_text
def get_rolling_data(team, window, data):
df_team = data[data['Team'] == team]
df_team_for = df_team.groupby('Round_ID')['Score', 'xScore'].sum().rename(columns={'Score':"For",
... | ciaran-grant/expected-score-model | notebooks/visualisations/rolling_expected_score/rolling_expected_score.py | rolling_expected_score.py | py | 12,461 | python | en | code | 3 | github-code | 1 |
36412945847 | import argparse
import tensorflow as tf
import numpy as np
from models.model_builder import ModelBuilder
import cv2
import timeit
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int,
help="Evaluation batch size", default=1)
parser.add_argument("--num_c... | chansoopark98/Tensorflow-Keras-Semantic-Segmentation | export_tflite.py | export_tflite.py | py | 3,233 | python | en | code | 12 | github-code | 1 |
70976532513 |
import os
import pandas as pd
import numpy as np
def read_dataset(data_name):
'''
=====KDD======
'''
if data_name == 'kdd':
data_dir = './dataset/kdd/'
class_name = ['normal.', 'neptune.', 'smurf.', 'back.']
if not os.path.exists(data_dir + 'pro_data.csv'):
p = pd.r... | NIPSCode/Portray_learn | code/data_loader.py | data_loader.py | py | 1,012 | python | en | code | 0 | github-code | 1 |
31912115677 | #!/usr/bin/env python
# Diallo Ibrahima & Thiam Moustapha
# Projet: Resolution automatique d'un puzzle
# 11/01/2016
import numpy as np
import copy as cp
def Read_Data(my_puzzle):
with open(my_puzzle, 'r') as file_in:
contents= file_in.readlines()
n=0
m=0
for i, li... | ibrahima883/Puzzle | Projet.py | Projet.py | py | 13,891 | python | en | code | 1 | github-code | 1 |
40646892785 |
play = True
started = False
while play:
action = input(">").lower()
if action == 'help':
print(" start - to start the car \n stop - to stop the car \n quit - to exit")
elif action == 'start':
if started:
print("Car is already started, WHAT ARE YOU DOING???")
else:
... | krishnastest/PythonProject | learning/CarGame.py | CarGame.py | py | 710 | python | en | code | 0 | github-code | 1 |
21967591966 | from LinkedList import *
def evenAfterOdd(head):
if head is None:
return head
oddHead = None
evenHead = None
evenTail = None
oddTail = None
while head is not None:
if head.data % 2 == 0:
if evenHead == None:
evenHead = head
evenTail ... | Saumya-svm/Python_DSA | Linked List/Even after Odd LL.py | Even after Odd LL.py | py | 895 | python | en | code | 1 | github-code | 1 |
34341998236 | with open('source', 'r+') as file:
file = file.read().splitlines()
calories = [int(calorie) if calorie else 0 for calorie in file]
def first_puzzle():
max_cal = current_cal = 0
for calorie in calories:
if calorie:
current_cal += calorie
else:
if current_cal > m... | BartekWrzalski/Advent-of-Code-2022 | Day 1 Calorie Counting/day1.py | day1.py | py | 728 | python | en | code | 0 | github-code | 1 |
22746282406 | import cv2
import numpy as np
import torch
class Compose(object):
"""Composes several video_transforms together.
Args:
transforms (List[Transform]): list of transforms to compose.
Example:
>>> video_transforms.Compose([
>>> video_transforms.CenterCrop(10),
>>> vi... | Jo-won/CSQ_pytorch | lib/datasets/transform.py | transform.py | py | 10,704 | python | en | code | 0 | github-code | 1 |
41763662332 | from opentrons import robot, containers, instruments
robot.head_speed(x=18000, y=18000, z=5000, a=400, b=400)
class Vector(object):
def tolist(self):
return list(self.input_list)
def astype(self, input_type):
if input_type == int:
return Vector([int(float(x)) for x in self.input_... | PanoptoSalad/OT1_jmx | PHIP/coupling_sequence_phip - Try2/13_SC1000_1amine_dispense_24To1times96_col.py | 13_SC1000_1amine_dispense_24To1times96_col.py | py | 3,470 | python | en | code | 0 | github-code | 1 |
35574394655 | import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'ONLY-USED-FOR-TESTING'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ASSETBANK_AUTH_ENABLED = True
ASSETBANK_AUTH_TOKEN_KEY = ''
ASSETBANK_URL ... | brightinteractive/asset-bank-auth-django | assetbankauth/settings.py | settings.py | py | 394 | python | en | code | 0 | github-code | 1 |
33642073510 | f = open('fetched_tweets_output.json')
ff = open('INPUT_FILE.json','a')
while True:
a = f.readline()
print(a)
if a == '\n' or len(a)<60:
continue
else:
ff.write(a)
f.close()
ff.close() | NBALAJI95/PB-Phase-3-Spark | Non-Cloudera/clean.py | clean.py | py | 192 | python | en | code | 0 | github-code | 1 |
35705053518 | from src.models.product import Product
from typing import Union
from src.models.user import User
from http import HTTPStatus
from .. import jwt
from flask import request
class UserService:
allowed_coins = [100, 50, 20, 10, 5]
@staticmethod
def get_users():
try:
return User.get_all()
... | Rumir125/vending-maachine-amir | src/services/user_service.py | user_service.py | py | 5,567 | python | en | code | 0 | github-code | 1 |
36883997039 | import argparse
import yaml
import os
import os.path as osp
from sklearn.model_selection import ParameterGrid
import shutil
class MyDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(MyDumper, self).increase_indent(flow, False)
def parse_args():
"""Parses the ... | Guangxuan-Xiao/Case-Search | src/grid.py | grid.py | py | 2,188 | python | en | code | 4 | github-code | 1 |
31245945427 | import random
#Created by Wolf
print("Hello ! Let's play a game =) \nType numbers 0 - 9 and try to find the treasure.")
def main():
finePartita = False
Campo = list(range(0, 10))
posizionedeltesoro = random.randint(0, 9)
tentativi = 3
while finePartita == False:
print(*Campo)
user... | Gh0st-ed/Python | Treasurehunt.py | Treasurehunt.py | py | 967 | python | en | code | 0 | github-code | 1 |
26666123586 | import math
import random
class Dataset:
def __init__(self, samples, batch_size, multim=False, audiovid=False, audiotext=False, textvid=False, exp3=False,
decision_level=False):
self.samples = samples
self.batch_size = batch_size
self.num_batches = math.ceil(len(self.samp... | xctpto/Multimodal-DialogueGCN | helpers.py | helpers.py | py | 7,241 | python | en | code | 0 | github-code | 1 |
2573942818 | from sdv.model import Service
from sdv_model.proto.seats_pb2 import (
CurrentPositionRequest,
MoveComponentRequest,
MoveRequest,
Seat,
SeatComponent,
SeatLocation,
)
from sdv_model.proto.seats_pb2_grpc import SeatsStub
class SeatService(Service):
"""
Seats service for getting and cont... | eclipse-velocitas/vehicle-model-python | sdv_model/Cabin/SeatService/__init__.py | __init__.py | py | 3,463 | python | en | code | 1 | github-code | 1 |
72780138915 | import math
import overpy.exception
import holoviews
import datashader.geo
import sonar.lowrance_log_parser
import logging
logger = logging.getLogger('sonar_map')
def AdjustToIncludeNearestLandmark(lon_min, lon_max, lat_min, lat_max):
orig_lon_min = lon_min
orig_lon_max = lon_max
orig_lat_min = lat_min... | bjcosta/sonar | src/sonar/map.py | map.py | py | 8,566 | python | en | code | 2 | github-code | 1 |
23720605692 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import numbers
from einops import rearrange, repeat
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import torch.nn.functional as F
import math
# f... | m-hmy/NTIRE2023_Dn50_MegNR | models/team20_megnr.py | team20_megnr.py | py | 71,675 | python | en | code | 1 | github-code | 1 |
16248264600 | from dataclasses import dataclass
from typing import List
@dataclass
class Book:
title:str
author:str
borrower_name:str
def add_books(book_log: List[Book])->None:
print("Title?")
title = input("> ")
print("Author(s)?")
author = input("> ")
book_log.append(Book(title,author,""))
def vi... | MariannM22/Library | Mock Library/main.py | main.py | py | 1,840 | python | en | code | 0 | github-code | 1 |
72008093473 | """ A simple TCP client in Python """
import socket
target_host = "127.0.0.1"
target_port = 9999
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
client.connect((target_host, target_port))
# send some data
message = 'GET / HTTP:/1.1\r\nHost: google.com\r\n\r\n... | d4rkp0rt/TCP_Client | main.py | main.py | py | 399 | python | en | code | 0 | github-code | 1 |
16136995440 | import os
import pickle
import sys
from unittest import TestCase
# determine the absolute path to the 'backend' directory
backend_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
# add the directory 'backend/app/email/' to sys.path
sys.path.append(os.path.join(backend_path, "app", "email"))
... | amosproj/amos2023ws01-ticket-chat-ai | Backend/test/email/handle_mail_test.py | handle_mail_test.py | py | 6,549 | python | en | code | 3 | github-code | 1 |
38833934909 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key= lambda x:x[1], reverse = True)
i = 0
maxUnits = 0
while truckSize > 0 and i < len(boxTypes):
box = boxTypes[i]
if box[0] < truckSize:
t... | VJ-P/Daily-Leetcode | January-2020/maximumUnits.py | maximumUnits.py | py | 544 | python | en | code | 0 | github-code | 1 |
33612464774 | from openeis.applications import DriverApplicationBaseClass, InputDescriptor, \
OutputDescriptor, ConfigDescriptor, Descriptor
from openeis.applications import reports
import logging
import datetime as dt
from django.db.models import Avg
from openeis.applications.utils.baseline_models import day_time_temperature_mo... | VOLTTRON/openeis | openeis/applications/whole_building_energy_savings.py | whole_building_energy_savings.py | py | 11,502 | python | en | code | 10 | github-code | 1 |
15981241751 | import cv2
import numpy as np
from classes.camera import Camera
from classes.trackbars import Trackbars
from utils.utils import get_resize_picture
class Inklinometer:
def __init__(self, camera: Camera, trackbars: Trackbars, options: dict):
self.gray = None
self.REL_FROM_CENTER_TO_FIRST_HATCH = op... | DoubleCitizen/Inklinometer | classes/inklinometer.py | inklinometer.py | py | 15,130 | 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.