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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20896859782 | from __future__ import division
from random import shuffle
from maze import *
def move_forward(maze): # proceed forward choosing random directions until there is no path available
new_maze = maze
directions = [UP, RIGHT, DOWN, LEFT]
creation_ended = False
while not creation_ended:
shuffle(dir... | alextlinden/maze | maze_creation.py | maze_creation.py | py | 1,595 | python | en | code | 0 | github-code | 36 |
37708151811 | from numpy.core.numeric import normalize_axis_tuple
import pandas as pd
import numpy as np
import xarray as xr
from pandarallel import pandarallel
import time
import credentials
import tc_functions as fun
import plotting_functions as tcplt
storm_data = pd.read_csv('data/filtered_storm_list_keep-leading-5.csv')
storm_... | galenvincent/tc-wind-shear | integrated_circulation.py | integrated_circulation.py | py | 2,941 | python | en | code | 1 | github-code | 36 |
25404280105 | # -*- coding: utf-8 -*-
import torch
from model import Model
from utils import load_img,mkdir
import os
import argparse
import cv2
import time
from glob import glob
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data', default=r'/data/Disk_B/MSCOCO2014/train2014', type=str, help='... | thfylsty/ImageFusion_DeepDecFusion | fuseimg.py | fuseimg.py | py | 3,582 | python | en | code | 5 | github-code | 36 |
7704126003 | # -*- encoding: utf-8 -*-
import networkx as nx
from tools import const
# 如果没有label_type,标注为“default”
def load_data(graph_name: str, label_type: str) -> (nx.Graph, dict):
if const.System == "Windows":
edge_path = const.WindowsRootPath + "\data\graph\{}.edgelist".format(graph_name)
if label_type ==... | Sngunfei/HSD | tools/dataloader.py | dataloader.py | py | 2,898 | python | en | code | 3 | github-code | 36 |
8429575958 | from os import replace
import math
import sys
filename = sys.argv[1]
file = open("{}".format(filename), "r")
read = file.read().split(" ")
fileRead = []
charLength = 0
count = 0
comparisonValue = int(read[1])
finalArray = []
for names in range(2, len(read)):
strippedInput = read[names].strip('\n')... | hassaanarif/White-Board-Interview-Quesitons | Arbisoft_Test_1.py | Arbisoft_Test_1.py | py | 857 | python | en | code | 1 | github-code | 36 |
21769549582 | # -- fgw/simulations.py --
# Author: Jake Cray
# GitHub: crayjake/fgw-python
''' '''
# imports
from fgw.structures import DataStruct
import numpy as np
from typing import TypeVar
from math import sqrt, sin, pi
from .interfaces import SimulationInterface
from .schemes import CrankNicolson
# system wi... | crayjake/fgw-python | fgw/simulations.py | simulations.py | py | 3,185 | python | en | code | 0 | github-code | 36 |
8444672238 | import functools
import warnings
import numpy
import cupy
import cupyx.scipy.fft
def _wraps_polyroutine(func):
def _get_coeffs(x):
if isinstance(x, cupy.poly1d):
return x._coeffs
if cupy.isscalar(x):
return cupy.atleast_1d(x)
if isinstance(x, cupy.ndarray):
... | cupy/cupy | cupy/lib/_routines_poly.py | _routines_poly.py | py | 12,381 | python | en | code | 7,341 | github-code | 36 |
12486698422 | import contextlib
import os
import subprocess
import tempfile
from pathlib import Path
from pprint import pprint
from shutil import copyfile
from time import monotonic, sleep
from typing import Dict
from unittest import mock
import requests
from docker_tests.command_utils import run_command
from docker_tests.constant... | drivendataorg/snowcast-showdown | 4th Place/images/base/docker_tests/test_docker_compose_quick_start.py | test_docker_compose_quick_start.py | py | 5,681 | python | en | code | 12 | github-code | 36 |
71121334825 | from threading import Thread
import webbrowser, http.server, socketserver
import time;
port_number = 8000
server = None
def startServer(port):
Handler = http.server.SimpleHTTPRequestHandler
global server
server = socketserver.TCPServer(("", port), Handler)
print("Start server at port", port)
serv... | ldlchina/Sample-of-WebGL-with-STL-loader | LocalServer.py | LocalServer.py | py | 862 | python | en | code | 17 | github-code | 36 |
33662814296 | # Here is a quick Python solution to Problem 1 on the Mixing Addition Problem Set
import numpy as np # convenient for doing math
P_1 = 10. # Initial pressure Oxygen (atm)
V_o = 1. # Initial Volume Oxygen (L)
T = 298. # Temperature (K)
P_2 = 1. # Initial... | swflynn/Teaching_UCI | Chem131_C_2017/Sample_Problems/mixing/mixing.py | mixing.py | py | 1,346 | python | en | code | 0 | github-code | 36 |
74779834984 | from unittest import TestCase
from random import randint
from Common.common import rand_permutate
from collections import namedtuple
from .selection_in_linear_time import select, rand_select
from .problem_9_3 import select_variant
class TestSelection(TestCase):
def test_selection(self):
case_class = named... | GarfieldJiang/CLRS | P2_Sorting/OrderStatistics/test_selection.py | test_selection.py | py | 1,825 | python | en | code | 0 | github-code | 36 |
25867245413 | #test
import os
import yaml
from ..grid import Grid
import numpy as np
def load_test_data(yml_file_path):
"""Given a file path of the yaml file, return the data in the file."""
with open(yml_file_path, 'r') as f:
s = f.read()
test_data = yaml.load(s)
return test_data
def test_vertices():
... | uceclz0/mesh_generation | mesh_generation/test/grid_test.py | grid_test.py | py | 1,354 | python | en | code | 0 | github-code | 36 |
41246308973 | #!/usr/bin/env python3
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
class CORSPermissiveHTTPRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
super().end_headers()
if __name__ == "__main__... | habitatofmatt/keyboard-reducer | tools/pyodide-serve.py | pyodide-serve.py | py | 465 | python | en | code | 0 | github-code | 36 |
10770360159 | #! /usr/bin/python3
import sys
import logging
import cliff.app
import cliff.commandmanager
from commands.workflows import Workflows
from commands.sysconfig import SysConfig
from commands.daemons import Coordinator
from commands.daemons import Provisioner
from commands.generator import Generator
from commands.reports i... | ICGC-TCGA-PanCancer/cli | scripts/pancancer.py | pancancer.py | py | 1,578 | python | en | code | 8 | github-code | 36 |
72522500264 | import logging
from .models import ChangeLogTracker
logger = logging.getLogger(__name__)
class ChangeLoggerMiddleware(object):
def process_request(self, request):
try:
ChangeLogTracker.thread.request = request
except Exception as e:
logger.error(e)
| kdmukai/changelogger | changelogger/middleware.py | middleware.py | py | 299 | python | en | code | 0 | github-code | 36 |
25022706363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, argparse, json
from common.utils import use_progressbar, count_file
from smali_opcode import HCG_FILE_NAME
def merge_hash_dict(d1, d2):
'''merge d1 into d2'''
# 1. iterate through all keys of d1
# 2. check if the key is also in d2
# 2.1 yes, pl... | chushu10/StructuralClassification | count_hash.py | count_hash.py | py | 3,759 | python | en | code | 1 | github-code | 36 |
21541507358 | from random import randint
def playGame(MaxRangeChances):
secretNumber = randint(1, MaxRangeChances[0])
print(f"\nI've chosen a secret number between 1 and {MaxRangeChances[0]}.")
for numberOfGuesses in range(MaxRangeChances[1], 0, -1):
print(f"You have {numberOfGuesses} guess(es).")
... | kevinoyovota/Python-Task-3 | guessing_game.py | guessing_game.py | py | 888 | python | en | code | 0 | github-code | 36 |
19524023566 | from django.contrib import messages
from django.shortcuts import render,redirect
from students.models import student_homework,StudentFee,Attendance
from Accounts.models import UserAuthentication,Teacher
from datetime import datetime as dt
from pytz import timezone
# Create your views here.
def parent_home(request):
... | Asif-Ali1234/tution_management | parents/views.py | views.py | py | 2,388 | python | en | code | 0 | github-code | 36 |
27288756918 | # choose a player to go and make it move
# each player may take a step a head
# First one to 20 wins
Score = 0
def function():
P1 = str(input("WILL YOU GO FIRST OR SECOND ?"))
if P1 == "first" :
print(" Player 1 starts ")
def function2():
P2 = input(" Enter 1 or 2 ")
if P2 == "1":
result = Score +... | Elib22/MIN_CigshamwaByamungu | main.py | main.py | py | 618 | python | en | code | 0 | github-code | 36 |
10528069074 | from PIL import Image
from torchvision import transforms
from JointCompose import JointCompose, IMG_ONLY_TRANSFORM, MASK_ONLY_TRANSFORM, RANDOM_JOINT_TRANSFORM_WITH_BORDERS, BORDER_ONLY_TRANSFORM, JOINT_TRANSFORM_WITH_BORDERS
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.... | yolish/kaggle-dsb18 | dsbaugment.py | dsbaugment.py | py | 16,818 | python | en | code | 0 | github-code | 36 |
33364078946 | from flask import Flask, request, jsonify, url_for, session, redirect, render_template
from flaskext.mysql import MySQL
from flask_oauth import OAuth
import logging
import time
from logging.handlers import RotatingFileHandler
# from urllib.requests import urlparse
app = Flask(__name__)
app.secret_key = 'secretkey'
# k... | Iann221/UASTST | api.py | api.py | py | 5,898 | python | en | code | 0 | github-code | 36 |
650884033 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient
class YymanhuaPipeline(object):
def process_item(self, item, spider):
# 插入数据库
... | jihongzhu/python- | yymanhua/yymanhua/pipelines.py | pipelines.py | py | 737 | python | en | code | 0 | github-code | 36 |
9738742376 | def move():
direction = "W" # The default is always forwards
key = input(">> ").upper()
if key not in 'WASD': # If the entered key is not W A S D
print("Invalid Input\n")
while True:
key = input(">> ").upper()
if key in 'WASD':
break
direction =... | Aim-Entity/gamejam-1 | algo/movement.py | movement.py | py | 384 | python | en | code | 0 | github-code | 36 |
74506416103 | from django.urls import include, path, re_path
from django.urls import reverse
from rest_framework.routers import DefaultRouter
from .views import SubscriptionViewSet, UserSubscriptionView, SubscriptionCreateView, SubscriptionCancelView, SubscriptionUpdateView, SubscriptionReactiveView
app_name = 'subscription'
rout... | jubelltols/React_DRF_MySql | DRF/src/onbici/subscription/urls.py | urls.py | py | 814 | python | en | code | 0 | github-code | 36 |
37204976551 | #!/usr/bin/python3
from __future__ import print_function
import os
import sys
import torch
import torch.backends.cudnn as cudnn
import argparse
import cv2
import numpy as np
from collections import OrderedDict
sys.path.append(os.getcwd() + '/../../src')
from config import cfg
from prior_box import PriorBox
from dete... | tienhoangvan/libfacemaskdet | train/tasks/task1/demo.py | demo.py | py | 5,078 | python | en | code | 0 | github-code | 36 |
18657364741 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('orderByDay.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(row[0])
y.append(int(row[1]))
plt.plot(x,y)
plt.xlabel('Weekdays')
plt.ylabel('Number of orders')
pl... | gjtqiyue/Comp421-Database-Project | Deliverable_3/PlotCsv.py | PlotCsv.py | py | 360 | python | en | code | 0 | github-code | 36 |
1955434501 | import logging
import sqlite3.dbapi2 as sqlite3
import os
from ..config import CREATE_QUERY, TEST_QUERY
def load_database(path):
DB_INSTANCE = sqlite3.connect(path)
cursor = DB_INSTANCE.cursor()
try:
cursor.execute(TEST_QUERY)
except sqlite3.OperationalError as e:
logging.error(f"Somet... | nocturn9x/AmazonOffers-Manager | AmazonBot/database/dbcreator.py | dbcreator.py | py | 1,215 | python | en | code | 10 | github-code | 36 |
31014089660 |
# Imports
import PySimpleGUI as sg
import openai
import os
from openai.error import APIConnectionError, AuthenticationError
import threading
from datetime import datetime
from peewee import SqliteDatabase, Model, CharField, TextField
# Envs
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
... | montexbjeliseo/gui_for_chatgpt | gui_chat_gpt_api_python.pyw | gui_chat_gpt_api_python.pyw | pyw | 11,379 | python | es | code | 0 | github-code | 36 |
72192933225 | import redis, json, uuid, time, calendar, csv, io, os, yaml, xmltodict
from bottle import response
from dicttoxml import dicttoxml
from datetime import datetime
allowed_types = {
"application/json",
"application/xml",
"application/x-yaml",
# "text/tab-separated-values",
}
# expire after five minutes
... | Zamanien/SI_mandatory | esb_transform.py | esb_transform.py | py | 3,154 | python | en | code | 0 | github-code | 36 |
25775618531 | import pydriller
from pydriller.metrics.process.code_churn import CodeChurn
from pydriller.metrics.process.contributors_count import ContributorsCount
hash1 = "f858260790250880fc74ab7108073435f534d7f1"
hash2 = "319f616e572a03b984013d04d1b3a18ffd5b1190"
repo_path = "~/workfolder/dayjs"
churn_metric = CodeChurn(path_to... | vrjuliao/BCC | engenharia-de-software-2/ex-8-1/3.py | 3.py | py | 1,059 | python | pt | code | 0 | github-code | 36 |
14199367630 | import cv2
import pickle as pkl
import time
import xgboost as xgb
import math
import numpy as np
import mediapipe as mp
from speak import speakText
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
width = 640
height = 480
hands = mp_hands.Hands(min_detection_confidence=0.6, min_tracking_confiden... | bahrain-uob/PoseMate | run_v2.py | run_v2.py | py | 19,687 | python | en | code | 1 | github-code | 36 |
30467293197 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findFrequentTreeSum(self, root: TreeNode):
if not root:
return []
res = {}
self.dfs(root, res)
maxi = max([ele for ele in res.val... | dundunmao/LeetCode2019 | 508. Most Frequent Subtree Sum.py | 508. Most Frequent Subtree Sum.py | py | 1,346 | python | en | code | 0 | github-code | 36 |
18775996369 | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('forms', views.form, name='form'),
path('remove/<todo_id>', views.delete_todo, name='remove'),
path('add_todo', views.add_todo, name='new_todo'),
path('update_todo/<todo_id>', views.edit_todo, n... | Torgbui-Hiram/django_crm | website/urls.py | urls.py | py | 580 | python | en | code | 0 | github-code | 36 |
41329717796 |
import tensorflow as tf
import numpy as np
import cv2
import os
def save_image(path, image) :
extension = os.path.splitext(path)[1]
result, encoded_img = cv2.imencode(extension, image)
if result :
with open(path, "wb") as f :
encoded_img.tofile(f)
# 대상 입력
target = input("대상을 입력하세요 : ... | moonsung1234/SimilarityComparisonProject | increase.py | increase.py | py | 1,532 | python | en | code | 1 | github-code | 36 |
1598374603 | import unittest
from inverter import scale_number
class TestScaleNumber(unittest.TestCase):
def setUp(self):
self.field_mapping = {"name": "Current Solar Production (kilowatts)",
"format": "{:.1f}kW",
"divisor": 1000,
... | eastc5/inverter | tests/test_inverter.py | test_inverter.py | py | 1,205 | python | en | code | 0 | github-code | 36 |
12262454581 | import sys
import contentful_management
from env import *
client = contentful_management.Client(MANAGEMENT_API_TOKEN)
space = client.spaces().find(SPACE_ID)
environment = space.environments().find('master')
content_types = environment.content_types().all()
content_type = content_types[0]
if '--test' in sys.argv:
... | wildlava/skydiving-formations-react | tools/ingest_formations.py | ingest_formations.py | py | 3,444 | python | en | code | 0 | github-code | 36 |
16076363640 | import argparse
import os
import statistics
from typing import Callable
import dotenv
from tqdm import tqdm
from headhunter import get_vacancies_from_hh, fetch_areas_ids, predict_rub_salary_hh
from salary_helpers import create_table
from superjob import get_vacancies_from_sj, predict_rub_salary_sj, fetch_town_ids
PR... | shadowsking/salary-statistics | main.py | main.py | py | 2,481 | python | en | code | 0 | github-code | 36 |
26250599999 | import tensorflow as tf
import math
batch_size = 128
vocabulary_size = 106321
embedding_size = 128
graph = tf.Graph()
with graph.as_default():
train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
# Ops and variables pinned to the CPU be... | DefuLian/script | dl/loc_pred/train.py | train.py | py | 1,739 | python | en | code | 1 | github-code | 36 |
22703498747 | import spacy
import numpy
import os
from numpy import dot
from numpy.linalg import norm
nlp = spacy.load('en_core_web_lg')
def compare_wordlists_by_spacy_vectors(model, wordlist1, wordlist2):
vectorlist1 = model(wordlist1)
vectorlist2 = model(wordlist2) #unicode string
myData = [ ]
for wordve... | kariemoorman/iat-weat-wefat | scripts/comparison_functions/spacy_word_comparison_functions.py | spacy_word_comparison_functions.py | py | 2,179 | python | en | code | 0 | github-code | 36 |
33449376249 | import csv
with open("zadanie2.csv", newline='') as file:
reader = csv.reader(file, delimiter=',')
header = next(reader)
wiersze = []
for row in reader:
if row[1] != "":
wiersze.append(row)
wiersze.sort(key=lambda x: int(x[0]) if x[0].isdigit() else -1)
poprzednie_id = None
for row in wiersze:
... | Kubek-3/python | csv.py | csv.py | py | 1,306 | python | pl | code | 0 | github-code | 36 |
10755048516 | #date:21-9-17
import pafy
url="https://www.youtube.com/watch?v=mkKXS0FI_L4"
video=pafy.new(url)
audiostreams = video.audiostreams
for a in audiostreams:
print(a.bitrate, a.extension, a.get_filesize())
########to download audio directly
#audiostreams[1].download()
bestaudio = video.getbestaudio()
bestaudio.bi... | pemagrg1/YoutubeDownloader | download_audio.py | download_audio.py | py | 513 | python | en | code | 1 | github-code | 36 |
31981642211 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
mylist = my_list.copy()
m = mylist.count(search)
if m == 0:
return mylist
for i in range(m):
n = mylist.index(search)
mylist[n] = replace
return mylist
| osamuflair/alx-higher_level_programming | 0x04-python-more_data_structures/1-search_replace.py | 1-search_replace.py | py | 261 | python | en | code | 0 | github-code | 36 |
75156395304 | # Кузнецов Денис ИУ7-13Б
# Программа для нахождения максимального значения над главной диагональю
# И минимального - под побочной диагональю
from def_fool import check_int_number, check_material_number
def find_max_min(A):
max_el = float('-inf')
min_el = float('+inf')
N = len(A[0])
M = len... | Denis926178/Python | lab9/lab92.py | lab92.py | py | 2,470 | python | ru | code | 0 | github-code | 36 |
72775441703 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 07:43:03 2020
@author: Das
"""
# Importing Essential Libraries
import nltk
import random
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.tree import DecisionTreeClassifier
from ... | DasBhai/MNCRankingRealtime | mod_sentiment.py | mod_sentiment.py | py | 2,815 | python | en | code | 0 | github-code | 36 |
6243299984 | import requests
import pprint
import matplotlib.pyplot as plt
from tabulate import tabulate
import numpy as np
print('')
print('- GLOBAL INFO -')
print('')
# CONNECT WITH THE API
url = 'https://api.coingecko.com/api/v3/coins/categories'
r = requests.get(url)
response = r.json()
# pprint.pprint(response)
# exit()
... | jbbaptista/Personally | Sectores_coingecko/Add_daily_info_database.py | Add_daily_info_database.py | py | 9,661 | python | en | code | 0 | github-code | 36 |
41019665619 | import os
from pathlib import Path
import structlog
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.ses... | sipwise/repoapi | repoapi/settings/common.py | common.py | py | 4,245 | python | en | code | 2 | github-code | 36 |
6208216835 | file = open('file.txt', 'r')
#file2 = file.read()
#print(file2)
print("------------------------")
for l in file:
data = l.split(' ')
print(data)
print("--->>>" + l)
file2 = file2.strip()
for palabra in file2.split(' '):
if palabra.isalpha():
print(palabra)
else:
print(">"+palabra+"<... | emmanuelortizhernandez/Lenguajes-y-Automatas-II | practica.py | practica.py | py | 335 | python | en | code | 0 | github-code | 36 |
7796422428 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : 保留最大的数.py
# @Author: smx
# @Date : 2019/8/27
# @Desc :
# 存在的问题:语法错误或者数组越界非法访问等情况 --》 输入有错,输入是两行!题目要求和给的测试案例不一定对应!
# 存在的问题:超时! --》 不用两层for循环用not in判断
# 存在的问题:答案不正确! --》
# 我自己的想法有错误,不能是排序得到答案,需要的将大的数字的位置提到前面来
# 自己的想法有错误,不是去掉比后面一个元素大的元素,是保留的元素要比其他的元素大
# 8215492
#... | 20130353/Leetcode | target_offer/数组/保留最大的数.py | 保留最大的数.py | py | 2,015 | python | zh | code | 2 | github-code | 36 |
43751185703 | from __future__ import unicode_literals
import os
import tempfile
import unittest
from textwrap import dedent
import mock
import six
import rows
import rows.plugins.postgresql
import rows.plugins.utils
import tests.utils as utils
from rows import fields
from rows.plugins.postgresql import pgconnect
from rows.utils i... | turicas/rows | tests/tests_plugin_postgresql.py | tests_plugin_postgresql.py | py | 9,172 | python | en | code | 851 | github-code | 36 |
7749159191 | from flask import Blueprint, request
from flask import jsonify, render_template
from authlib.specs.rfc6749 import OAuth2Error
from authlib.flask.oauth2 import current_token
from ..models import OAuth2Client, OAuth2Token, User
from ..auth import current_user
from ..forms.auth import ConfirmForm, LoginConfirmForm
from ..... | itsocietysu/EACH-OAuth2.0 | website/routes/oauth2.py | oauth2.py | py | 4,226 | python | en | code | 0 | github-code | 36 |
18846832139 | def play(player):
global input_
new_y, new_x = input("Enter the coordinates: ").split()
if not(new_y.isdigit() and new_x.isdigit()):
print("You should enter numbers!")
else:
y, x = int(new_y), int(new_x)
cell_index = 3 * (y - 1) + (x - 1)
if not(x > 0 and x < 4 and y > 0 ... | lika010/SimpleTicTacToe | Simple Tic-Tac-Toe/task/tictactoe.py | tictactoe.py | py | 2,600 | python | en | code | 0 | github-code | 36 |
30076689122 | # general imports
from pathlib import Path
import os
import re
import argparse
from time import time
import multiprocessing as mp
from functools import partial
from collections import Counter
# processing imports
import numpy as np
import pandas as pd
from tqdm import tqdm
from collections import OrderedDict
from diff... | dataforgoodfr/batch7_rse | polls/rse_model/rse_watch/pdf_parser.py | pdf_parser.py | py | 21,499 | python | en | code | 5 | github-code | 36 |
30631135881 | '''Given a number x,
determine whether the given number is Armstrong number or not.
A positive integer of n digits is called
an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... '''
# #program1 incomplete program tryout
# #input
# num = i... | nishanthhollar/geeksforgeeks_python_basic_programs | basic_programs/armstrongnum.py | armstrongnum.py | py | 1,496 | python | en | code | 0 | github-code | 36 |
1832479916 | def repeat(n):
a=[]
while n!=0:
ele = n%10
if ele in a:
return 0
else:
a.append(ele)
n=n//10
return 1
n=int(input())
m=int(input())
res=0
for i in range(n,m+1):
res=res+repeat(i)
print(res)
| lakshman533/Python_programs | countnn.py | countnn.py | py | 282 | python | en | code | 0 | github-code | 36 |
15680118405 | import json
import logging
from .codebase import CodebaseAgent
from .gpt_agent import GPTAgent, Role
class ProgrammerAgent:
def __init__(self, codebase_repo_path, gpt_api_key):
self.codebase_agent = CodebaseAgent(codebase_repo_path)
self.gpt_agent = GPTAgent(api_key=gpt_api_key, role=Role.PROGRAMME... | csmathguy/SAGA | src/agent/programmer.py | programmer.py | py | 1,812 | python | en | code | 0 | github-code | 36 |
33664019417 | # This is our basic snake game.
# We will utilise python and some libraries to make it
import turtle # this imports the turtle to be used in our game.
t = turtle.Turtle()
for c in [ 'green', 'blue', 'red', 'white']:
t .color(c)
t.forward(50)
t. left(75)
| josephkb87/PythonBasics | Application And Worked Examples/Basic Personal Snake Game/main.py | main.py | py | 270 | python | en | code | 3 | github-code | 36 |
70441946023 | '''
Summary
Attempt #1
Your own answer?: No
Reference: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1731/A-Python-solution-85ms-O(n)
Runtime: 48 ms, faster than 96.47% of Python3 online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 14.4 MB, less t... | cjy13753/algo-solutions | leetcode/solution_3.py | solution_3.py | py | 1,208 | python | en | code | 0 | github-code | 36 |
26464454997 | import string
import random
def hangman():
turns=int(input("\nIn how many turns do you want to guess the string : "))
print()
length=int(input("\nhow many letters word do you wanna guess? "))
word=''.join(random.choice(string.ascii_lowercase) for x in range(length))
w1=word
#print(word)
gue... | Naveen2224/Hangman | Hangman.py | Hangman.py | py | 1,474 | python | en | code | 1 | github-code | 36 |
25674262123 |
from odoo import models, fields, api,_
class student(models.Model):
_name = 'student.student'
student1=fields.Char(string='student1')
student2=fields.Char(string='student2')
student3=fields.Char(string='student3')
student4=fields.Char(string='student4',compute='onchange_student4',store=True)
... | maaanas/student | models.py | models.py | py | 577 | python | en | code | 0 | github-code | 36 |
1133144480 | import pyfiglet
import platform
import os
import sys
import socket
import threading
from time import sleep
from queue import Queue
def banner():
banner = pyfiglet.figlet_format('PORT SCANNER')
print('\033[93m'+banner+'\033[m')
ports = Queue()
first_port = 1
last_port = 65535
for i in range(first_port, las... | ArthurDeveloper/portscanner-python | portscanner.py | portscanner.py | py | 2,780 | python | en | code | 3 | github-code | 36 |
34683343714 | #!/home/kelsi/.virtualenvs/mtg/bin/python
# -*- coding: utf-8 -*-
from bottle import route, run, template, view
from datetime import date
import sqlite3
con = sqlite3.connect('mtg.db')
con.row_factory = sqlite3.Row
cursor = con.cursor()
@route('/hello/<name>')
@view('sample')
def hello(name):
return dict(name=n... | kelind/bio-mtg | mtg_bottle.py | mtg_bottle.py | py | 2,408 | python | en | code | 0 | github-code | 36 |
13245977761 | #!/usr/bin/env python
# coding: utf-8
# # Jenkins - Monitoring, Building and Running Regressions
#
# This tool was written to ease my daily job because I need to check the regression tests regularly which totally have around 7000 regression tests. It's really such a hassle to do it manually and frequently.
#
# This ... | wy8162/hggraph | jenkins_tools.py | jenkins_tools.py | py | 24,012 | python | en | code | 0 | github-code | 36 |
74457209702 | """Futurepedia"""
import json
import re
import time
import random
import scrapy
import os
from urllib.parse import urljoin
from zimeiti.items import ZimeitiItem
from zimeiti.public import refactoring_img, down_img, contenc_description, get_words, timetimes, execute, is_exists, \
refactoring_img1
import math
class... | AYongmengnan/zimeiti | zimeiti/spiders/futurepedia.py | futurepedia.py | py | 3,916 | python | en | code | 0 | github-code | 36 |
32301076957 | #!/usr/bin/env python
from scapy.all import *
from subprocess import call
import time
op=1 # Op code 1 for ARP requests
victim=raw_input('Enter the target IP to hack: ') #person IP to attack
victim=victim.replace(" ","")
spoof=raw_input('Enter the routers IP *SHOULD BE ON SAME ROUTER*: ') #routers IP.. Should be the... | ammarx/ARP-spoofing | src/mmattack.py | mmattack.py | py | 563 | python | en | code | 32 | github-code | 36 |
21315566191 | # D = len(data) ## number of docs...data is list of documents
# print('D: ', D)
import torch
import pickle
beta = torch.load('betas-40.pt', map_location=torch.device('cpu'))
beta = beta.numpy()
with open('vocab_50K.pkl', 'rb') as f:
vocab = pickle.load(f)
TC = []
num_topics = len(beta)
for k in range(num_topic... | gretatuckute/neuralNLP | ETM_evaluation/testBetaOrder.py | testBetaOrder.py | py | 488 | python | en | code | 1 | github-code | 36 |
16154117928 | from django.utils.translation import ugettext_lazy as _
STRONGLY_DISAGREE = "strongly disagree"
DISAGREE = "disagree"
SOMEWHAT_DISAGREE = "somewhat disagree"
NEITHER = "neither agree nor disagree"
SOMEWHAT_AGREE = "somewhat agree"
AGREE = "agree"
STRONGLY_AGREE = "strongly agree"
PARENTING_ATTITUDES_CHOICES = [
(... | langcog/web-cdi | webcdi/cdi_forms/choices.py | choices.py | py | 1,038 | python | en | code | 7 | github-code | 36 |
17585378222 | import numpy as np
import matplotlib.pyplot as plt
from starwhale import dataset
def show_image(image) -> None:
plt.imshow(image, cmap="gray")
plt.show(block=True)
ds_name = "fer2013/version/latest"
ds = dataset(ds_name)
row = ds.fetch_one()
data = row.features
show_image(
np.frombuffer(data["image"].t... | star-whale/starwhale | example/datasets/fer2013/example.py | example.py | py | 399 | python | en | code | 171 | github-code | 36 |
18305200802 | #!/usr/bin/python
#
# This is a script for dumping and changing peripheral settings on an STM32
# on a running target with he help of OpenOCD. It was written for reverse
# engineering the DPS5005 but should work for any STM32 target with little
# change.
#
# No rights reserved
#
import socket
import sys
prompt = "> "... | kanflo/opendps | ocd-client.py | ocd-client.py | py | 24,789 | python | en | code | 840 | github-code | 36 |
35018450468 | from os import path
import sys
import metavision_designer_engine as mvd_engine
from metavision_designer_engine import Controller
import metavision_designer_cv as mvd_cv
import metavision_designer_core as mvd_core
import metavision_hal as mv_hal
import cv2
from Python.Event_Processor.EventProcessor import EventProcessor... | GuillaumeCariou/I3S_Tutorship_Internship | Python/Log_Luminance/Main.py | Main.py | py | 7,685 | python | fr | code | 0 | github-code | 36 |
20157445865 | from collections import defaultdict
from itertools import permutations
class DinnerTable:
def __init__(self, instructions) -> None:
self.ins = instructions
self.happiness_scores = {}
self.guest_list = []
def process_happiness_scores(self):
lines = [line for line in self.ins.sp... | davidcolton/adventofcode | 2015/day_13/dinner.py | dinner.py | py | 2,243 | python | en | code | 0 | github-code | 36 |
6103056667 | import os
import argparse
import utils
import json
import numpy as np
from sklearn import metrics
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
import torchvision.transforms as T
from models.dgcnn import DGCNN
from models.pointnet import PointNet, feature_transform_regularizer
import tran... | leoriczhang/3d-pointcloud- | test_cls.py | test_cls.py | py | 6,038 | python | en | code | 0 | github-code | 36 |
41613216897 | import time
# 切换着执行 yield
def worker1():
# for i in range(n):
while True:
print("in worker1")
yield
time.sleep(1)
def worker2():
# for i in range(n):
while True:
print("in worker2")
yield
time.sleep(1)
if __name__ == '__main__':
# 调用生成器函数 产生生成器对象... | ABDM357/python_summary_knowledge_001 | Day01-15 Python基础课程/Day01-15课程与项目/06协程-网络/03-代码/01-使用yield实现协程.py | 01-使用yield实现协程.py | py | 447 | python | en | code | 0 | github-code | 36 |
30085141101 | from typing import TypedDict
from gdbdash.commands import BoolOption, StrOption
from gdbdash.modules import Module
from gdbdash.utils import FileDescriptorOrPath
DashboardOptions = TypedDict(
"DashboardOptions",
{
"text-highlight": StrOption,
"text-secondary": StrOption,
"text-divider"... | JensDll/dotfiles | unix/.config/gdbdash/gdbdash/dashboard.pyi | dashboard.pyi | pyi | 586 | python | en | code | 0 | github-code | 36 |
31551053914 | """ Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
No final, mostre a matriz na tela, com a formatação correta """
lista = [[],[],[]]
for i in range(3):
for j in range(3):
lista[i].append(int(input(f'Digite um valor [{i}][{j}]: ')))
print('\nA matriz dos núm... | ClebersonGarcia05/curso-python | Mundo python 03/Exercícios/Listas/ex086.py | ex086.py | py | 440 | python | pt | code | 0 | github-code | 36 |
31826768248 | # make some tests
import os, glob
from pprint import pprint
from importlib import reload
import designspaceProblems
reload(designspaceProblems)
import designspaceProblems.problems
reload(designspaceProblems.problems)
from designspaceProblems.problems import DesignSpaceProblem, allProblems
from designspaceProblems ... | LettError/DesignspaceProblems | tests/makeTests.py | makeTests.py | py | 19,721 | python | en | code | 18 | github-code | 36 |
7939019332 | from itertools import combinations
def answer(l):
l.sort(reverse=True)
for i in range(len(l), 0, -1):
for c in itertools.combinations(l, i):
if sum(c) % 3 == 0:
return int(''.join(map(str, c)))
return 0
| deepspacepirate/googlefoobar | L2-please_pass_the_coded_messages.py | L2-please_pass_the_coded_messages.py | py | 235 | python | en | code | 0 | github-code | 36 |
37350691317 | from ase import Atom, Atoms
from ase.units import Bohr
from gpaw import GPAW
from gpaw.test import equal
def test_xc_nonselfconsistentLDA(in_tmp_dir):
a = 7.5 * Bohr
n = 16
atoms = Atoms([Atom('He', (0.0, 0.0, 0.0))], cell=(a, a, a), pbc=True)
calc = GPAW(gpts=(n, n, n), nbands=1, xc='LDA')
atoms.... | f-fathurrahman/ffr-learns-gpaw | my_gpaw/test/xc/test_nonselfconsistentLDA.py | test_nonselfconsistentLDA.py | py | 1,193 | python | en | code | 0 | github-code | 36 |
28521392927 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from urbansim.functions import attribute_label
from numpy import ones, array, float32
class ln_a... | psrc/urbansim | urbansim/household_x_gridcell/ln_access_to_workplace_from_residences.py | ln_access_to_workplace_from_residences.py | py | 2,137 | python | en | code | 4 | github-code | 36 |
11591514846 | def main():
f = open("input/day1.txt", "r")
counter = 0
tmp = 0
for x in f.readlines():
x = int(x.rstrip())
if(x > tmp and tmp != 0):
counter += 1
tmp = x
print(counter)
if __name__ == "__main__":
main() | Tyv217/AdventOfCode2021 | day1a.py | day1a.py | py | 264 | python | en | code | 0 | github-code | 36 |
42736810973 | # -*- coding: utf-8 -*-
"""
Created on Sun May 2 10:11:50 2021
@author: Simon
"""
# Imports
import matplotlib.pyplot
import csv
from bs4 import BeautifulSoup
import requests
import particlemove # Associated file used to move particles
import tkinter as tk
import time
# Model variables
num_of_iterations = 200 # Th... | simonhp66/bacterialbomb | bacterialbomb.py | bacterialbomb.py | py | 13,564 | python | en | code | 0 | github-code | 36 |
27895854947 | from django.db import models
from django.conf import settings
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import uuid
channel_layer = get_channel_layer()
class MessageManager(models.Manager):
def get_pending_messages(self, user):
pending_messages_qs = user.pendi... | stgoddv/whatsapp-clone-django-vuejs | djchat/chat/models.py | models.py | py | 3,772 | python | en | code | 10 | github-code | 36 |
9204282514 | import sys
import os
import time
import traceback
import numpy as np
import torch
import torchvision
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.autograd import Variable
from tqdm import tqdm
#con... | sarah-antillia/SOL4Py_V4 | SOL4Py/torch/ZTorchSimpleModel.py | ZTorchSimpleModel.py | py | 2,551 | python | en | code | 0 | github-code | 36 |
21142071947 | from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.typing import Adj, OptPairTensor, OptTensor, Size
from torch_geometric.utils.repeat import repeat
import torch
from torch_sparse import SparseTensor
from torch import Tensor, nn
from torch.nn impor... | wi-re/spheric_density_demo | rbfConv.py | rbfConv.py | py | 24,177 | python | en | code | 2 | github-code | 36 |
74158129382 | # test_cloud_client.py
import pytest
from datetime import datetime
from testfixtures import LogCapture
from cloud_server import initialize_server, add_database_entry
from database_definitions import Patient
import io
import os
initialize_server()
pathname = os.getcwd()
full_pathname = pathname + '/images/test_image.... | pdijour/Patient_Monitoring_FullStack | test_cloud_client.py | test_cloud_client.py | py | 2,802 | python | en | code | 1 | github-code | 36 |
73137302504 | """factRequestForDocuments
Revision ID: 489ca98de532
Revises: d6c3af32b13e
Create Date: 2022-01-26 22:39:14.403851
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '489ca98de532'
down_revision = 'd6c3af32b13e'
branch_labels = None
depends_on = None
def upgrade... | bcgov/foi-reporting | datawarehouse/edw_migrations/versions/489ca98de532_factrequestfordocuments.py | 489ca98de532_factrequestfordocuments.py | py | 1,937 | python | en | code | 0 | github-code | 36 |
40321895686 | import os
import pandas as pd
def get_file_list(path):
file_list = []
for root, dirs, files in os.walk(path):
for file in files:
file_list.append([root, file])
return file_list
def save_to_excel(file_list, excel_file):
df = pd.DataFrame(file_list, columns=["Папка", "Имя файла"])
... | leansellerdev/testPythonRpa | main.py | main.py | py | 648 | python | ru | code | 0 | github-code | 36 |
23306322275 | import click
import csv
import itertools
from Bio import motifs
from Bio.Seq import Seq
from Bio.SeqUtils import GC
from Bio.Alphabet import generic_dna
from Bio.Alphabet.IUPAC import unambiguous_dna
def homer_parse(fstream):
def build(name, freq):
m = motifs.Motif(counts=freq)
m.name = name
... | ren-lab/snp-selex | pwm/score.py | score.py | py | 4,389 | python | en | code | 15 | github-code | 36 |
24179539315 | """Helper functions for iterables."""
import collections
from itertools import islice, zip_longest
from typing import Callable, Iterable, Iterator, Optional, TypeVar
T = TypeVar("T")
# Courtesy of https://docs.python.org/3/library/itertools.html
def grouper(
iterable: Iterable[T],
n: int,
*,
incompl... | NickG123/AdventOfCode2022 | utils/iterables.py | iterables.py | py | 1,958 | python | en | code | 0 | github-code | 36 |
74955138663 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import requests
SNIPPET_TEMPLATE = """<snippet>
<content><![CDATA[
{}
]]></content>
<description>{}</description>
<scope>source.python</scope>
<tabTrigger>{}</tabTrigger>
</snippet>"""
def _request_code(target_url):
"""Request a code file... | fhightower/sublime-snippet-creator | sublime_snippet_creator/sublime_snippet_creator.py | sublime_snippet_creator.py | py | 3,465 | python | en | code | 0 | github-code | 36 |
8746369027 | import requests
import numpy as np
from phe import paillier
import math
api_address = "http://localhost:8000"
N_FEATURES = 10
PRECISION = 2**(-16)
EXP = -8
TEST_DATA = [0.48555949, 0.29289251, 0.63463107, 0.41933057, 0.78672205, 0.58910837, 0.00739207, 0.31390802, 0.37037496, 0.3375726]
TEST_PRED = 0.4481214474665382... | arinaruck/isp_2022 | hw8/steal_model.py | steal_model.py | py | 1,831 | python | en | code | 0 | github-code | 36 |
16431295526 | from qtdataflow.Qt import QtCore
QObject = QtCore.QObject
Signal = QtCore.Signal
class Node(object):
"""
Logical Representation of a node.
"""
def __init__(self):
#self.schema = schema
self.node_type = 'BaseNode'
self.accepts_input = False
self.generates_output = False... | B-Rich/qt-dataflow | qtdataflow/model.py | model.py | py | 3,501 | python | en | code | null | github-code | 36 |
9324455473 | import os
from dotenv import load_dotenv
import discord
from discord import app_commands
from langchain.llms import OpenAI
# Load the .env file
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
guild_id = os.getenv('DISCORD_GUILD')
openai_key = os.getenv('OPENAI_KEY')
class Client(discord.Client):
def __init__(sel... | conradomanclossi/Trends | bot/main.py | main.py | py | 1,334 | python | en | code | 0 | github-code | 36 |
25314544397 | import sys
input = lambda : sys.stdin.readline().rstrip()
def main(s1, s2):
l1, l2, answer = len(s1), len(s2), 0
dp = [0]*l2
for i1 in range(l1):
dp_sub = [0]*l2
for i2 in range(l2):
dp_sub[i2] = (min(i2,1)*dp[i2-1] + 1)*(s1[i1]==s2[i2])
answer = max(answer, max(dp_sub))... | soohi0/Algorithm_study | 4월_4주/BOJ_공통부분문자열/BOJ_공통부분문자열_강태훈.py | BOJ_공통부분문자열_강태훈.py | py | 494 | python | en | code | 0 | github-code | 36 |
23315419953 | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = [
'nose',
'unittest2',
]
setup(
name='quickunit',
version='0.6.0',
author='David Cramer',
author_email='dcramer@gmail.com',
description='A discovery plugin for Nose which relies on sane structure.',
url=... | dcramer/quickunit | setup.py | setup.py | py | 1,025 | python | en | code | 34 | github-code | 36 |
42866907447 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:
if not root1 or not root2:
return False
... | allen791210/LeetCode | 1214_Two_Sum_BSTs.py | 1214_Two_Sum_BSTs.py | py | 914 | python | en | code | 0 | github-code | 36 |
10902517011 | from django.test import TestCase
from home.models import UserProfile
class UserProfileModelTestCase(TestCase):
@classmethod
def setUpTestData(cls):
# Create test data before running the tests
UserProfile.objects.create(
name='John Doe',
email='johndoe@example.com',
... | shubhamkhuntia/superU-Assignment | home/tests.py | tests.py | py | 1,010 | python | en | code | 0 | github-code | 36 |
32786931379 | __all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__name__ = "influxdump"
__summary__ = 'InfluxDB data backup tool'
__uri__ = "https://github.com/gams/influxdump"
__version__ = "1.0.6"
__author__ = 'Stefan Berder <stefan@measureofqu... | gams/influxdump | influxdump/__about__.py | __about__.py | py | 484 | python | en | code | 3 | github-code | 36 |
31762824166 | from collections import deque
def bfs():
dx = [0,1,0,-1]
dy = [1,0,-1,0]
while loc:
x_y = loc.popleft()
y, x = x_y[0], x_y[1]
for i in range(4):
nX = x + dx[i]
nY = y + dy[i]
if nX < 0 or nX >= m or nY < 0 or nY >= n: continue
if ma... | 4RG0S/2020-Spring-Jookgorithm | 이승민/[20.03.30]2178.py | [20.03.30]2178.py | py | 626 | python | en | code | 4 | github-code | 36 |
17742767435 | # EDGE LIST GRAPH
from queue import Queue
MAX = 100
V = None
E = None
visited = [False for i in range(MAX)]
path = [0 for i in range(MAX)]
graph = [[] for i in range(MAX)]
dist = [-1 for i in range(MAX)]
def BFS(s):
dist[s] = 0
visited[s] = True
q = Queue()
q.put(s)
while q.empty() == False:
... | baocogn/self-learning | big_o_coding/Blue_13/Schoolwork/day_5_BFS.py | day_5_BFS.py | py | 985 | python | en | code | 0 | github-code | 36 |
7154136673 | # 23. Merge k Sorted Lists
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: 'List[ListNode]') -> 'ListNode':
newhead = ListNode(None)
curr = newhead
import heap... | Fanll123/MyLeetcodeExercise | 23.py | 23.py | py | 951 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.