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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
27940252845 | import random
from kfp import components, dsl
from kfp.components import InputPath, OutputPath
from kfp.components import func_to_container_op
from typing import NamedTuple
def train_data_load(
output_dataset_train_data: OutputPath('Dataset')
):
import tensorflow as tf
import pandas as pd
import ... | matildalab-private/kfp_example | fashion_mnist/train_prediction.py | train_prediction.py | py | 6,745 | python | en | code | 0 | github-code | 1 |
4432837632 | alist = [5,4,6,7,9,3,10,9,5,6]
def findDuplicates(nums):
i = 0
ans =[]
while i < len(nums):
if nums[i] != i+1:
correct = nums[i] - 1
if nums[correct] != nums[i]:
nums[correct], nums[i] = nums[i], nums[correct]
else:
i += 1
... | Santho-osh/pythonProject | Sorting/CyclicSort/findDuplicates.py | findDuplicates.py | py | 504 | python | en | code | 1 | github-code | 1 |
43684655986 | import math
import string
from nltk.corpus import stopwords
from collections import Counter
from nltk.stem.porter import *
from sklearn.feature_extraction.text import TfidfVectorizer
import jieba
def tfidf_calc(text, corpus, k, file_path):
# corpus = ['This is the first document.',
# 'This is the se... | henry-nju/- | main-match.py | main-match.py | py | 2,000 | python | en | code | 0 | github-code | 1 |
5224241009 | import operator
def PatternCount(Text, Pattern):
# fill in your function here
result = 0
genome_dic = {}
for num in range(len(Text) - len(Pattern) + 1):
k_mer = Text[num: num+len(Pattern)]
# print(three_mer)
if k_mer == Pattern:
result += 1
r... | ryoiwata/coursera_bioinformatics | class_1/class_1_quiz_1.py | class_1_quiz_1.py | py | 2,493 | python | en | code | 0 | github-code | 1 |
71919922594 | # Read text from a file, and count the occurence of words in that text
# Example:
# count_words("The cake is done. It is a big cake!")
# --> {"cake":2, "big":1, "is":2, "the":1, "a":1, "it":1}
from collections import Counter
import re
def read_file_content(filename):
# Reading the text file
with op... | Hephzihub/Python | Reading-Text-Files/main2.py | main2.py | py | 610 | python | en | code | 0 | github-code | 1 |
18481392221 | """
Define helpful logging functions.
"""
# STD
from collections import defaultdict
from functools import wraps
from genericpath import isfile
from os import listdir
from os.path import join
from typing import Optional, List, Callable
import os
# EXT
import numpy as np
import torch
# PROJECT
from src.utils.types imp... | Kaleidophon/tenacious-toucan | src/utils/log.py | log.py | py | 8,806 | python | en | code | 0 | github-code | 1 |
6500492677 | while True:
s = 0
q = 0
while (q< 2):
n= float(input())
if (n >= 0 and n <= 10):
s += n
q += 1
else:
print("nota invalida")
print("media = %.2f" % (s / 2))
t = 0
while True:
print("novo calculo (1-sim 2-nao)")
t= int(inp... | joy1954islam/uri-problem-solution-in-python | problem 1118 Several Scores with Validation.py | problem 1118 Several Scores with Validation.py | py | 404 | python | en | code | 17 | github-code | 1 |
30715904956 | import traceback
from http import HTTPStatus
from flask import request, abort, jsonify
from .constants import REQ_ARG_PAGE, REQ_ARG_PER_PAGE, REQ_ARG_PAGINATION, REQ_ARG_TYPE, ENTITY_TYPE
from .app_cfg import max_items_per_page
def get_request_arg(arg: str, default: int) -> int:
"""
Get a positive integer a... | ibuttimer/full-stack-trivia | backend/flaskr/util/misc.py | misc.py | py | 5,259 | python | en | code | 0 | github-code | 1 |
10425974706 | import logging
import math
import os
import pickle
import random
import signal
import sys
import uuid
from time import sleep
from threading import Thread
import rpyc
from rpyc.utils.server import ThreadedServer
from utils import LOG_DIR
from conf import block_size, replication_factor, minions_conf
MASTER_PORT = 213... | lyu-xg/PyDFS | pydfs/master.py | master.py | py | 7,721 | python | en | code | null | github-code | 1 |
34139755887 | import os
import sys
sys.path.append("Mask_RCNN")
from mrcnn.model import MaskRCNN
from mrcnn import utils
from data import Data
from waldo_config import Waldoconfig
if __name__ == '__main__':
config = Waldoconfig()
config.display()
model = MaskRCNN(mode="training", config=config,
... | alseambusher/deepwaldo | train.py | train.py | py | 1,130 | python | en | code | 8 | github-code | 1 |
6484753583 | """
@Time : 2021/1/31 18:23
@Author : Steven Chen
@File : 8.selenium_cookies.py
@Software: PyCharm
"""
# 目标:
# 方法:
from selenium import webdriver
url = 'https://www.baidu.com'
driver = webdriver.Chrome()
driver.get(url)
cookies = {data["name"]: data["value"] for data in driver.get_cookies()}
print(cookies)
| PandaCoding2020/pythonProject | SpiderLearning/3.selenium/8.selenium_cookies.py | 8.selenium_cookies.py | py | 325 | python | en | code | 0 | github-code | 1 |
70735105634 | import os, sys
import glob
import pandas as pd
from toil.realtimeLogger import RealtimeLogger
from Prop3D.parsers.container import Container
class USEARCH(Container):
IMAGE = 'docker://edraizen/usearch:latest'
LOCAL = ["usearch"]
RETURN_FILES = True
@staticmethod
def parse_uc_file(uclust_file):... | bouralab/Prop3D | Prop3D/parsers/USEARCH.py | USEARCH.py | py | 3,792 | python | en | code | 16 | github-code | 1 |
44574510671 | import time
from pages.register_page import RegisterPage
def test_register_a_new_user(browser):
page = RegisterPage(browser, 'http://80.249.147.135/user/register/')
page.open()
login = page.register_user()
page.should_be_redirect_to_login_page()
page.should_be_alert_success_message_on_login_page(... | Humoyun209/testStore | test_register_page.py | test_register_page.py | py | 338 | python | en | code | 1 | github-code | 1 |
34728957249 | from django.shortcuts import render, redirect
from .models import Device, VirtualDevice, Permissions, TrafficData, Device
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from .forms import DeviceFor... | Lema25/SmartTraffic_Control | smarttraffic/traffic/views.py | views.py | py | 5,227 | python | es | code | 0 | github-code | 1 |
71881631394 | class NEHService:
@staticmethod
def read_data_by_rows(filepath):
with open(filepath) as f:
f.readline()
n, m = [int(x) for x in next(f).split()]
data = [[int(x) for x in line.split()[1::2]] for line in f]
data = list(filter(lambda x: len(x) > 1, data))
... | maciejGolebio/SPD | neh/neh_service.py | neh_service.py | py | 458 | python | en | code | 0 | github-code | 1 |
17957990942 | """
Module for parsing segmented HamNoSys transcriptions.
"""
from pysign.data import HAMNOSYS
import attr
from tabulate import tabulate
def ascify(text, sep='.'):
return '.'.join(
HAMNOSYS.get(char, {"Name": '<'+char+'>'})["Name"] for char in
text).replace('.asciispace.', ' ')
def parse_... | lingpy/pysign | src/pysign/parse.py | parse.py | py | 34,106 | python | en | code | 0 | github-code | 1 |
42257866436 | # MA5060: NUMERICAL ANALYSIS
# TANMAY GOYAL
# AI20BTECH11021
# NOTE: 1. We take the input as Ax = b, and output x
# NOTE: 2. We assume A is a square matrix
import numpy as np
n = -1
while(n<=0):
n = int(input("Enter the dimension of the square matrix: "))
if(n <= 0):
print("Incorrect Dimensions. Ple... | tanmaygoyal258/MA5060-NumericalAnalysis | GaussElimination.py | GaussElimination.py | py | 1,755 | python | en | code | 0 | github-code | 1 |
4639975872 | import os
import subprocess
import sys
import time
import django
from django.conf import settings
from django.core import management
from shovel import task
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "djangorestblog")
)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
#... | MaciejPaszkowski/djangorest_simple_blog | shovel/shovel.py | shovel.py | py | 1,750 | python | en | code | 0 | github-code | 1 |
32179622727 | import datetime
from shifts import models
def prepare_prune_worker_shift(before):
d = (datetime.date.today() - before).days
assert d >= 7
beforeisoyear, beforeisoweek, beforeweekday = before.isocalendar()
assert beforeweekday == 0
beforeisoyearweek = 100 * beforeisoyear + beforeisoweek
(
... | Mortal/shiftplanner | shifts/prune.py | prune.py | py | 829 | python | en | code | 0 | github-code | 1 |
38612986384 | import state
import math
import collections
def label(graph):
GOAL_NUM = 5
goalTables = [
(i,obj)
for i,obj in enumerate(graph.nodes)
if obj[state.ObjType.Table] > .5
and obj[len(state.ObjType) + state.ObjAttrs.goal] > .5
]
tables = [
(i,obj)
for i,obj in enumerate(graph.nodes)
if obj[state.ObjType.... | lukeshimanuki/qqq | heuristic.py | heuristic.py | py | 1,226 | python | en | code | 0 | github-code | 1 |
11648173695 | #!/usr/bin/python -tt
""""
created on 17th March 2018
@author: Abhishek Chattopadhyay
FName: addTest
"""
from __future__ import print_function
import os
import sys
import datetime
import xml.etree.ElementTree as ET
BASEDIR = '.'
_template = BASEDIR + '/xml/templates/testtemplate.xml'
optDir = BASEDIR + '/xml/optio... | abhishekchattopadhyay/Octopus | automation/scripts/addTest.py | addTest.py | py | 10,993 | python | en | code | 1 | github-code | 1 |
75066813153 | # Fib.py
from math import *
def fib(n):
a, b = 0, 1
l = []
while a < n:
l.append(a)
a, b = b, a+b
num = eval(input('Input the number in the Fibonacci squence you wish to discover: '))
print(l[num - 1])
fib(factorial(500))
| TonyVH/Python-Programming | Chapter 03/Fib.py | Fib.py | py | 261 | python | en | code | 0 | github-code | 1 |
29608590768 | import json
def parse(path):
with open(path, 'r') as f:
lines = f.readlines()
lines = [line.strip().split(' ') for line in lines]
frame = []
S_index = []
for line_index, line in enumerate(lines):
line_array = []
for i in range(0, len(line), 2):
k, v = line[i].s... | rsmit3/hackaton-team-5 | parse_txt.py | parse_txt.py | py | 832 | python | en | code | 0 | github-code | 1 |
71131920673 | def checkio(game_result):
horizon = game_result
vertic = [''.join(h[i] for h in horizon) for i in range(3)]
NW = ''.join([game_result[i][i] for i in range(3)])
NE = ''.join([game_result[i][2-i] for i in range(3)])
all = [horizon, vertic, NW, NE]
for i in all:
if "XXX" in i:
r... | count99/practice | checkio/Home/XsandOsReferee.py | XsandOsReferee.py | py | 444 | python | en | code | 0 | github-code | 1 |
19031139452 | from abc import ABC
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from sklearn.utils import indexable
from sklearn.utils.validation import _num_samples
class SlidingTimeSeriesSplit(TimeSeriesSplit, ABC):
def __init__(self, n_splits: int, gap: int = 0):
super().__init__(n_splits... | vcerqueira/blog | src/cv_extensions/sliding_tss.py | sliding_tss.py | py | 1,953 | python | en | code | 15 | github-code | 1 |
34145590490 | # Run this script as `root user`. This is the only script that should ever be run as root user.
# Creats the first IAM admin that can add additional IAM users/roles/groups/etc..
try:
import boto3
except ImportError:
print(f'Error: boto3 is required. Please install.')
print(f'Try: pip install boto3')
def crea... | jim-hill-r/gmby6 | core/infra/provision/start.py | start.py | py | 1,020 | python | en | code | 0 | github-code | 1 |
36902006495 | '''
Descripttion:
version:
Author: LiQiang
Date: 2021-04-08 21:37:49
LastEditTime: 2021-04-09 19:34:00
'''
"""
主函数,用来提取关键词 、及主题句子
"""
import textRank
##########生成词云所用的库##########
import matplotlib.pyplot as plt
import PIL.Image as Image
import jieba
import numpy as np
import os
from wordcloud import ... | MarsCube/TextRank-1 | main_two_cloud.py | main_two_cloud.py | py | 4,182 | python | en | code | 0 | github-code | 1 |
15938992699 | #! venv/bin/python3
# -*- coding: UTF-8 -*-
import queue
from multiprocessing.managers import BaseManager
class QueueServer:
def __init__(self, ip='0.0.0.0', port=3000, authkey='lzw520'):
self._queue = queue.Queue()
self._ip = ip
self._port = port
self._authkey = authkey
... | dz85/DXDSTest | producer_consumer/queue_server.py | queue_server.py | py | 1,071 | python | en | code | 0 | github-code | 1 |
36795692494 | import sqlite3
import bcrypt
import time
import datetime
import math
# User(UserNumber, Name, Surname, Email_address, Password)
# UserNumber TEXT NOT NULL
# Password TEXT NOT NULL
# Email TEXT NOT NULL
# User_Type CHAR(1)
# Name TEXT NOT NULL
# PRIMARY KEY(UserNumber)
# Admin(UserNumber)
# UserN... | ardaa/CS281 | database.py | database.py | py | 19,973 | python | en | code | 0 | github-code | 1 |
41331723652 | # coding=utf-8
import random
import re
from django.db import models, transaction
from django.db.models import Count, Q
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
import django.utils.htt... | entropia/no-bot-is-perfect | nbip_server/nbip/models.py | models.py | py | 20,182 | python | en | code | 0 | github-code | 1 |
28238218682 | # -*- coding: utf-8 -*-
"""
This module contains any functions directly related to ROI operations and queries.
"""
import sys
import os.path
import math
import lib
import roi
import numpy as np
import logging
from HMR_RS_LoggerAdapter import HMR_RS_LoggerAdapter
base_logger = logging.getLogger("hmrlib." + os.path.ba... | mcbanjomike/Scripts-RayStation-4.7.2 | hmrlib/poi.py | poi.py | py | 25,576 | python | en | code | 3 | github-code | 1 |
6217795298 | for c in range(0, 5):
p = float(input('Digite o peso: '))
if c == 0:
m = p
n = p
else:
if p > m:
m = p
if p < n:
n = p
print('O maior peso é {}Kg e o menor é {}Kg'.format(m, n))
| Rodrigo98Matos/Projetos_py | Curso_em_Video_py3/ex055.py | ex055.py | py | 248 | python | pt | code | 1 | github-code | 1 |
25271619340 | """
The (U)nique (ID)entity of a cosmic particle entering earth's atmosphere.
Airshowers have UIDs. Airshowers may lead to a detection by the
instrument which in turn will create a record.
So record-IDs are an instrument-specific measure,
while UIDs are a simulation specific measure to keep track of all
thrown particle... | cherenkov-plenoscope/starter_kit | plenoirf/plenoirf/unique.py | unique.py | py | 1,279 | python | en | code | 0 | github-code | 1 |
33330576982 | from flask import Flask, render_template
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from bs4 import BeautifulSoup
import requests
#don't change this
matplotlib.use('Agg')
app = Flask(__name__) #do not change this
#insert the scrapping here
url_get = req... | kopikepu/Capstone_Webscrapping | app.py | app.py | py | 3,043 | python | en | code | 0 | github-code | 1 |
71395832033 | from datetime import datetime
from ninja import FilterSchema, Schema
from pydantic import Field, validator
class CourseIn(Schema):
title: str
description: str
slug: str
language: str
requirements: str
what_you_will_learn: str
level: str
categories: list[int] | None
instructors: li... | gabrielustosa/educa | educa/apps/course/schema.py | schema.py | py | 2,173 | python | en | code | 0 | github-code | 1 |
71059419553 | from django.contrib import admin
from .models import Service, AppointmentRequest, Appointment, EmailVerificationCode, Config
@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
list_display = ('name', 'duration', 'price', 'created_at', 'updated_at',)
search_fields = ('name',)
list_filter = ('d... | adamspd/django-appointment | appointment/admin.py | admin.py | py | 1,201 | python | en | code | 11 | github-code | 1 |
17223706930 | import multiprocessing
from multiprocessing import Pool
import time
# def spawn(num):
# print('Spawned!{}'.format(num))
# if __name__ == '__main__':
# s1 = time.time()
# for i in range(500):
# p = multiprocessing.Process(target=spawn,args=(i,))
# p.start()
# #p.join()
# e1 = time.time()
# s2 = time.time()
#... | Chaitanya-Varun/PythonConcepts | MultiProcessing.py | MultiProcessing.py | py | 645 | python | en | code | 0 | github-code | 1 |
26635775008 | """backend/main.py."""
from typing import Optional
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from maze_generator import ALPHA, DISCOUNT, EPSILON, NUM_EPISODES, MazeGenerator
from pydantic import BaseModel, validator
# Initialize FastAPI app
app = FastAPI(
title="DungeonMazeGenera... | mariaafara/DungeonMapGenerator | serving/api_main.py | api_main.py | py | 2,456 | python | en | code | 1 | github-code | 1 |
12780521041 | import logging
from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
from .convert import xlsx_to_jvfdtm
logging.basicConfig(level=logging.DEBUG)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:8080"
... | luminousai/rosetta | server/src/app.py | app.py | py | 591 | python | en | code | 0 | github-code | 1 |
2327947698 | """
server.py
version = 0.002
Remote Access Tool
Made by Lukas Alstrup
github.com/LukasAlstrup/rat
"""
import os
import socket
import base64
import random
import datetime
import time
from functions import *
import threading
import sys
from queue import Queue
import struct
import signal
#Welcome
print("[+] Welcome to ... | YagamiShadow/rat | Server/server.py | server.py | py | 3,392 | python | en | code | 0 | github-code | 1 |
31636907161 | import os
import json
from S3utility.s3_notification_info import parse_activity_data
from provider.storage_provider import storage_context
from provider import digest_provider, download_helper
import provider.utils as utils
from activity.objects import Activity
"""
DepositDigestIngestAssets.py activity
"""
class act... | elifesciences/elife-bot | activity/activity_DepositDigestIngestAssets.py | activity_DepositDigestIngestAssets.py | py | 4,579 | python | en | code | 19 | github-code | 1 |
70276393954 | """
Typical rock, paper, scissor game
The computer vs user
Once user choose to quit the game, the score will be shown
"""
import random
user_wins = 0 #tracking scores by creating this two variables
computer_wins = 0
options = ["rock", "paper", "scissor"]
options[0]
while True: #while loop
use... | mnanizan/games | rock_paper_scissor.py | rock_paper_scissor.py | py | 1,675 | python | en | code | 0 | github-code | 1 |
29687300166 | #!/usr/bin/env python3
#
# An HTTP server that's a message board.
# PRG(Post-Redirect-Get) design pattern : HTTP application의 매우 자주 사용되는 패턴임
# 실행 순서
# 1. localhost:8000/ 접속하면 do_GET을 call => html form내용이 화면에 보여짐
# ==> web browser에서 server를 call할 때 method의 default값은 GET 방식임
# 2. textarea에 데이터 입력하고 submit button누르면 do... | Leftddr/web_programming | Standard Web Library/1. Standard Web Library/5_MessageboardPartThree/MessageboardPartThree.py | MessageboardPartThree.py | py | 3,066 | python | ko | code | 0 | github-code | 1 |
798865698 | import utils
def get_relaunch_hits(tasks, args):
knowledge = utils.get_knowledge_file(args)
round_num = utils.get_round(args)
one_assignment_tasks, two_assignment_tasks = [], []
for task in tasks:
image_name = task['url']
if image_name not in knowledge:
two_assignment_tasks... | ShubhangDesai/visual-genome-test-curation | stage2/initial_launch.py | initial_launch.py | py | 1,722 | python | en | code | 0 | github-code | 1 |
39334745659 | from flask import Flask, jsonify, render_template, request
import numpy as np
import pandas as pd
import sklearn as sk
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.model_selection import train_test_split
app = Flask(__n... | bharathprakash321/ML-Review-Detector | app.py | app.py | py | 1,480 | python | en | code | 0 | github-code | 1 |
23869569915 | # -*- coding: utf-8 -*-
import logging
from datetime import date
from os import path
import xlsxwriter
from envios import Envio
from helpers import add_util_days, mailer, to_money
from pagamentos import Pagamento
from plataformas import PlataformaABC
logger = logging.getLogger(__name__)
CWD = path.dirname(path.absp... | rennancockles/LojaIntegrada_Scripts | lojaintegrada_scripts/commands/pedidos_pagos.py | pedidos_pagos.py | py | 9,362 | python | pt | code | 0 | github-code | 1 |
3120852172 | from tkinter import *
import os
import platform
import threading
from tkinter import messagebox
from rocketrecorder.open_folder import open_the_folder
if platform.system() == "Linux":
from rocketrecorder.linux_screen_recorder import (
record,
stop_video_recording,
)
else:
from rocketreco... | YuriiDorosh/Rocket-Recorder | rocketrecorder/rocket_recorder.py | rocket_recorder.py | py | 5,024 | python | en | code | 4 | github-code | 1 |
26280754005 | import websockets
import socket
import asyncio
import time
import glabalVal as g
temperature = "25"
humidity = "44"
def recUdp():
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 创建套接字,ipv4,UDP类型
local_addr = ("", 62436) # 设置本地的端口,一般不写ip地址
udp_socket.bind(local_addr) # 绑定套接字,不绑定端口号系统会随机分... | Ambiguous666/RemoteLabContral | sockettest.py | sockettest.py | py | 929 | python | en | code | 0 | github-code | 1 |
25021705065 | #mengimport library yang digunakan
from keras.models import load_model
from PIL import Image
from matplotlib import pyplot as plt
import numpy as np
#Membaca gambar menggunakan library PIL, pembaca juga
#dapat menggunakan library lain, seperti OpenCV
gambar1= Image.open("dataset/mnist/testing/0/img_108.jpg")
... | ardianumam/Data-Mining-and-Big-Data-Analytics-Book | edisi2/10.5.2 Menggunakan Model yang telah ditraining.py | 10.5.2 Menggunakan Model yang telah ditraining.py | py | 1,272 | python | id | code | 26 | github-code | 1 |
24105604048 | def f(fun, x):
y = eval(fun)
return y
def newton():
fun = input("ingresa tu función")
dfun = input("ingresa la derivada de tu función")
x0 = float(input("ingresa el valor inicial"))
tol = float(input("ingrese la tolerancia deseada"))
iteraciones = int(input("ingrese el número máxim... | cortegons/Analisis-numerico | códigos/newton.py | newton.py | py | 1,004 | python | es | code | 0 | github-code | 1 |
18596317269 | import numpy as np
import seaborn as sn
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
from matplotlib import pyplot
import pandas as pd
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
import data_operations
import constants
def naiv... | Cryoscopic-E/Data-mining-coursework1 | scripts/research_question.py | research_question.py | py | 3,150 | python | en | code | 0 | github-code | 1 |
42014273667 |
import zipfile
from functools import partial
import re
from collections import OrderedDict, Counter, defaultdict
import shutil
import os
from pprint import pprint
import datetime
import subprocess
import sys
from pathlib import Path
import mistune
from book_section import (CHAPTER, PART, SUBCHAPTER, TOC,
... | JoseBlanca/md2epub | epub_creation.py | epub_creation.py | py | 37,754 | python | en | code | 2 | github-code | 1 |
35885711050 | import socket
import subprocess
from datetime import datetime
# Clear the terminal screen
subprocess.call('clear', shell=True)
# Prompt the user to enter the target IP address or hostname
target = input("Enter the target IP address or hostname: ")
# Function to perform the port scanning
def port_scan(target):
tr... | Toothless5143/Port-Scanny | port-scanny.py | port-scanny.py | py | 1,303 | python | en | code | 0 | github-code | 1 |
25253660991 | import requests
import json
import time
import queue
import threading
proxy_list = []
def get_proxies():
url = "https://proxylist.geonode.com/api/proxy-list?limit=500&page=1&sort_by=lastChecked&sort_type=desc&speed=fast&protocols=socks4%2Csocks5"
response = requests.get(url)
response_status = response.st... | milan-sony/foxy | foxytest.py | foxytest.py | py | 3,006 | python | en | code | 0 | github-code | 1 |
29521286818 | #####################################################################################
## Procedure Name :
## Purpose :
## Arguments :
## Returns :
## Comments :
## Version : 1.0
## FilePath : \huawei-platform-script\LRR\get_most_popular.py
## Author : FANG
## Date ... | zff90/hua | get_most_popular.py | get_most_popular.py | py | 1,805 | python | en | code | 0 | github-code | 1 |
71494957473 | #!/usr/bin/env python3
# encoding: utf-8
"""
@version: v1.0
@author: XuanjieXiao
@license: BSD Licence
@contact: xuanjiexiao@163.com
@site: https://blog.csdn.net/weixin_40749043
@software: PyCharm
@file: linklist.py
@time: 2022/5/19 14:08
"""
class Node:
def __init__(self, item):
self.item = item
... | XuanjieXiao/PyTorch_Learn | structure/Structure/linklist.py | linklist.py | py | 739 | python | en | code | 1 | github-code | 1 |
24870777060 | #!/usr/bin/env python
"""Script that inserts NIfTI/JSON files into the database"""
import os
import sys
import lib.exitcode
import lib.utilities
from lib.lorisgetopt import LorisGetOpt
from lib.dcm2bids_imaging_pipeline_lib.nifti_insertion_pipeline import NiftiInsertionPipeline
__license__ = "GPLv3"
sys.path.appen... | aces/Loris-MRI | python/run_nifti_insertion.py | run_nifti_insertion.py | py | 5,231 | python | en | code | 10 | github-code | 1 |
31892002549 | import torch
from transfer import TransferNet
from utils import load_image
import torchvision.transforms as transforms
from torchvision.utils import save_image
# path
content_path = "content/chicago.jpg"
style_path = "styles/wave.jpg"
save_dir = ""
weight_path = "saved_weights/fst_wave.pth"
device = torch.device('cuda... | callmewenhao/FastStyleTransfer | predict.py | predict.py | py | 869 | python | en | code | 0 | github-code | 1 |
4521860662 | def all_pairs(array, sum_value):
occurrences = {}
register = {}
pairs = []
for key, value in enumerate(array):
look_for = sum_value - value
position = occurrences.get(look_for)
if position is not None and not register.get(f"{key},{position}"):
pairs.append((look_for,... | matheuscordeiro/random-problems | Cracking the Coding Interview/Cap 16/16.24_swap.py | 16.24_swap.py | py | 587 | python | en | code | 0 | github-code | 1 |
27272349876 | # 베르트랑 공준
def magic(num):
count = 0
for i in range(num+1, 2*num):
count += 1
for j in range(2, int(i**0.5)+1):
if i % j == 0:
count -= 1
break
return count
while True:
n = int(input())
if n == 0:
break
elif n == 1:
p... | honggom/TIL | problem-solving/baekjoon/math/4948.py | 4948.py | py | 374 | python | en | code | 0 | github-code | 1 |
8967238816 | import warnings
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
from urllib.parse import urlparse
import mlflow.sklearn
from mlflow.models.signature impo... | shippedbrain/shipped-brain-api | examples/elastic_net/train_and_log.py | train_and_log.py | py | 3,589 | python | en | code | 2 | github-code | 1 |
7611745222 | import gui
import pygame, sys
from pygame.locals import *
from tkinter import filedialog
WINDOW_DIMENSIONS = (700, 500)
BLACK = (0, 0, 0)
main_clock = pygame.time.Clock()
pygame.init()
pygame.display.set_caption('Play Aid!')
window = pygame.display.set_mode(WINDOW_DIMENSIONS, 0, 32)
font = pygame.font.SysFont("comics... | daveymclain/play_aid_app | main.py | main.py | py | 1,890 | python | en | code | 0 | github-code | 1 |
28651776589 |
file = open("mbox-short.txt")
dict = dict()
list = list()
for line in file :
line=line.lower()
for i in range (len(line)):
if line[i].islower():
dict[line[i]]= dict.get(line[i],0)+1
#for letter in line.split(""):
#dict[letter]= dict.get(letter,0)+1
#print (dict)
list = [(v,k) f... | amine-harrane/Python | Exercises/exe_10_3.py | exe_10_3.py | py | 356 | python | en | code | 0 | github-code | 1 |
43641338998 | #########################
# data_processing.py #
#########################
# Implements DataGenerator and batch sampling
# functionality for MAML. Originally based on
# functionality in CS330 Homework 2, Fall 2020.
# Written by Will Geoghegan for CS330
# final project, Fall 2020. Based on work by
# CS330 course staff.... | wdg3/regularized-meta-learning | src/data_processing.py | data_processing.py | py | 5,371 | python | en | code | 1 | github-code | 1 |
13857013396 | from inspect import _empty
from discord import player
from discord.ext import commands
import random
import traceback
class Connectx(commands.Cog):
def __init__(self, config, bot: commands.Bot):
self.bot = bot
self.config = config
self.game_list = {}
self.predefined_emoji_l... | JeppeLovstad/Discord-Meme-Delivery-Bot | BotModules/connectx.py | connectx.py | py | 6,037 | python | en | code | 0 | github-code | 1 |
5182513730 | import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras... | olliesguy/Machine-Learning | Neural Networks/Convolutional NN/largerConvolutionalNNwithKeras.py | largerConvolutionalNNwithKeras.py | py | 2,867 | python | en | code | 0 | github-code | 1 |
4709157122 | import easydict
from generator import KoGPT2IdeaGenerator
if __name__ == "__main__":
args = easydict.EasyDict({
'gpus' : 1,
'model_params' : 'model_chp/model_-last.ckpt'
})
evaluator = KoGPT2IdeaGenerator(args)
result = evaluator.generate("내구성")
print(result)
| madcamp-final/KoGPT2_generation | idea_generation/test.py | test.py | py | 304 | python | en | code | 0 | github-code | 1 |
6950578278 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch._jit_internal import Optional, Tuple
from torch.nn import grad # noqa: F401
from torch.nn.functional import linear
from torch.nn.modules.linear import _LinearWithBias
from torch.nn.parameter import P... | Flawless1202/Non-AR-Spatial-Temporal-Transformer | nast/models/utils/spatial_temporal_tensor_attention.py | spatial_temporal_tensor_attention.py | py | 16,739 | python | en | code | 73 | github-code | 1 |
1795182435 | import json
import time
import network
try:
with open('wlan.json') as f:
wlan_config = json.load(f)
hostname = wlan_config['HOSTNAME']
wlan_credentials = wlan_config['WLAN_CREDENTIALS']
assert len(wlan_credentials) > 0
except OSError:
raise Exception('wlan config does not exist, but is man... | dtn7/dtn7zero | micropython-lib/wlan.py | wlan.py | py | 3,021 | python | en | code | 2 | github-code | 1 |
27948279806 | import requests
from datetime import datetime
import os
GENDER = "male"
WEIGHT_KG = 70
HEIGHT_CM = 5.1
AGE = 20
APP_ID = "a824f715"
API_KEY = "e448d4180759e718cbd58d59be69abc2"
exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheet_endpoint = "https://api.sheety.co/4bbf6252f12ebc8107aab6bbe... | Fidelis-7/100-days-of-coding-in-python | 100-Days/Day_38/main.py | main.py | py | 1,611 | python | en | code | 2 | github-code | 1 |
39398181335 | #!/usr/bin/python3
"""print square with # characters"""
def print_square(size):
"""print square function
args:
size: length of the square
return:
a square drawn using # characters
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
... | ondanje/alx-higher_level_programming | 0x07-python-test_driven_development/4-print_square.py | 4-print_square.py | py | 516 | python | en | code | 0 | github-code | 1 |
5117953906 | message = input()
for i in range(len(message)):
Ascii = ord(message[i]) #Turning each letter of the sentece into Ascii
if Ascii == 32: #If the charater is a space
print(chr(Ascii), end="")
elif Ascii == 121: #If the charater is 'y'
print(chr(97), end="")
elif Ascii ... | brownae1331/2023-Brown | Python/Python Inro Tasks/13 Caesar Cypher.py | 13 Caesar Cypher.py | py | 546 | python | en | code | 0 | github-code | 1 |
11110614854 | class NodArbore:
def __init__(self, info, parinte=None):
self.info = info
self.parinte = parinte
def drumRadacina(self):
nod = self
l = []
while nod is not None:
l.append(nod)
nod = nod.parinte
return l[::-1]
def vizitat(self):
... | eduardpetre/AI | Lab8/main.py | main.py | py | 2,040 | python | en | code | 0 | github-code | 1 |
21807101085 | from numpy import load
import argparse
import pandas as pd
import numpy as np
import random
import os
df = pd.read_csv('dummy_embedding.csv')
df_X = df
N = 1
k = 5
n_iter = 150
X = df_X.to_numpy()
#Initialize k random centroides. Centroids can not be inizialized on the same point.
def inizialize_centroids(X, k):
... | Kerman-Sanjuan/Covid19-Tweet-Text-Clustering | clustering.py | clustering.py | py | 4,020 | python | en | code | 0 | github-code | 1 |
36865815414 | #!/usr/bin/env python
# coding: utf-8
# In[174]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from itertools import combinations
# ###... | TataAndBigData/AICORE_project_1_submission | Wine_project_Tanya.py | Wine_project_Tanya.py | py | 24,410 | python | en | code | 0 | github-code | 1 |
2616990888 | import json
import logging
from twitterauth.session import Session
from twitterauth.test import APITestCase
from twitterauth.configs import settings
from twitterauth.utils import helper
from twitterauth.utils import payload
LOGGER = logging.getLogger('twitter')
grant_type_missing_err_msg = 'Missing required parameter... | rohitkadam19/API-Automation | twitter_app_auth/tests/api/test_input_validation.py | test_input_validation.py | py | 3,892 | python | en | code | 1 | github-code | 1 |
73539569312 | import argparse
import csv
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("firstCol", help = "Number of the first column to match", type=int)
parser.add_argument("secondCol", help = "Number of the second column to match, multiple content", type=int)
parser.add_argument("-b", "... | EuphoricThinking/encyklopedia_lekow | encyklopedia_leków/rodzielCsv.py | rodzielCsv.py | py | 1,603 | python | en | code | 0 | github-code | 1 |
752490094 | # This program maps IPs to the ports open on them
with open("results.txt",'r') as f:
lines = f.readlines()
count = 0
mapping = {}
for line in lines:
if "Nmap scan report for" in line:
target = count
ports = []
while("_____" not in lines[target]):
if "/" in lines[target]... | NoctemLeges/ProxyAnalysis | IPtoPortMap.py | IPtoPortMap.py | py | 546 | python | en | code | 0 | github-code | 1 |
28013595614 | from citations import *
import sys, os
if __name__ == "__main__":
if len(sys.argv) < 2:
print("È necessario indicare come argomento export.xslx, il file Excel ottenuto")
print("esportando le proprie pubblicazioni seguendo questi passi:")
print("")
print(" 1. Cercarsi su https://arp... | robol/citation-count | citation-count.py | citation-count.py | py | 4,557 | python | it | code | 0 | github-code | 1 |
10600504602 | import pandas as pd
import numpy as np
import pickle
import torch
import random
import os
import sys
from pathlib import Path
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + './../..')
# MAX_LEN=12
# MAX_COND_SEQ=56
# MAX_PROC_SEQ=40
# MAX_MED_SEQ=15#37
# MAX_LAB_SEQ=899
# MAX_BMI_SEQ=118
def create_vo... | healthylaife/MIMIC-IV-Data-Pipeline | model/model_utils.py | model_utils.py | py | 15,348 | python | en | code | 102 | github-code | 1 |
5411922401 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from baselines.common.schedules import LinearSchedule
from baselines import logger
from model import NoisyDistDuelingConv, NoisyDistDuelingMLP, NoisyDuelingConv, No... | dai-dao/Rainbow-Net-Pytorch | test_atari.py | test_atari.py | py | 6,772 | python | en | code | 6 | github-code | 1 |
29123820566 | import os
import posixpath
import errno
import json
import resource
import sys
import shutil
import textwrap
import urllib.parse
import urllib.request
import warnings
import logging
# External modules
import click
import yaml
# We import botocore here so we can catch when the user tries to
# access AWS without having ... | nchammas/flintrock | flintrock/flintrock.py | flintrock.py | py | 45,036 | python | en | code | 629 | github-code | 1 |
20850779363 | import numpy as np
import cv2
import mss
import os
LABELS_PATH = os.path.dirname(__file__) + '/coco.names'
LABELS = open(LABELS_PATH).read().strip().split("\n")
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")
class Frame:
def __init__(self, source='webcam', screen_size=(800, 640)):
... | SarperYurttas/objectDetectionWithYOLO | object_detection/utils.py | utils.py | py | 1,013 | python | en | code | 0 | github-code | 1 |
4743048609 | import requests
from twilio.rest import Client
import os
import time
url = 'http://api.vk.com/method/'
token = os.environ['sms_token']
account_sid = os.environ['account_sid']
auth_token = os.environ['auth_token']
def get_json(user_id):
method = url + 'users.get'
data = {
'user_ids': user_id,
'... | zYoma/api_01_sms | main.py | main.py | py | 1,002 | python | en | code | 0 | github-code | 1 |
33091804418 | import solution
class Solution(solution.Solution):
def solve(self, test_input=None):
return self.smallerNumbersThanCurrent(test_input)
def smallerNumbersThanCurrent(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num_set = {}
# LeetCode do... | QuBenhao/LeetCode | problems/1365/solution.py | solution.py | py | 702 | python | en | code | 8 | github-code | 1 |
28410999980 | from django.conf import settings
from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.views.generic import TemplateView
import django_js_reverse.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^jsreverse/$', django_js_reverse.views.urls_js, name='js_rev... | pamella/pokebattle | pokebattle/urls.py | urls.py | py | 857 | python | en | code | 1 | github-code | 1 |
29927345087 | """
target_df 생성 (users에 없는 user_id 추가)
: 매개변수에는 dev_users_list / test_users_list 와 users.
"""
def target_df_generator(target_users_list, users):
print('1. target user의 dataframe 생성 중')
target_df = users[users['user_id'].isin(target_users_list)]
for target_user in target_users_list:
if (tar... | 2hyes/kakao-arena_brunch | target_df.py | target_df.py | py | 10,571 | python | ko | code | 0 | github-code | 1 |
21220358291 | from distutils.errors import CompileError
from traceback import print_tb
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
import torch
import transformers
from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler
from transformers import BertConfig, Bert... | Rolo123y/fnc-1-MSCI598 | fnc-bert-eval.py | fnc-bert-eval.py | py | 7,680 | python | en | code | 0 | github-code | 1 |
73374112673 | from http import HTTPStatus
import django.test
import django.urls
__all__ = []
class StaticURLTests(django.test.TestCase):
def test_homepage_endpoint(self):
response = django.test.Client().get(
django.urls.reverse("homepage:home"),
)
self.assertEqual(response.status_code, HT... | xtern0o/educational_django_project_yandex | lyceum/homepage/tests.py | tests.py | py | 623 | python | en | code | 1 | github-code | 1 |
72382523234 | from django.db import models
import auto_prefetch
from django_resized import ResizedImageField
from folio.utils.media import MediaHelper
from folio.utils.choices import PortfolioChoices
from folio.utils.models import NameBaseModel, ExperienceAndSchoolModel
from django.utils.text import slugify
from django.urls import ... | Gentility01/my-folio1 | core/models.py | models.py | py | 5,589 | python | en | code | 0 | github-code | 1 |
3646031553 | # . - один любой символ кроме \n
# ? - 0 или 1 вхождение шаблона слева
# + - 1 и более вхождений
# * - 0 и более вхождений или повторений
# \w - любая цифра или буква
# \W - все кроме
# \d - любая цифра
# \D - все кром цифр
# \s - любой "пробельный символ"
# \S - все кроме
# \b - граница слова
# [...] - символы в скобк... | UlrichKh/mentors_1 | rexp.py | rexp.py | py | 952 | python | ru | code | 0 | github-code | 1 |
40287460442 | #06-007.py
import re
pattern = re.compile(r'abc')
mc = re.search(pattern, '123abcdabc')
if mc :
print('{}~{}에 {}존재'.format(mc.start(), mc.end(), mc.group()))
else:
print('문자열에 패턴이 존재하지 않음')
#mc = pattern.search('123abcd')
#mc = re.search(r'abc', '123abcd')
| superf2t/TIL | PYTHON/BASIC_PYTHON/수업내용/06/06-007.py | 06-007.py | py | 313 | python | en | code | 1 | github-code | 1 |
20939299113 | # ========================
# Panda3d - panda3d_gpu.py
# ========================
# Panda3d imports.
from panda3d.core import NodePath, ClockObject, Filename, Texture
from panda3d.core import Shader, ShaderAttrib, PNMImage
from panda3d.core import LVector3i
'''# Local imports.
from etc import _path'''
# Basic Timer ... | svfgit/solex | gpu/panda3d_gpu.py | panda3d_gpu.py | py | 7,117 | python | en | code | 0 | github-code | 1 |
43816202446 | import numpy as np
from collections import defaultdict
from scipy import sparse
def trans_matrice(L,D,vois):
I,J,V=[],[],[]
for i in range(len(L)):
for l in vois[L[i]]:
j=D[l]
if j>=0:
I.append(i)
J.append(j)
V.append(1./len(vois[... | LeoReg/UniversalExplorationDynamics | Fig3/Percolation_exact_enum.py | Percolation_exact_enum.py | py | 1,605 | python | en | code | 1 | github-code | 1 |
6933911036 | import os
import json
import pytz
import logging
from flask_socketio import SocketIO, emit
from flask import (Flask, render_template, request, jsonify)
from pymongo import MongoClient
from threading import Thread, Event
from datetime import datetime
from convxai.utils import *
logging.basicConfig(format='%(asctime)s ... | huashen218/convxai | convxai/services/web_service/web_server.py | web_server.py | py | 6,524 | python | en | code | 9 | github-code | 1 |
74359950112 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/9 0:05
# @Author : SELF-T-YY
# @Site :
# @File : classical_sample_ambiguous_shortestPath.py
# @Software: PyCharm
import json
import networkx as nx
import sys
import numpy
fileWritePath = r'../data_forSystem/ieee_visC/IV_ambiguousBetweennessDa... | ShenXilong2000/newSystem | python/classical_sample_ambiguous_shortestPath.py | classical_sample_ambiguous_shortestPath.py | py | 3,102 | python | en | code | 0 | github-code | 1 |
16881549779 | # definimos una función para solicitar la carga del string
def carga():
return input("Ingrese un string: ")
# definimos una función para comprobar el total de vocales
def comprobar(string):
cant=0
lista=["a","e","i","o","u"]
for x in range(len(string)):
for k in range(len(lista)):
i... | shokone/python-exercices | tema_6_funciones/ejer2.py | ejer2.py | py | 587 | python | es | code | 9 | github-code | 1 |
25744704351 | import datetime
import os
import platform
class Clock:
def __init__(self):
self._stopwatch_counter_num = 10800
self._running = None
self._alarm_minute = None
self._alarm_hour = None
self._seconds = None
self._minutes = None
self._hour = None
self._a... | bailerG/clock_python_app | main.py | main.py | py | 2,054 | python | en | code | 0 | github-code | 1 |
14755309227 | #nested dictionary...............
people={1:{'name':'john','age':78,'sex':'Male'},2:{'name':'marry','age':68,'sex':'Female'}}
print(people)
print(people[1]['name'])
print(people[2]['sex'])
#Append...................
people[3]={}
people[3]['name']='Simran'
people[3]['age']=22
people[3]['sex']='female'
pe... | Simo0o08/Python-Assignment | Python assignment/Module 5/Dict.py | Dict.py | py | 645 | python | en | code | 0 | github-code | 1 |
35385777411 | from ast import Return
from enum import auto
import json
from lib2to3.pgen2 import token
from multiprocessing.util import abstract_sockets_supported
from textwrap import wrap
from flask import Flask, jsonify, request, make_response
from SQLalchemy import Autor, Postagem, db
import jwt
from datetime import datetime,time... | Glauberorionslt/apiblog-devaprender | app.py | app.py | py | 8,266 | python | pt | 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.