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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32506810174 | class Validation():
def __init__(self, filledList):
self.__filledBoard = filledList
def EmptyCells(self):
empty = 0
for row in range(9):
for col in range(9):
if(self.__filledBoard[row][col][0].get() == ""):
empty += 1
return empty > 64... | Acro146/Sudoku | validation.py | validation.py | py | 2,356 | python | en | code | 1 | github-code | 13 |
22073932904 |
import torch
import torch.nn as nn
import dgl.function as fn
import torch.nn.functional as F
from models.encoder.ogb_encoder import OGB_NodeEncoder, OGB_EdgeEncoder
from models.norm.gnn_norm import GNN_Norm
from models.pool.global_pool import GlobalPooling
from models.activation.local_activation import LocalActivatio... | chenchkx/graph_prediction | models/GCN.py | GCN.py | py | 4,565 | python | en | code | 0 | github-code | 13 |
29247022346 |
import os
import requests
import pprint
import json
limitParam = 10 #There are ~4200 matches of Platinum, ~2500 matches of Diamond, ~500 matches of Master
leagueParam = 4 #3 for Platinum, 4 for Diamond, 5 for Master
targetPath = "../../gggreplays/" #Target path for replay files. Make sure the folder exists!
pp = ppr... | JohnSegerstedt/DATX02-19-81 | gggreplays/getter.py | getter.py | py | 1,239 | python | en | code | 4 | github-code | 13 |
1430229989 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension('clpt_commons_bcn',
['clpt_commons_bcn.pyx'],
extra_compile_args=['/openmp',
'/O2', '/favor:INTEL64'],... | albertoferna/compmech | compmech/conecyl/clpt/setup_clpt_commons_bcn.py | setup_clpt_commons_bcn.py | py | 448 | python | en | code | null | github-code | 13 |
5156068393 | import pymongo
import dns
from scrapy.conf import settings
from scrapy.exceptions import DropItem
# totalrank logic
class MiaTotalPipeline(object):
canada = ['/piu.countryImg/031.png']
up = ['fa fa-caret-up']
down = ['fa fa-caret-down']
Lvtext = ['-']
toint = ['test']
blank = [' ']
def p... | Cmindo/mia | pipelines.py | pipelines.py | py | 6,366 | python | en | code | 0 | github-code | 13 |
71875407377 | import matplotlib.pyplot as plt
import seaborn as sns
FIGSIZE = (13, 4)
FONTSIZE_TEXT = 16
COLS_NUM = 2
def metrics_str(data, metrics):
met_str = ''
for met in metrics:
met_str += met.__name__+': '
met_outcome = met(data)
met_str += "{:.4f}".format(met_outcome) + '\n'
return met_s... | binkjakub/house-prices | notebooks/plot_utils.py | plot_utils.py | py | 1,209 | python | en | code | 0 | github-code | 13 |
16309628843 | #!/usr/bin/env python3
## https://github.com/zylai/ical-fake-meetings-generator/blob/master/iCal_Fake_Events_Generator.py
from pathlib import Path
import os.path
from os import path
import sys
from calendar import monthrange
from datetime import datetime,timedelta
import uuid
import random
import re
##### User-definab... | franceme/staticpy | cal.py | cal.py | py | 3,582 | python | en | code | 0 | github-code | 13 |
73783663698 | #!usr/bin/env
from os import listdir
from os.path import isdir, join
import sys
import a
import time
import re
from download import Download
from db import DB
counter = 1
path = "crawlers"
crawlers = [f for f in listdir(path) if isdir(join(path, f))]
for option in crawlers:
print("%d - %s" % (counter, optio... | LascaTorbot/crawler-surface | crawler.py | crawler.py | py | 2,452 | python | en | code | 0 | github-code | 13 |
363190571 | # Python_Intro
# Problem Set 3
#A series of exercises for CS50 hands-on projects
"""
This one's my approach to the "Grocery List" problem
"""
grocery = {} #A brand new dict
while True:
try:
item = input().upper()
if item in grocery:
grocery[item] += 1
else:
grocery[it... | JeremyJerez/Python_Set-_3 | grocery.py | grocery.py | py | 443 | python | en | code | 0 | github-code | 13 |
29060344413 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :Pytorch-MTCNN-68-FACE
@File :RNetDataGenerator.py
@Author :huangxj
@Date :2023/9/13 15:48
'''
import os
import pickle
import sys
import cv2
import numpy as np
import torch
from tqdm import tqdm
# sys.path.append("../")
from Dat... | huangxiaojun1996/Pytorch-MTCNN-68-FACE | Dataset/RNetDataGenerator.py | RNetDataGenerator.py | py | 6,350 | python | en | code | 2 | github-code | 13 |
72711103378 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AUTHOR: Geert Oosterbroek
DESCRIPTION:
Expanded nuclei approach to mRNA clustering,
current default method
"""
from read_roi import read_roi_zip
import pandas as pd
import numpy as np
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import o... | GeertO97/mRNA_clustering | expanded_nuclei.py | expanded_nuclei.py | py | 2,677 | python | en | code | 0 | github-code | 13 |
37905801574 | from random import randint
def random_list():
s = [randint(a, b) for i in range(c)]
print(s)
a = int(input("Start the list: "))
b = int(input("Finish the list: "))
c = int(input("Number of items: "))
random_list() | PavloStakhyra/Pytonhomework | random_list.py | random_list.py | py | 224 | python | en | code | 0 | github-code | 13 |
37190882865 | from pyproj import CRS, Transformer
from owslib.wmts import TileMatrix, TileMatrixSet
def _convert_coordinates(longitude: float, latitude: float) -> tuple[float, float]:
"""Takes GPS coordinates (EPSG 4326) as input and converts them to the Mercator projection (EPSG 3857).
This function is used to easil... | louistransfer/object_detection_ign | object_detection_ign/wmts/utils.py | utils.py | py | 2,955 | python | en | code | 4 | github-code | 13 |
10428914828 | # Morse Code
from morse import morse_code
def morsify(string):
morsified = ""
for letter in string:
morsified += morse_code[letter]
return morsified
stringIn = input("Enter the string to Morsify: ")
string = stringIn.upper()
print(morsify(string))
| RajaAjayKumar/BasicPythonProjects | Coding Challenges/10 Morse Code.py | 10 Morse Code.py | py | 284 | python | en | code | 0 | github-code | 13 |
39989362679 | from __future__ import unicode_literals
from __future__ import print_function
import torchtext
from collections import defaultdict,Counter
import codecs
from itertools import count
PAD_WORD = '<blank>'
UNK = 0
BOS_WORD = '<s>'
EOS_WORD = '</s>'
USE_RL = False
def __getstate__(self):
return dict(self.__dict__, stoi... | timchen0618/LaPat | baseline/gmdr/biwei_dialog0/dialog0/Seq2SeqWithRL/IO.py | IO.py | py | 3,154 | python | en | code | 2 | github-code | 13 |
35219634825 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 20 15:16:50 2016
@author: Hanbin Seo
"""
### import data
import urllib.request
import numpy as np
X_train, y_train = None, None
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/arcene/ARCENE/arcene_train.data"
with urllib.request.urlopen(url) as respone :... | 5eo1ab/study4machine-learning | A8-dim_reduction/seo8.py | seo8.py | py | 4,942 | python | en | code | 1 | github-code | 13 |
17939276580 | from graia.ariadne.app import Ariadne
from graia.ariadne.event.message import GroupMessage
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import *
from graia.ariadne.message.parser.twilight import Twilight, MatchResult
from graia.ariadne.model import Group, Member
from graia.say... | Rainbow-Project/bot_rain_py | modules/moegirl_info.py | moegirl_info.py | py | 2,428 | python | en | code | 4 | github-code | 13 |
17953740790 | class Rectangle:
def CalculateArea(self):
# This function will accept input of length and breadth and calculate area
self.width=int(input("Enter Length:"))
self.height=int(input("Enter breadth:"))
area=self.width*self.height
print(area)
return (area)
d... | LakshitaNarsian/IT-TOOLS | class rectangle.py | class rectangle.py | py | 1,214 | python | en | code | 0 | github-code | 13 |
73693524817 | # -*- coding: utf-8 -*-
'''
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
'''
distancia_total = int(input())
combustivel_gasto = float(input())
consumo = distancia_total / combustivel_gasto
print(f"{consumo:.3f} km/l") | AkiraTorres/beecrowd | Respostas/Python/1014.py | 1014.py | py | 256 | python | pt | code | 3 | github-code | 13 |
19241526997 | from django.core.management import BaseCommand
from django.db import transaction
from open_api.recuperation_facility import get_api_data
from ...models import Facility
# ./manage.py setapidata 실행
class Command(BaseCommand):
def handle(self, *args, **options):
try:
# transaction 을 사용해 Excepti... | kimdohwan/Place-For-Elderly | app/facilities/management/commands/setapidata.py | setapidata.py | py | 1,265 | python | ko | code | 0 | github-code | 13 |
37856109203 | class Hero:
hp=0
power=0
name=""
def __init__(self, hp, power,name):
self.hp = hp
self.power = power
self.name = name
#回合格斗方法
def fight(self,enemy):
self.hp = self.hp - enemy.power
enemy.hp = enemy.hp -self.power
#我方胜利,输出英雄台词
if self.hp > ... | lqin007/testDemo | PythonPractice/heroPractice/hero.py | hero.py | py | 756 | python | en | code | 0 | github-code | 13 |
39686170092 | # Name: Downloading Files With Certutil
# RTA: certutil_webrequest.py
# ATT&CK: T1105
# Description: Uses certutil.exe to download a file.
import common
MY_DLL = common.get_path("bin", "mydll.dll")
@common.dependencies(MY_DLL)
def main():
# http server will terminate on main thread exit
# if daemon is True
... | endgameinc/RTA | red_ttp/certutil_webrequest.py | certutil_webrequest.py | py | 708 | python | en | code | 1,004 | github-code | 13 |
28703077444 | import pygame
from pygame import Rect
from pygame import Surface
import piece
from piece import *
class entities():
def __init__(self, _list = []):
self._list = _list
def addEntity(self, toAdd):
self._list.append(toAdd)
def getLength(self):
return len(self._list)
def getEntityByID(self, ID):
for i in se... | jyota/vHunter | entities.py | entities.py | py | 574 | python | en | code | 0 | github-code | 13 |
30583877128 | # -*- coding: utf-8 -*-
import hashlib
from copy import deepcopy
import numpy as np
from ge.bpmc.api.schemas.bpm import CriteriaModel, OverlayModel
from ge.bpmc.api.schemas.default import (AngleModel, BigIntModel, BooleanModel,
DoubleModel, DoublePointModel,
... | dbenlopers/SANDBOX | misc/bpm_cloud/ge.bpmc/ge/bpmc/business/translator.py | translator.py | py | 15,434 | python | en | code | 0 | github-code | 13 |
69970886738 | import pygame
from castspellaction import *
from color import *
from gamestat import *
from actor import *
from spell import *
from vector import *
class Player(Actor):
def __init__(self, level):
Actor.__init__(self, level)
self.hp = GameStat(20)
self.mana = [GameStat(10) for _ in range(3)... | kotrenn/crystal | player.py | player.py | py | 2,061 | python | en | code | 0 | github-code | 13 |
477195461 | from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .validators import currency_available_validator, empty_params_validator, date_validator, float_validator
from exchange_rate.utils import get_currency_rates, get_exchanged_currency_amount, ... | PedroDDiez/django-adapters | api/views.py | views.py | py | 3,265 | python | en | code | 1 | github-code | 13 |
35175424568 | import numpy as np
import bisect
class PeakInfo:
def __init__(self, name, prev_name, path, is_watched):
self.name = name
self.prev_name = prev_name
self.path = path
self.is_watched = is_watched
def __lt__(self, other):
if self.is_watched == other.is_watched:
... | Sergey-Dvoraninovich/SAiIO | LR6.py | LR6.py | py | 2,977 | python | en | code | 0 | github-code | 13 |
12098598027 | # Problem 4:
# Largest Palindrome Product
#
# Description:
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of
# two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
from math import cei... | mihiryerande/project-euler-004 | main.py | main.py | py | 2,411 | python | en | code | 0 | github-code | 13 |
32044834954 | import requests
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display,Image,display_jpeg
from google.colab import drive
drive.mount('/content/drive/')
path = '/content/drive/My Drive/Colab Notebooks/youtube_app'
df = pd.read_table(path+'... | tsurusekazuki/YouTure-prot | models/youtube/download-thumbnail.py | download-thumbnail.py | py | 1,545 | python | en | code | 0 | github-code | 13 |
13513989946 | from ebcli.core.abstractcontroller import AbstractBaseController
from ebcli.resources.strings import strings, flag_text
from ebcli.operations import listops
class ListController(AbstractBaseController):
class Meta:
label = 'list'
description = strings['list.info']
usage = 'eb list [options... | aws/aws-elastic-beanstalk-cli | ebcli/controllers/list.py | list.py | py | 756 | python | en | code | 150 | github-code | 13 |
35857081437 | #!/usr/bin/python3
#(c) 2017 Todd Riemenschneider
#
#Enable Multiprocessing
from multiprocessing import Pool
#getpass will not display password
from getpass import getpass
#ConnectionHandler is the function used by netmiko to connect to devices
from netmiko import ConnectHandler
#Time tracker
from time import time
#cr... | twr14152/Network-Automation-Scripts_Python3 | netmiko/NetworkDiscovery/host_file_and_script/archive/discovery_script.py | discovery_script.py | py | 4,223 | python | en | code | 52 | github-code | 13 |
2929216459 | import json
from functools import partial
from tornado.httpclient import AsyncHTTPClient
GEMS_URL = 'https://rubygems.org/api/v1/versions/%s.json'
def get_version(name, conf, callback):
repo = conf.get('gems') or name
url = GEMS_URL % repo
AsyncHTTPClient().fetch(url, user_agent='lilydjwg/nvchecker',
... | amazingfate/nvchecker | nvchecker/source/gems.py | gems.py | py | 523 | python | en | code | null | github-code | 13 |
73727892176 | '''
> shortest_path(map_40, 5, 34)
[5, 16, 37, 12, 34]
'''
import math
def shortest_path(M,start,goal):
### data in M
## 1. M.intersections - dict - x,y coordinate of every node.
# {0: [0.7801603911549438, 0.49474860768712914],
# 1: [0.5249831588690298, 0.14953665513987202],
# 2: [0.8085335344099086, 0.769633... | Xing-Kai/Intro_to_Self_Driving_Car | 6_Navigating_Data_Structures/Project_Implement_Route_Planner/student_code_02.py | student_code_02.py | py | 3,143 | python | en | code | 1 | github-code | 13 |
72755316178 | import json
from django.http import HttpResponse
from hashlib import md5
from scratch_api.models import FavoriteProduction, User, Production,Gallery, LikeProduction, CommentEachOther,FavoriteGallery,LikeGallery
def website_ajax_favorite(request, production):
"""
ajax favorite a production
:param request:
... | liqiniuniu/- | website/ajax_views.py | ajax_views.py | py | 7,129 | python | en | code | 0 | github-code | 13 |
71698214098 | from flask import Flask, render_template, request
from textblob import TextBlob
app = Flask(__name__)
def predict_sentiment(text):
analysis = TextBlob(text)
# Use TextBlob's polarity to predict sentiment
if analysis.sentiment.polarity > 0:
return 'Positive'
elif analysis.sentiment.po... | smartinternz02/SI-GuidedProject-612159-1699512337 | app.py | app.py | py | 737 | python | en | code | 0 | github-code | 13 |
37503651959 | #!/usr/bin/env python3
def calculate():
limit = 10**6
solutions = [0] * limit
for i in range(1, limit * 2):
for j in range(i // 5 + 1, (i + 1) // 2):
temp = (i - j) * (j * 5 - i)
if temp >= limit:
break
solutions[temp] += 1
answer = solut... | sayantan3/project-euler | pep_135.py | pep_135.py | py | 410 | python | en | code | 0 | github-code | 13 |
30138679522 | from tests.source.shotgun.base import ShotgunTestCase
from zou.app.models.project import Project
from zou.app.models.person import Person
from zou.app.models.task_type import TaskType
from zou.app.models.task_status import TaskStatus
from zou.app.services import assets_service, shots_service, tasks_service
class Im... | cgwire/zou | tests/source/shotgun/test_shotgun_import_tasks.py | test_shotgun_import_tasks.py | py | 6,363 | python | en | code | 152 | github-code | 13 |
11562287151 | import os
from starter_code_section_5.models.item import ItemModel
from starter_code_section_5.tests.base_test import BaseTest
class ItemModelIntegrationTest(BaseTest):
# printing out the running unit test file location/name
print("Running unit tests from: " +
os.path.dirname(__file__) +
... | ikostan/automation_with_python | starter_code_section_5/tests/integration/models/test_item.py | test_item.py | py | 930 | python | en | code | 0 | github-code | 13 |
31504405971 | from django.shortcuts import render,redirect, get_object_or_404, reverse
from .forms import ArticleForm, CommentForm
from django.contrib import messages
from .models import Article, Comment, Tag
from django.utils.text import slugify
from django.contrib.auth.decorators import permission_required, login_required
from dja... | LitmusPaper/zaknews | article/views.py | views.py | py | 2,819 | python | en | code | 0 | github-code | 13 |
7679304435 | import os
# pid = os.fork()
# if pid == 0:
# print("I am from father process")
# else:
# print("I am from child process")
from multiprocessing import Process, Pool
# 子进程要执行的代码
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid()))
if __name__=='__main__':
print('Parent proc... | JesseCodeBones/python_study_2 | process_1.py | process_1.py | py | 638 | python | en | code | 0 | github-code | 13 |
70505585299 | # coding: utf-8
import base64
import datetime
import threading
def data_uri(data):
return 'data:image/png;base64,' + base64.b64encode(data)
def daterange(start_date=None, end_date=None, date_range=None):
if date_range:
start_date = min(date_range)
end_date = max(date_range)
for n in xra... | berkerpeksag/github-badge | app/helpers.py | helpers.py | py | 712 | python | en | code | 290 | github-code | 13 |
3638873510 | import json
import argparse
import numpy as np
from distutils.version import LooseVersion
parser = argparse.ArgumentParser(description="Make a combined arch-specific core package list")
parser.add_argument("--linux",
help="conda list json file with list of linux packages")
parser.add_argument("--os... | ddkauffman/skare3 | pkg_defs/ska3-core/combine_arch.py | combine_arch.py | py | 1,880 | python | en | code | 0 | github-code | 13 |
26260455223 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 12:23:25 2020
@author: vinmue
"""
import numpy as np
from tensorflow.keras.layers import Dense, Dropout, Input, BatchNormalization
from tensorflow.keras.models import load_model, clone_model
import tensorflow.keras as keras
from tensorflow.keras.optimizers ... | ViniTheSwan/ReinforcementTrading | parent/Trading/RL/DeepQLearningEager.py | DeepQLearningEager.py | py | 6,131 | python | en | code | 1 | github-code | 13 |
13379124013 | import errno
import itertools
import os
import sys
# pip install pptree
import pptree
# To make the start,end line working, put this line of code before importing ElementTree
sys.modules['_elementtree'] = None
import xml.etree.ElementTree as ET
# To make this working, use python 3.8 or older version
class LineNumber... | gsiqi/xmlTreeMatching | treeMatch.py | treeMatch.py | py | 9,130 | python | en | code | 0 | github-code | 13 |
16755437255 | """Test cnot."""
import numpy as np
from toqito.matrices import cnot
def test_cnot():
"""Test standard CNOT gate."""
res = cnot()
expected_res = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
bool_mat = np.isclose(res, expected_res)
np.testing.assert_equal(np.all(bool_mat), Tr... | vprusso/toqito | toqito/matrices/tests/test_cnot.py | test_cnot.py | py | 324 | python | en | code | 118 | github-code | 13 |
10347857061 | from __future__ import print_function
import argparse
import sys
import ijson # .backends.yajl2_cffi as ijson
import random
import os
from program_helper.ast.parser.ast_exceptions import TooLongBranchingException, TooLongLoopingException, \
VoidProgramException, TooManyVariableException, UnknownVarAccessExcepti... | rohanmukh/nsg | data_extraction/data_reader/data_reader.py | data_reader.py | py | 10,723 | python | en | code | 20 | github-code | 13 |
71601962259 | import queue
import time
import pygame
import random
pygame.init()
width = 800
height = 800
rows = 10
cols = 10
mines = 15
size = width / rows
num_font = pygame.font.SysFont('Arial', 25, bold=True)
lost_font = pygame.font.SysFont('Arial', 45, bold=True)
time_font = pygame.font.SysFont('Arial', 35, bold=True)
num_... | meirrrrr/saper_game_by_meirrrr | main.py | main.py | py | 6,055 | python | en | code | 0 | github-code | 13 |
13998103670 | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from my_fake_useragent import UserAgent
import requests
import json
import time
# 通过webdriver获取页面内容
def getDrivertDriverByWebdriver(url):
opt=webdriver.ChromeOptions()
# 请求头伪装
opt.add_argument('--user-agent=%s' % UserA... | Jsonyuanlairuci/python | Response.py | Response.py | py | 1,969 | python | en | code | 1 | github-code | 13 |
14671935328 | # _*_ coding=utf-8 _*_
# 冒泡排序,时间复杂度O(n²)
def bubble_sort(num):
"""
如果冒泡排序中的一次排序没有发生交换,则说明列表已经有序,可以直接结束算法
:param num:
:return:
"""
for i in range(len(num) - 1):
exchange = False
print(num)
for j in range(len(num) - 1 - i):
if num[j] > num[j + 1]:
... | IsaacNewLee/BubbleSort | bubble_sotr.py | bubble_sotr.py | py | 606 | python | zh | code | 0 | github-code | 13 |
30796376367 | #!/usr/bin/env python3
__version__ = "0.1.0"
import util
from nlp_02 import nlp_025
"""
25. テンプレートの抽出
記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し,
辞書オブジェクトとして格納せよ.
https://ja.wikipedia.org/wiki/Template:基礎情報_国
"""
def test_execute():
excepted = util.expected_file(__file__)
actual = util.dict2tsv(nlp_025.execute(".... | bulldra/nlp100 | tests/nlp_02/test_nlp_025.py | test_nlp_025.py | py | 510 | python | ja | code | 0 | github-code | 13 |
72690348177 | from typing import Literal, Dict, Any
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from .base import BaseDataset, collate_fn
class MVTecDataset(BaseDataset):
CLASSES = ('background', 'nut', 'wood_screw', 'lag_wood_screw', 'bolt', # 0-4
'black_oxide_screw', 'shiny_screw',... | crazyboy9103/oriented_detection | datasets/mvtec.py | mvtec.py | py | 4,092 | python | en | code | 0 | github-code | 13 |
73515789456 | from openpyxl import Workbook, load_workbook
import decimal
from datetime import datetime
# DBからデータを読み取ってExcelファイルに書き出す場合、
# セルの書式など気にする必要が無ければ、pandasの方が便利、より少ない行で実装できる
wb = Workbook()
ws = wb.active
ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
# 日本語特に問題なし
ws2.cell(row=1, column=1, valu... | Fumi76/py_openpyxl_example | write.py | write.py | py | 1,916 | python | ja | code | 0 | github-code | 13 |
27580494813 | import src.constants as c
from src.pre_process import extract_features
from src.test_model import batch_cosine_similarity
from scipy.io.wavfile import read
import numpy as np
import base64
from pydub import AudioSegment
from src import silence_detector
import librosa
def clipped_audio(x, num_frames=c.NUM_FRAMES):
... | kienlanman/api-speaker-recognition | src/service/TransferAudio.py | TransferAudio.py | py | 3,269 | python | en | code | 0 | github-code | 13 |
11191694029 | names=[]
usernames=[]
entries=int(input("No of Entries : "))
for i in range(0,entries):
names.append(input("Entry {} ".format(i+1)))
for j in range(0,entries):
usernames.append(names[j].lower().replace(" ","_"))
for user in usernames:
print (user.title().replace("_"," "))
print(usernames)
| AshuAhlawat/Python | Basics/05loops1List2.py | 05loops1List2.py | py | 308 | python | en | code | 1 | github-code | 13 |
43828562963 | # Analytical computations
f, ax = plt.subplots(1,1)
f.suptitle('G* function with variable coefficients')
# import modules
import numpy as np
def Vi(ai,alphai):
return alphai**2/((1+2*alphai)*(1+ai)**2)
def V(a_prms,alpha):
D=1
for ai,alphai in zip(a_prms,alpha):
D*=(1+Vi(ai,alphai))
retu... | utsekaj42/enthral_summer_school_2021 | Day 3/python_source/interactive_gstar_function.py | interactive_gstar_function.py | py | 2,515 | python | en | code | 1 | github-code | 13 |
31321867954 | from abc import ABC
from dataclasses import dataclass, field
import datetime
import os
from typing import Union
import copy
import yaml
import re
from dateutil.relativedelta import relativedelta
from datetime import date
__path: str = os.environ['TSDB_DATA']
parser_regex = '^([A-Za-z0-9\s\-]*)(_[A-Za-z0-9\s\-]*)?(_[A... | imry-rosenbuam/jabberjaw | jabberjaw/utils/mkt_classes.py | mkt_classes.py | py | 8,183 | python | en | code | 0 | github-code | 13 |
26414737482 | from ursina import *
import Game
from ..Screen import Screen
from GameStates import GameStates
from Graphics.Container import Container
from Graphics.UIs.Inventory.Inventory import Inventory
from Overlays.Notification import Notification
from .SelectionStatus import SelectionStatus
from .MenuButton import MenuButton
... | GDcheeriosYT/Gentrys-Quest-Ursina | Screens/Selection/Selection.py | Selection.py | py | 5,041 | python | en | code | 1 | github-code | 13 |
40263793600 |
import pandas as pd
from sklearn.decomposition import PCA
import numpy as np
def main():
xTrain=pd.read_csv("xTrain_normal.csv")
xTest=pd.read_csv("xTest_normal.csv")
pca=PCA()
X_pca_train=pca.fit_transform(xTrain)
X_pca_test=pca.transform(xTest)
np.savetxt("pca_train.csv",X_pca_train,delimit... | yikevding/cs334-machine-learning | hw5/q1b.py | q1b.py | py | 920 | python | en | code | 0 | github-code | 13 |
17380727562 | from random import randint
print('W E L C O M E T O')
print('*****' * 6 + '*')
print('*****ROCK, PAPER, SCISSORS*****')
print('*****' * 6 + '*')
t = ['Rock', 'Paper', 'Scissors']
computer = t[randint(0, 2)]
player = False
while player == False:
player = input('Rock[R], Paper[P], Scissor... | edake1/Programming-Projects | rock_paper_scissors.py | rock_paper_scissors.py | py | 1,833 | python | en | code | 0 | github-code | 13 |
44040932896 | from importlib.util import source_hash
fruits=[]
fruits.append("mango")
fruits.append("apple")
fruits.append("banana")
fruits.append("kiwi")
print(fruits)
if 'Mango' in fruits:
print(1)
else:
print(0)
fruits.insert(2,"strawberry")
print(fruits)
dry_fruits=["almonde","cashew","walnut", "dates", "rasins"]
... | itzzyashpandey/python-data-science | data structures/list_fun.py | list_fun.py | py | 564 | python | en | code | 0 | github-code | 13 |
20461267249 | #!/usr/bin/env python3
import valve.rcon
from flask import Flask, request, redirect
app = Flask(__name__)
fields_translate = {
"CPU": "srcds_cpu",
"NetIn": "srcds_netin",
"NetOut": "srcds_netout",
"Uptime": "srcds_uptime",
"Maps": "srcds_maps",
"FPS": "srcds_fps",
"Players": "srcds_players"... | ezskillgg/srcds-exporter | srcds-exporter.py | srcds-exporter.py | py | 1,999 | python | en | code | 0 | github-code | 13 |
8821564512 | from tkinter import *
from tkinter import ttk
from tkinter.font import *
import cassiopeia
from tracker import *
import os
import configparser
class Window:
def __init__(self):
global nicknameWindow
nicknameWindow = Tk()
init()
labelAboutPlayer()
inputField()
lastUs... | May2Beez/LoL-Summoners-Tracker | window.py | window.py | py | 4,791 | python | en | code | 0 | github-code | 13 |
9087968850 | #https://www.acmicpc.net/problem/2696
#백준 2696번 중앙값 구하기 (자료구조)
#import sys
#input = sys.stdin.readline
import heapq
t = int(input())
for _ in range(t):
n = int(input())
nums = []
temp = n
while temp > 0 :
data = list(map(int, input().split()))
nums.extend(data)
temp -= 10
r... | MinsangKong/DailyProblem | 07-20/4-1.py | 4-1.py | py | 1,129 | python | en | code | 0 | github-code | 13 |
37945008218 | ###############################################################
# 25/02/2007 Andrzej Olszewski
# jobOptions to run Hydjet generation
# Random number seed setting via nseed
# 15/03/2008 Andrzej Olszewski
# Updated for configurables
#==============================================================
#########################... | rushioda/PIXELVALID_athena | athena/Generators/Hydjet_i/share/hydjet.minbias.pbpb5520.r12345.job.py | hydjet.minbias.pbpb5520.r12345.job.py | py | 3,686 | python | en | code | 1 | github-code | 13 |
4788017218 | import re
text = input()
matched = re.finditer(r"(^|(?<=\s))-?([0]|[1-9][0-9]*)(.[0-9]+)?($|(?=\s))", text)
output = []
for match in matched:
output.append(match.group())
print(" ".join(output)) | Iskren-Dimitrov/SoftUni_Python_Fundamentals | lab_regular_expressions/match_numbers.py | match_numbers.py | py | 202 | python | en | code | 0 | github-code | 13 |
36581334432 | import pynput
from pynput.keyboard import Key, Listener
keys = []
def on_press(key):
keys.append(key)
write_file(keys)
def write_file(keys):
with open('log.txt', 'w') as f:
for key in keys:
#removing ''
k = str(key).replace("'", "")
f.write(k)
#explicitly adding a space after ev... | hastagAB/Awesome-Python-Scripts | Keylogger/script.py | script.py | py | 526 | python | en | code | 1,776 | github-code | 13 |
21358514143 | import time
import cv2
import os
import numpy
import torch
import clip
import numpy as np
from PIL import Image
from scipy import spatial
from config import CLIP_MODEL_PATH, OP_NUM_THREADS
from service.image_infer import get_ui_infer
from dbnet_crnn.image_text import ImageText
from service.image_utils import get_roi_... | Meituan-Dianping/vision-ui | service/image_trace.py | image_trace.py | py | 10,854 | python | en | code | 185 | github-code | 13 |
17703732109 | from django.core.management.base import BaseCommand, CommandError
from apps.orders.models import Order, OrderItem
from apps.shipments.models import Shipment, ShipmentLog
from django.utils import timezone
from django.contrib.auth.models import User
import requests
import json
import datetime
API_Key = 'b313e7c9662a0287... | oshevelo/sep_py_shop | FirstShop/apps/shipments/management/commands/deliverytrack.py | deliverytrack.py | py | 1,310 | python | en | code | 0 | github-code | 13 |
13284799256 | import random
import time
import os
print("你好,现在你有10秒钟的时间记忆下列物品及其编号")
things=["苹果","香蕉","橙子","梨子","猕猴桃","柚子","猴魁","铁观音","毛笔","宣纸"]
for i in range(10):
print(i,":",things[i])
time.sleep(10)
os.system("cls")
n=0
t2=random.sample(things,5)
for i in t2:
ans=int(input(i+"的编号是:"))
if i==things[ans]:
... | hesongji/python- | 小游戏.py | 小游戏.py | py | 509 | python | en | code | 1 | github-code | 13 |
36733558654 | from django.http import HttpResponse,HttpResponseNotFound,HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404,get_list_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate,login,logout
from django.... | jlev/Boycott-Toolkit | community/views.py | views.py | py | 9,679 | python | en | code | 6 | github-code | 13 |
30138655120 | import sys
def find_max_crossing_subarray(A, low, mid, high):
left_sum = -sys.maxsize
sum = 0
max_left = -1
for i in range(mid, low-1, -1): # important that you go "downto", because you need to know what comes AFTER idx i (we are finding the CROSS sum)
sum += A[i]
if sum > left_sum:
... | Xtrah/TDT4120 | Python/DivideAndConquer/MaximumSubarray.py | MaximumSubarray.py | py | 1,696 | python | en | code | 6 | github-code | 13 |
35345446024 | import os
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import Pipeline.UI.main_ui as master_ui
import maya.OpenMayaUI as omui
from Pipeline.media.UI_Converter import Convert_Ui
import Pipeline
class Converter(object):
def __init__(self):
# all the relative folders for our project
... | underminerstudios/ScriptBackup | MayaAssetPipeline/Maya_Tools/Pipeline/UI/Pipeline_Gui.py | Pipeline_Gui.py | py | 2,409 | python | en | code | 2 | github-code | 13 |
27342569784 | #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import json
INFO = {
'version': '0.4-dev',
}
def main():
"Run functions specified on the command line"
if len(sys.argv) <= 1:
raise SystemExit("no command(s) specified")
cmds = sys.argv[1:]
if '-h' in cm... | teamsspaul/NUEN629 | Lab_Paste/NUEN629/LABS/LAB0/pyne-0.4/configure.py | configure.py | py | 4,236 | python | en | code | 1 | github-code | 13 |
16184350253 | """
AC(https://www.acmicpc.net/problem/5430)
- 함수는 R(뒤집기) D(버리기)
- R은 배열에 있는 숫자의 순서를 뒤집는 함수고, D는 첫 번째 숫자를 버리는 함수.
배열이 비어있는데 D를 사용한 경우에는 에러가 발생
- 함수는 조합해서 사용이 가능
- 입력 : 테스트 케이스의 개수 T(최대 100)
수행할 함수 P(1 <= p의 길이 <= 100,000)
배열에 들어있는 수의 개수 n(0 <= n <= 100,000)
... | akana0321/Algorithm | BaekJoon/Implementation/AC_5430.py | AC_5430.py | py | 1,822 | python | ko | code | 0 | github-code | 13 |
39115949086 | import os
import yaml
from typing import Dict, Any
class KaggleDbtSourceTableColumn:
"""A class representig a dbt source column, enriched with the kaggle metadata"""
def __init__(self, dbt_yaml: Dict[str, Any]):
"""Constructs all necessary attributes for the object from a parsed dby .yml file"""
... | Beetelbrox/accident-information-challenge | airflow/plugins/kaggle_elt/kaggle_dbt_source.py | kaggle_dbt_source.py | py | 3,428 | python | en | code | 0 | github-code | 13 |
41266676814 | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
outputs = []
n = len(nums)
def backtrack(index, k, path):
if len(path[:]) == k:
outputs.append(path[:])
for i in range(index, n):
path.append(nums[i])
... | AshwinRachha/LeetCode-Solutions | 78-subsets/78-subsets.py | 78-subsets.py | py | 468 | python | en | code | 0 | github-code | 13 |
34815806735 | import numpy as np
from heapq import nlargest
from functools import reduce
"Horrible, embarrassing code."
def main() -> None:
with open("inputs/day9_input.in", "r") as f:
heightmap = []
lows = []
result_p1 = 0
result_p2 = []
for line in f.readlines():
heightmap... | berkentekin/Advent_of_code_2021 | day09/day9.py | day9.py | py | 2,420 | python | en | code | 0 | github-code | 13 |
27648906983 | """
Made by @plutus
"""
import json
from types import SimpleNamespace
import requests
from traffic_source import TSProvider, TSCampaign
class TSPropellerAdsProvider(TSProvider):
"""
PropellerAds Provider
"""
def __init__(self, ts_name: str, api_key: str):
super().__init__(ts_name)
s... | ourprofit/binom-cost-synchronizer | providers/propeller_ads.py | propeller_ads.py | py | 6,138 | python | en | code | 0 | github-code | 13 |
70491984978 | def findMin(list):
min = list[0]
for i in range(0, len(list)):
if list[i] < min:
min = list[i]
return min
def findMax(list):
max = list[0]
for i in range(0, len(list)):
if list[i] > max:
max = list[i]
return max
if __name__ == '__main__':
numbers =... | Dom0nS/Python-PJATK | project3/zad1.py | zad1.py | py | 525 | python | en | code | 0 | github-code | 13 |
23758653000 | from Crypto.Cipher import AES
iv = b"\x00"*16
key = b"andy love simone"
msg = b"andy love simoneandy love simone"
expected = "d6fdc5d5596e6ff6c3039cfbb5d9216f"
h = AES.new(key, AES.MODE_CBC, iv=iv).encrypt(msg)
hd = h.hex()
print(hd)
print(hd[-32:])
print(expected)
print(hd[-32:] == expected)
def XOR(b1, b2):
ret... | micahshute/ece_code | applied_crypto/playground/lesson4/cbc_mac_test.py | cbc_mac_test.py | py | 657 | python | en | code | 1 | github-code | 13 |
38175390579 | #===============================================================================
# Autor : Rosenio Pinto
# e-mail: kenio3d@gmail.com
#===============================================================================
class Scene_Info(object):
def __init__(self, scene_check_state = {},
ref... | rosenio/Batch.io | scripts/Process/Utils/Scene_Info.py | Scene_Info.py | py | 4,566 | python | en | code | 6 | github-code | 13 |
33683139189 | from bs4 import BeautifulSoup
log = logging.getLogger('statistics') # Логер в контексте джанго, заменить на нативный
class Facebook_Stats:
def __init__(self, fb_post_id, fb_token):
self.fb_post_id = fb_post_id
self.fb_token = fb_token
def req_stats(self, url_method):
req = requests.... | maksymkv25/Medium-Facebook-statistics | main.py | main.py | py | 3,134 | python | en | code | 0 | github-code | 13 |
28462403140 | user_in = input("Число = ")
try:
user_num = int(user_in)
except ValueError:
message = "Ошибка, это не число"
else:
message = user_num ** 2 # какая-то лишняя операция затесалась
last_num = user_num % 10
new_num = user_num // 10
message = last_num * 10000 + new_num
print(me... | Sadburritos/python_homework | May26/09.py | 09.py | py | 378 | python | ru | code | 0 | github-code | 13 |
17056467084 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankCreditProdarrangementContracttextQueryModel(object):
def __init__(self):
self._bsn_no = None
self._contract_type = None
self._query_type = None
@property
de... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/MybankCreditProdarrangementContracttextQueryModel.py | MybankCreditProdarrangementContracttextQueryModel.py | py | 1,938 | python | en | code | 241 | github-code | 13 |
15602704920 | budget = float(input())
statists = int(input())
price_for_cloth_statists = float(input())
decor = budget * (10 / 100)
sum_for_cloth = statists * price_for_cloth_statists
if statists > 150:
percentage = sum_for_cloth * (10 / 100)
for_cloth = sum_for_cloth - percentage
money = for_cloth + decor
if budg... | PowerCell12/Programming_Basics_Python | Conditional Statements/Exercise/05. Godzilla vs. Kong.py | 05. Godzilla vs. Kong.py | py | 1,094 | python | en | code | 0 | github-code | 13 |
17087076594 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.RecResultInfo import RecResultInfo
class AlipayOpenDataItemRecommendBatchqueryResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenDataItemRecom... | alipay/alipay-sdk-python-all | alipay/aop/api/response/AlipayOpenDataItemRecommendBatchqueryResponse.py | AlipayOpenDataItemRecommendBatchqueryResponse.py | py | 1,088 | python | en | code | 241 | github-code | 13 |
73091704336 | import numpy as np
import soundfile as sf
from scipy import signal
import matplotlib.pyplot as plt
from scipy import array, zeros, signal
from scipy.fftpack import fft, ifft, convolve
#If using termux
import subprocess
import shlex
x,fs = sf.read('../data/Sound_Noise.wav')
y = np.zeros(len(x))
samp_freq = fs
order ... | hellblazer1/EE3025_A1 | codes/4_3.py | 4_3.py | py | 1,220 | python | en | code | 0 | github-code | 13 |
15722003623 | import numpy as np
from matplotlib import pyplot as plt
def find_max_correlation(sound_array, min_shift, max_shift, plot=False, correlation_step=1):
auto_correlation = []
for shift in np.arange(min_shift, max_shift, correlation_step):
auto_correlation.append(np.corrcoef(sound_array[:-shift], sound_arr... | ArturPrzybysz/autotune | src/autocorrelation.py | autocorrelation.py | py | 670 | python | en | code | 1 | github-code | 13 |
22417634206 | import time
"""
Recursive Example: calculate Fibonacci sequence.
遞廻函式例子: 求斐波那契數列
"""
def fibo(n):
"""Return the n-th element of Fibonacci sequence.
Fibonacci sequnce is an infinite list of positive numbers,
begining with the first two ones, and any subsequent number that equals to
the sum o... | mkaoy2k/PythonExample-Repo | fibo.py | fibo.py | py | 3,367 | python | en | code | 0 | github-code | 13 |
1980873096 | from torch.nn.modules.activation import LeakyReLU
from torch.nn.modules.batchnorm import BatchNorm1d
from .base import BaseVAE
from .types_ import *
import torch
from torch import nn
import torch.nn.functional as F
class BetaVAE(BaseVAE):
num_iter = 0
has_labels = False
def __init__(
... | burknipalsson/vae_synthetic_hsi | models/beta_vae.py | beta_vae.py | py | 4,371 | python | en | code | 4 | github-code | 13 |
17464518472 | import json
from _datetime import datetime
from PyQt5 import QtWidgets
from common import config
from common.static_func import get_uuid1
from view.customer.ui.ui_return_visit_setting import Ui_MainWindow
from database.dao.customer import customer_handler
from database.dao.sale import sale_handler
class ReturnVisit... | zgj0607/Py-store | view/customer/return_visit_setting.py | return_visit_setting.py | py | 4,365 | python | en | code | 3 | github-code | 13 |
7314400745 | INF = 1 << 31
# 構造体の定義
class maxflow_edges:
def __init__(self, to: int, cap: int, rev: int):
self.to = to
self.cap = cap
self.rev = rev
def dfs(pos, goal, F, G, used):
if pos == goal:
return F
used[pos] = True
for v in G[pos]:
if v.cap > 0 and used[v.to] is Fa... | sugimotoyuuki/kyopro | tessoku/9_8/maximum_flow.py | maximum_flow.py | py | 1,421 | python | en | code | 0 | github-code | 13 |
36724961412 | from core.constants import LOWER_STARTING_POSITION
from core.robot import get_robot_wrapper
from py_trees.behaviour import Behaviour
from core.logger import log, LogLevel
from py_trees.common import Status
from core import constants
from enum import Enum
"""
Teleoperate the arm.
Operations:
X-PLANE
- up -> forwar... | tannerleise/RoboticsFinal | final_project/controllers/grocery_shopper/behavior/teleoperate.py | teleoperate.py | py | 3,940 | python | en | code | 0 | github-code | 13 |
17114312844 | """add_first_initial_column
Revision ID: 63f9353737ad
Revises: a68cb3e25cb2
Create Date: 2023-05-14 20:43:37.289649
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '63f9353737ad'
down_revision = 'a68cb3e25cb2'
branch_labels = None
depends_on = None
def upgrad... | alliance-genome/agr_literature_service | alembic/versions/20230514_63f9353737ad_add_first_initial_column.py | 20230514_63f9353737ad_add_first_initial_column.py | py | 1,032 | python | en | code | 1 | github-code | 13 |
4474091612 | #-*- coding:utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class HrContractContribution(models.Model):
_name = "hr.contract.contribution"
_description = "Contract Pay Contribution"
name = fields.Char(string="Reference",
required=True)
code = fields.... | LuisMalave2001/GarryTesting | hr_payroll_extends/models/hr_contract_contribution.py | hr_contract_contribution.py | py | 3,629 | python | en | code | 2 | github-code | 13 |
29542077785 | ascore = 100
bscore = 100
rounds = int(input())
for i in range(rounds):
a, b = input().split()
a = int(a)
b = int(b)
if a > b:
bscore -= a
elif b > a:
ascore -= b
else:
continue
print(ascore)
print(bscore) | orion222/competitive-programming | python/CCC/CCC 14 J3 Double Dice (2).py | CCC 14 J3 Double Dice (2).py | py | 273 | python | en | code | 0 | github-code | 13 |
38309046110 | import numpy as np
#pre_labels: predicated labels [[labels_0], [labels_1], ....]
#orig_labels: original labels of the same shape as pre_labels
# pre = tp / (tp + fp)
# all labels should be int
def gen_precision(pre_labels, orig_labels):
tp, fp = 0, 0
count_ins = len(pre_labels)
for i in range(count_ins... | TrivialError/branchlearning | model_evaluation.py | model_evaluation.py | py | 1,645 | python | en | code | 3 | github-code | 13 |
18402639839 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 7 18:44:35 2022
@author: jhazelde
"""
import torch
import argparse
import gradient_methods as gm
from torchvision import datasets, transforms
from matplotlib import pyplot as plt
from tqdm import tqdm
import os
print(f'Using GPU: {torch.cuda.get_device_name(0)}')
os.en... | meeree/LossLandscapesBNN | src/trainer_v2.py | trainer_v2.py | py | 26,930 | python | en | code | 0 | github-code | 13 |
19733164841 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 24 16:41:32 2021
@author: rachid2
"""
from sklearn.datasets import load_digits
from frnmf import FRNMF
import nimfa # from https://nimfa.biolab.si/
import tools
import numpy as np
#
import warnings
warnings.filterwarnings('ignore', category=Fut... | Hedjrachid/FR-NMF | demo.py | demo.py | py | 1,954 | python | en | code | 0 | github-code | 13 |
17043310294 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMsaasMediarecogVoiceMediaaudioUploadModel(object):
def __init__(self):
self._data = None
self._extinfo_a = None
self._extinfo_b = None
self._extinfo_c = None... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayMsaasMediarecogVoiceMediaaudioUploadModel.py | AlipayMsaasMediarecogVoiceMediaaudioUploadModel.py | py | 4,129 | python | te | code | 241 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.