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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
12089395343 | """
练习:
在终端中获取一个整数,作为边长,打印矩形。
效果:
请输入整数:5
$$$$$
$ $
$ $
$ $
$$$$$
"""
# number = int(input("请输入数字:"))
# print("$" * number)
# for item in range(number-2):#0 1 2
# print("$%s$" % (" " * (number - 2)))
# print("$" * number)
number = int(input("请输入数字:"))
for item in range(num... | 15149295552/Code | Month02/day04/exercise03.py | exercise03.py | py | 577 | python | zh | code | 1 | github-code | 13 |
70301768337 | from bs4 import BeautifulSoup
import requests
import json
def get_players(team=None, year=None):
# scrape players across all teams and years
if team == None and year == None:
teams = get_team_ids()
print('Checkpoint: Done getting team ids')
players = {}
for team in teams:
... | JohnAmadeo/football-networks | scraper_sync.py | scraper_sync.py | py | 3,514 | python | en | code | 0 | github-code | 13 |
21293502029 | # въвеждане на чисто от конзолата
# пресмятане на бонуса според услвията
# добавяне на допълнителен бонус
# принтиране на бонус точките
# принтиране на общия брой точки
number = int(input())
bonus = 0
if number <= 100 :
bonus = 5
elif number > 1000 :
bonus = number * 0.10
else:
bonus = number * 0.20
if n... | SJeliazkova/SoftUni | Programming-Basic-Python/Exercises-and-Labs/Conditional_Statements_Exercise/02.Bonus_Score.py | 02.Bonus_Score.py | py | 576 | python | bg | code | 0 | github-code | 13 |
31887144463 | '''
Created on Oct 28, 2018
@author: cmins
'''
# Every coordinates of first value is rows and second value is col
import psexceptions
import psgamestate
class PSBoard:
def __init__(self):
self._board = self.getNewBoard(7, 7)
# Joowon Jan,04,2019
# Add variable to store the... | ChanwO-o/peg-solitaire | psboard.py | psboard.py | py | 3,800 | python | en | code | 1 | github-code | 13 |
21931887455 | import map,pygame,random
from pygame.locals import *
class CrtPlayer:
#HP,FOOD,SLEEP,SKILL,FOODSPEED,SLEEPSEEPD,PLAYERX,PLAYERY,MAP
def __init__(self,Maps,Scr,Font):
self.HP=100
self.Food=1000
self.Sleep=2000
self.FoodSpeed=2
self.SleepSpeed=2
self.Pla... | henda233/SCP-E | player.py | player.py | py | 7,486 | python | en | code | 0 | github-code | 13 |
36322830623 | class Move_16:
def __init__(self,other,my,mx):
self.lst1 = other.lst1
self.yx = other.yx
self.my = my
self.mx = mx
def move__1(self):
y,x = self.yx
my = self.my
mx = self.mx
self.lst1[y][x],self.lst1[y+my][x+mx]=self.lst1[y+my][x+mx],self.lst1[y][x... | initialencounter/code | Python/游戏/华容道/15rewrite.py | 15rewrite.py | py | 3,918 | python | en | code | 0 | github-code | 13 |
31299037728 | from abc import ABC, abstractmethod
import numpy as np
input_str = '9C0141080250320F1802104A08'
with open('input', 'r') as f:
input_str = f.read()
input_str = input_str.strip()
print(input_str)
class Packet(ABC):
def __init__(self, type_id, version):
self.type = type_id
self.version = versio... | speug/AdventOfCode2021 | day16/packet_decoder.py | packet_decoder.py | py | 5,003 | python | en | code | 0 | github-code | 13 |
29123887596 | """Test calling `FCNet` with different input and output features."""
import pytest
from torch import rand # pylint: disable=no-name-in-module
from torch_tools import FCNet
def test_model_with_correct_input_features():
"""Test the model works with different input features."""
# With input batchnorm and dro... | jdenholm/TorchTools | tests/models/test_fc_net_call.py | test_fc_net_call.py | py | 1,456 | python | en | code | 4 | github-code | 13 |
12416625769 | # we will write a 'Person' class
class Person(object): # here we explicitly inherit from object
'''This class encapsulates a name, age and email fro a person'''
def __init__(self, n, a, e): # every function in a class MUST take 'self' as an argument
# here we can set inital values on our class
... | onionmccabbage/pythonFeb2023 | using_classes/b.py | b.py | py | 1,589 | python | en | code | 0 | github-code | 13 |
25147857772 | import nextcord
from nextcord.ext import commands
from nextcord import Interaction
import asyncio
from helpers.logger import logger
import openai
import os
class AI(commands.Cog):
def __init__(self, bot) -> None:
openai.api_key = os.getenv("OPENAI_API_KEY")
self.bot = bot
@nextcord.slash_com... | TiberiusBR/CaldeiraoBot | cogs/ai.py | ai.py | py | 2,369 | python | en | code | 1 | github-code | 13 |
4997304495 | from django.shortcuts import render
from django.http import HttpResponse
from . import forms
# Create your views here.
def index(request):
context = {}
context['personForm'] = forms.PersonForm()
context['livesForm'] = forms.LivesForm()
context['worksForm'] = forms.WorksForm()
return render(requ... | teetangh/Kaustav-CSE-LABS-and-Projects | Sem06-Web-Dev-LAB/WEEK 07/week07/question2_app/views.py | views.py | py | 1,220 | python | en | code | 2 | github-code | 13 |
3959021082 | import threading
from app import db
from cloud_components.request_executor import RequestExecutor
class RequestScheduler:
def __init__(self, config_id):
self.deploy_id = config_id
self.__executing__ = False
self.__executing_lock__ = threading.Lock()
self.__current_request_id__ = ... | Ydjeen/openstack_testbed | cloud_components/request_scheduler.py | request_scheduler.py | py | 3,064 | python | en | code | 1 | github-code | 13 |
23162245029 | # -*- coding: utf-8 -*-
import copy
# ******* How It Works ************
# For each changes on paper, current paper state is saved.
# To save state, first all top level object list is copied.
# List of all objects on paper (top levels and their children) are generated
# Attribute values of each those objects are stored... | ksharindam/chemcanvas | chemcanvas/undo_manager.py | undo_manager.py | py | 6,542 | python | en | code | 1 | github-code | 13 |
1166225514 |
from pathlib import Path
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from tkinter import *
import cv2
import face_recognition
import sqlite3
import numpy as np
import qr_detection
from tkinter import messagebox
import homepage as hp
from datetime import datetime
def go_detect_qr(current_window,c... | chirag-3/secure-lab-access-using-face-recognition-and-qr-code-scan | face_detection1.py | face_detection1.py | py | 8,003 | python | en | code | 0 | github-code | 13 |
71455690579 | with open('27test-lshastin') as f:
a=f.read()
a=a.split('\n')
a.pop(0)
a=list(map(int,a))
k=a.pop(0)
c=0
a=[x%2 for x in a]
for i in range(len(a)):
b=[]
for z in range(i,len(a)):
b.append(a[z])
if (b.count(1)==b.count(0)) and (len(b)>=k):
c+=1
print(c) | artgunBLACKMAESTRO/EGE | task27/27-lshastin.py | 27-lshastin.py | py | 292 | python | en | code | 0 | github-code | 13 |
23171025189 | from networkit import Graph
class MongoDBStorage:
def storeGraph(self, collection, graph: Graph):
converted_graph = {"nodes": []}
for node in graph.nodes():
associatednodes = []
graph.forEdgesOf(node, lambda left, right, weight, edge_id:
(associatednodes.ap... | kshaposhnikov/twitter-graph-model | tgml/loader/mongodbstorage.py | mongodbstorage.py | py | 599 | python | en | code | 0 | github-code | 13 |
17514468979 | from django.urls import path
from . import api_views
app_name = 'spacyal_api'
urlpatterns = [
path('retrievecases/', api_views.RetrieveCasesView.as_view(),
name='retrievecases'),
path('progress_model/', api_views.GetProgressModelView.as_view(),
name='progress_model'),
path('download_mode... | sennierer/spacyal | spacyal/api_urls.py | api_urls.py | py | 601 | python | en | code | 5 | github-code | 13 |
10720266149 | #!/usr/bin/env python3
from cmath import pi
from math import dist
import random
from turtle import pos
from typing import List
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from fwd_kinematics import *
JointValues = List[float]
JointValuesList = List[JointValues]
from pyl... | vineetjnair9/DT_sim | RRT_Connect_Du.py | RRT_Connect_Du.py | py | 7,979 | python | en | code | 0 | github-code | 13 |
45187569796 | import tensorflow as tf
from tests.cnn.image_input_4d import ImageInput4D
from tfoptests.nn_image_ops import NNImageOps
from tfoptests.persistor import TensorFlowPersistor
def test_conv_1():
# [4, 2, 28, 28, 3]
image_input = ImageInput4D(seed=713, batch_size=4, in_d=2, in_h=28, in_w=28, in_ch=3)
in_node ... | kgnandu/TFOpTests | tests/cnn/test_conv_1.py | test_conv_1.py | py | 1,358 | python | en | code | 0 | github-code | 13 |
14249253026 | '''
Author: rootReturn0
Date: 2020-09-08 10:53:58
LastEditors: rootReturn0
LastEditTime: 2020-09-08 17:30:38
Description:
'''
from pandas.core.common import random_state
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import *
from sklearn.model_selection im... | RootReturn0/ML | predict_clf.py | predict_clf.py | py | 3,945 | python | en | code | 0 | github-code | 13 |
70312266257 | from typing import Callable, Dict, List, Type
from os import getenv, path
from inspect import signature
import requests
from pydantic import parse_obj_as
from dotenv import load_dotenv
from models import CategoriesResponse, InstructionsResponse, PriceResponse, ProductsResponse, RegionsResponse, SearchResponse
from ex... | KlukvaMors/zdravcity_api | zdravcity.py | zdravcity.py | py | 3,891 | python | en | code | 1 | github-code | 13 |
23162185849 | from app_data import App
from common import float_to_str
from drawing_parents import hex_color, hex_to_color
from molecule import Molecule
from marks import Charge, Electron
from arrow import Arrow
from bracket import Bracket
from text import Text, Plus
import io
import xml.dom.minidom as Dom
# top level object types... | ksharindam/chemcanvas | chemcanvas/fileformat_ccdx.py | fileformat_ccdx.py | py | 17,214 | python | en | code | 1 | github-code | 13 |
25741745319 | from netCDF4 import Dataset
import numpy as np
from datetime import datetime
import os
import shutil
import csv
def get_min_index(data):
min_val = data[0]
for val in data:
if val <= min_val:
min_val = val
for i,val in enumerate(data):
if min_val == val:
break
return i
def get_all_files(folder):
files ... | animeshkuzur/netCDF_to_CSV | convert2.py | convert2.py | py | 2,554 | python | en | code | 3 | github-code | 13 |
33527299426 | """
@Time: 2023/11/1 11:24
@Auth: Y5neKO
@File: Thinkphp2_rce.py
@IDE: PyCharm
"""
import requests
import urllib
from urllib.parse import urljoin
def run(url, cmd):
try:
payload = r'/index.php?s=a/b/c/${@print(eval($_POST[cmd]))}'
payload = urllib.parse.urljoin(url, payload)
response... | Y5neKO/ClosureVulnScanner | exp/Thinkphp2_rce.py | Thinkphp2_rce.py | py | 584 | python | en | code | 8 | github-code | 13 |
17054086434 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class KbdishCommRuleShowInfo(object):
def __init__(self):
self._tag_ext_info = None
self._tag_name = None
self._tag_value = None
@property
def tag_ext_info(self):
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/KbdishCommRuleShowInfo.py | KbdishCommRuleShowInfo.py | py | 1,884 | python | en | code | 241 | github-code | 13 |
29817695078 | import pickle
import numpy as np
import tensorflow as tf
from sklearn.svm import SVC
from random import shuffle
from sklearn.preprocessing import normalize
from sklearn.neighbors import KNeighborsClassifier
import utils
import image
import pickle
import os
from keras.models import Sequential
from keras.layers import De... | senecal-jjs/Hyperspectral | keras_classification.py | keras_classification.py | py | 5,618 | python | en | code | 0 | github-code | 13 |
73817139217 | teencode = {
'vk': 'vo',
'ck': 'chong',
'hoy': 'thoi',
'lem': 'lam',
'hsi': 'hay sao i',
'yep': 'yes',
'choai xu': 'twice'
}
loop = True
while loop:
key = input('Bạn muốn tra từ gì? ').strip()
if key in teencode:
print(f"{key} nghĩa là {teencode[key]}")
else:
... | thuhuongvan98/Huong-Van | Lesson 5/ex_dict.py | ex_dict.py | py | 625 | python | vi | code | 0 | github-code | 13 |
39653392352 | import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
def imitate_synchronize():
'''
模拟一下同步先处理数据,然后才能取数据训练
:return:
'''
# 1 创建一个队列
queue = tf.FIFOQueue(1000, tf.float32)
# 放入数据
enq_m = queue.enqueue_many([[0.1, 0.3, 0.4],]) # 注意数据形式, [0.1, 0.3, 0.4]会被看做是一个张量, 而非... | bwbobbr/AI | 机器学习/day_05/day_05.py | day_05.py | py | 2,448 | python | zh | code | 0 | github-code | 13 |
41643411405 | # Method: 2 pass method
# 1: Calculate Length
# 2: Split list into k lists
# TC: O(n)
# SC: O(n)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def splitListToParts(self, head: Optional[ListNode... | ibatulanandjp/Leetcode | #725_SplitLinkedListInParts/solution.py | solution.py | py | 1,243 | python | en | code | 1 | github-code | 13 |
32642770740 |
import numpy as np
import tensorflow as tf
from agent import agent
from rtb_environment import RTB_environment, get_data
from drlb_test import drlb_test
from lin_bid_test import lin_bidding_test
from rand_bid_test import rand_bidding_test
#parameter_list = [camp_id, epsilon_decay_rate, budget_scaling, budget_init_va... | zgcgreat/dqn-rtb | parameter_test.py | parameter_test.py | py | 4,072 | python | en | code | 0 | github-code | 13 |
36388907882 | """
Implement the Reverification XBlock "reverification" server
"""
import logging
from opaque_keys.edx.keys import CourseKey
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from verify_student.models import VerificationCheckpoint, VerificationStatus, SkippedReverific... | escolaglobal/edx-platform | lms/djangoapps/verify_student/services.py | services.py | py | 3,251 | python | en | code | 0 | github-code | 13 |
16510515254 | """
from : https://leetcode.com/problems/candy-crush/discuss/1028524/Python-Straightforward-and-Clean-with-Explanation
Don't be intimidated by how long or ugly the code looks. Sometimes I fall into that trap. It's simpler than it seems.
Also, I would love feedback if this is helpful, or if there are any mistakes!
A ke... | tmbothe/Data-Structures-and-algorithms | src/arrays/candyCrush.py | candyCrush.py | py | 3,377 | python | en | code | 0 | github-code | 13 |
41905906790 | import csv
import os
import time
import re
import commands
import string
from appium import webdriver
import logging
import datetime
logging.basicConfig(level=logging.INFO)
apk_path = os.path.join(os.getcwd(), 'lite.apk')
class Browser(object):
platform_name = 'Android'
platform_version = string.strip(comman... | sxwollo/BrowserAppTest | venv/AppTest/launch_time_ui.py | launch_time_ui.py | py | 3,127 | python | en | code | 0 | github-code | 13 |
36460849139 | poker=list(range(1,53))
import random as rd
#rd.seed(30)
n=0
count=1000
while n<=count:
rdnum1,rdnum2=int(rd.random()*51),int(rd.random()*51)
while rdnum2==rdnum1:
rdnum2=int(rd.random()*51)
poker[rdnum1],poker[rdnum2]=poker[rdnum2],poker[rdnum1]
n+=1
first,second=poker[0],poker[1]
d... | fightpf/advanceiborgainc | 20200529temp.py | 20200529temp.py | py | 763 | python | en | code | 0 | github-code | 13 |
10065084450 | try:
from models.db import DbDAO
except ModuleNotFoundError:
from website.models.db import DbDAO
import logging
__author__ = "Le Gall Guillaume"
__copyright__ = "Copyright (C) 2020 Le Gall Guillaume"
__website__ = "www.gyca.fr"
__license__ = "BSD-2"
__version__ = "1.0"
class Invoice:
def __init__(self):
... | LegallGuillaume/MyCompta | website/models/invoice.py | invoice.py | py | 2,980 | python | en | code | 0 | github-code | 13 |
25620512291 | """
To analysing the behavior of ODA at the interface
"""
import typing
import numpy as np
import matplotlib.pylab as plt
import logger
from get_data import GetData
import static_info as stinfo
class WrapData(GetData):
"""
Get data and call other classes to analysis and plot them.
Before that, some calc... | saeed-amiri/analysing-legacy | codes/oda_analysing.py | oda_analysing.py | py | 8,871 | python | en | code | 0 | github-code | 13 |
27876443135 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from src import meta
from fnmatch import fnmatch
import argparse
import os
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--label', default='toxic')
parser.add_argument('--method', default='... | alno/kaggle-jigsaw-toxic-comment-classification-challenge | src/tools/corrplot.py | corrplot.py | py | 1,290 | python | en | code | 4 | github-code | 13 |
2845727012 | nodes_str = '''
1
/ \\
2 3
/ \\
4 5
/ \\
6 7
'''
print(nodes_str)
nodes = { "data" : 1 }
nodes['left'] = { "data" : 2 }
nodes['right'] = { "data" : 3 }
nodes['left']['left'] = { "data" : 4 }
nodes['left']['right'] = { "data" : 5 }
nodes['left']['left']['left'... | melezhik/sparrow-plugins | ds-binary-tree-bft2/tasks/python/task.py | task.py | py | 711 | python | tr | code | 2 | github-code | 13 |
23833077333 | #----------------------------------------------------------
# FUNCION PrintTabLatex()
#
# PARAMETROS
# aTitulos: Lista con los títulos a imprimir
# aDatos: Lista de listas con los datos correspondientes
# a cada titulo
# USO Imprime una tabla en formato latex para facilidad
# del pasaje de datos al inform... | fmonpelat/Analisis-Numerico---TP2 | python scripts/PrintTabLatex.py | PrintTabLatex.py | py | 1,280 | python | pt | code | 0 | github-code | 13 |
22720200123 | """Commands: "!total [emote]", "!minute [emote]"."""
from bot.commands.abstract.command import Command
from bot.utilities.permission import Permission
from bot.utilities.tools import replace_vars
class OutputStats(Command):
"""Reply total emote stats or stats/per minute."""
perm = Permission.User
def __... | NMisko/monkalot | bot/commands/outputstats.py | outputstats.py | py | 2,111 | python | en | code | 17 | github-code | 13 |
42488286511 | import numpy as np
import matplotlib.pyplot as plt
import NIST_mass_attenuation_data as NIST
import importlib
importlib.reload(NIST)
#class MassAttenData:
COL_MU = 1
COL_MUEN = 2
def log_spaced_array(start, end, points):
arr = pow(np.logspace(np.log10(start), np.log10(end), points), 10.0)
return arr
def log_inter... | agreenswardellipse/FAFA05_gamma_spectroscopy | NIST_mass_attenuation.py | NIST_mass_attenuation.py | py | 2,119 | python | en | code | 2 | github-code | 13 |
17052789854 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class IndirectQualificationInfo(object):
def __init__(self):
self._image_list = None
self._mcc_code = None
@property
def image_list(self):
return self._image_list
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/IndirectQualificationInfo.py | IndirectQualificationInfo.py | py | 1,773 | python | en | code | 241 | github-code | 13 |
17945288810 | import ipywidgets as widgets
import json
from IPython.display import display
from .sampling import Sampling
from .filters import Filters
from .columns import Columns
class Downloader:
def __init__(
self,
name=None,
catalog_item=None,
display_value=False,
display_widget=Fal... | cosphere-org/lakey-ui | lakey_ui/lakey/widgets/downloader.py | downloader.py | py | 2,740 | python | en | code | 1 | github-code | 13 |
71595944339 | import re #standard library providing regular expression facilities
import math #standard library providing mathematical operations
def move(joint, client):
'''converts the output (joint angles) as commands to the... | malek-luky/Industrial-Robotics | 3D Printing/62607_FinalReport_Team4/functions.py | functions.py | py | 5,429 | python | en | code | 0 | github-code | 13 |
32025138671 | '''Deep Convolutional Generative Adverserail Netowrks'''
# Import libraries
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optimizer
import torch.utils.data
from torch.autograd import Variable
import torchvision.datasets as datasets
import torchvision.utils as tvutils
import torch... | PavlySz/CIFAR10-GANs | dcgan.py | dcgan.py | py | 9,043 | python | en | code | 0 | github-code | 13 |
27684078643 | import hashlib
import secrets
import re
def calculate_sha256(filename):
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def comprobar_fila_condiciones(fila):
... | mikel0912/SGSSI-23-Labo06 | comprobacion/Labo06Act0.py | Labo06Act0.py | py | 1,799 | python | es | code | 0 | github-code | 13 |
6752607604 | from django.db import models
from custom_users.models import User
class Car(models.Model):
class Meta:
verbose_name = 'Автомобиль'
verbose_name_plural = 'Автомобили'
owner = models.ForeignKey(User, verbose_name='Хозяин автомобиля', on_delete=models.CASCADE,
relat... | Hooliganka/verification_task | server/src/cars/models.py | models.py | py | 837 | python | en | code | 0 | github-code | 13 |
14760067692 | from argparse import ArgumentParser
import sys
import curses
from time import sleep
import tempfile
import os
from math import factorial
import random
from random import randint
class Player:
"""
A Player explores a Maze. While exploring the maze their hunger goes down.
Occasionally they may find an enemy t... | NKoyfish/DungeonCrawl | sampleBattle.py | sampleBattle.py | py | 11,239 | python | en | code | 2 | github-code | 13 |
5671940541 | """
This code is released under an MIT license
"""
import networkx as nx
from esipy import App
from esipy import EsiClient
import config
graph = nx.DiGraph()
queue = list()# LIFO queue
esiapp = App.create(config.ESI_SWAGGER_JSON)
# init the client
esiclient = EsiClient(
cache=None,
headers={'User-Agent': c... | alexander94dmitriev/EveCanaryApp | network_remote.py | network_remote.py | py | 3,086 | python | en | code | 1 | github-code | 13 |
18068165132 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1025))
s.listen(5)
while True:
clt_soc, clt_add = s.accept()
print(f"Connection to {clt_add} established")
clt_soc.send(bytes("Socket Programming", "utf-8"))
clt_soc.close()
| kumarjeetray/Python_Programs | Socket Programming/SET II/SERVER2.py | SERVER2.py | py | 299 | python | en | code | 0 | github-code | 13 |
44340453635 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 06 06:11:42 2017
@author: Yunho
"""
from ggplot import *
import pandas as pd
# Adding a Title
ggplot(mpg, aes(x='cty', y='hwy')) + \
geom_point() + \
ggtitle("City vs. Highway Miles per Gallon")
# Adding Labels
ggplot(mpg, aes(x='cty')) + \
geom_histogr... | yunho0130/Python_Lectures | 2018_02_SMU_Lecture_Slide/ch10/code/ggplot_jupyter.py | ggplot_jupyter.py | py | 1,391 | python | en | code | 225 | github-code | 13 |
17427571218 | """
def splitRope(RemainingLength,possibleSplits,cuts,combinations):
if ( RemainingLength < 0 ) or len([x for x in possibleSplits if x <= RemainingLength]) == 0 :
del cuts[-1]
return combinations,cuts
for splitAt in possibleSplits:
if RemainingLength - splitAt == 0:
cuts.appe... | vigneshSr91/MyProjects | Exercise37-RopeCuttingRecursive.py | Exercise37-RopeCuttingRecursive.py | py | 1,556 | python | en | code | 0 | github-code | 13 |
3583607273 | # 전기버스 2
# time : 40m
# idea
'''
현재 가진 배터리로 갈 수 있는 모든 특정 정류소에서 충전하는 경우 모든 것을 다 고려 후, 가지치기 진행하기
→ DFS + charge_cnt 기준으로 가지치기
'''
def charge_times(s, cnt): # 최소 충전 횟수를 찾는 함수
global min_cnt # 현재까지의 최소 충전 횟수
if cnt >= min_cnt: # 가치지기 : 이미 현재의 최소를 넘은 경우
return # 해당 재귀를 종료
... | eondo/Algorithm | 분할정복&백트래킹/S_5208_전기버스2.py | S_5208_전기버스2.py | py | 1,444 | python | ko | code | 0 | github-code | 13 |
18091839822 | #!/usr/bin/python
######################################################################
# Name: ALaDyn_plot_utilities_Energy_Density.py
# Author: F.Mira
# Date: 2016-05-25
# Purpose: it is a module of: ALaDyn_plot_sections - plots energy density
# Source: python
#############################... | ALaDyn/tools-ALaDyn | pythons/utility_energy_density.py | utility_energy_density.py | py | 3,693 | python | en | code | 6 | github-code | 13 |
27839014475 | import pandas as pd
import xml.etree.ElementTree as ET
import sys
from random import *
import importlib
# load all data in Panda dataframes
# titles information
tittleInfo = pd.read_csv( "tittle_basics1.tsv", sep='\t' ) #100k
tittleCrew = pd.read_csv( "tittle_crew1.tsv", sep='\t' )
tittleRatings = pd.read_csv( "tittl... | akhiln28/ontology_assignment1 | DataExtract.py | DataExtract.py | py | 6,500 | python | en | code | 0 | github-code | 13 |
254256141 | #!/usr/bin/env python3
"""
This script splits exported tiddlers.md into multiple Markdown files in a "tiddlers" folder.
Usage: python split-tiddlers.py
"""
# The name of the multiple tiddlers Markdown file
in_file = 'tiddlers.md'
# The name of the folder where the output is stored
out_folder = 'tiddlers'
import os... | cdaven/tiddlywiki-stuff | markdown-export/split-tiddlers.py | split-tiddlers.py | py | 1,480 | python | en | code | 10 | github-code | 13 |
23269638002 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 09:24:31 2016
http://club.jd.com/clubservice.aspx?method=GetCommentsCount&referenceIds=3243686
@author: thinkpad
"""
import asyncio
import aiohttp
import aiomysql
import pandas as pd
import datetime
import queue
async def get_count(sku_group):
global crawl_id
... | Strongc/pc-jd | get_comment_count_aiohttp.py | get_comment_count_aiohttp.py | py | 4,036 | python | en | code | 0 | github-code | 13 |
18416183881 | import sys
player_name = input()
max_points = -sys.maxsize
winner = ''
while player_name != 'Stop':
player_points = 0
for i in player_name:
number = int(input())
i = ord(i)
if i == number:
player_points += 10
else:
player_points += 2
if player_p... | MiroVatov/Python-SoftUni | Python Basic 2020/Exam - 06 - Name Game.py | Exam - 06 - Name Game.py | py | 499 | python | en | code | 0 | github-code | 13 |
14113017883 | """
Created on Wed Jan 11 09:40:26 2017
@author: bobmek
"""
import openpyxl
import numpy as np
import pylab
from scipy.optimize import curve_fit
import xlsxwriter
#import panda as pd
#sigmoid funtion
def sigmoid(x, x0, k, a, c):
y =c+(a / (1 + np.exp(-k*(x-x0))))
return y
#commands to open notebook for I... | bobmek/fibrillation_analysis | sigmoid fit.py | sigmoid fit.py | py | 3,435 | python | en | code | 0 | github-code | 13 |
9038908542 | #!/usr/bin/env python
# Setup script for the PyGreSQL version 3
# created 2000/04 Mark Alexander <mwa@gate.net>
# tweaked 2000/05 Jeremy Hylton <jeremy@cnri.reston.va.us>
# win32 support 2001/01 Gerhard Haering <gerhard@bigfoot.de>
# requires distutils; standard in Python 1.6, otherwise download from
# http://www.pyt... | orynider/php-5.6.3x4VC9 | postgresql/src/interfaces/python/setup.py | setup.py | py | 1,910 | python | en | code | 3 | github-code | 13 |
74789979857 | import requests
from googletrans import Translator
from random import choice
# tradutor
tradutor = Translator()
def pega_conselho(assunto=False):
""" A função acessa a API e retorna um conselho
Args:
assunto (bool, optional): Se tiver uma palavra como
argumento será retornado um... | danielns-op/sitecomflask | apis/apis.py | apis.py | py | 3,283 | python | pt | code | 0 | github-code | 13 |
73701643217 | def rev(n, temp=''):
''' n-indicates the number to be reversed,
output:Return the number in reversed order in the string format'''
# YOUR CODE GOES HERE
if n// 10 == 0:
return temp + str(n)
next_n = n // 10
last_digit = n % 10
temp += str(last_digit)
return rev(next_n, te... | debnsuma/masters-ml | M1-M5/string_reverse_recursive.py | string_reverse_recursive.py | py | 334 | python | en | code | 0 | github-code | 13 |
15954365825 | # -*- coding: UTF-8 -*-
import json
import time
# from MALL.config import setting
#
# setting_params = setting.DATABASE
# record_path = "{}\{}".format(setting_params['path'], setting_params['shop'])
def shop_record(data_path, username, action_type, shop_list, amount):
with open("{}/record_of_{}.json".format(data_... | Bigberg/python | day5--ATM/MALL/core/shop_record.py | shop_record.py | py | 1,027 | python | en | code | 0 | github-code | 13 |
23769483050 | import sys
sys.path.append("../../")
from copy import deepcopy
import pandas as pd
from train_model import train
from notebooks.fc.hyperparams import hyperparameter as fc_hyperparameter
from notebooks.kc.hyperparams import hyperparameter as kc_hyperparameter
from notebooks.poa.hyperparams import hyperparameter as po... | Koen-Git/UC_Project_HPP | experiments.py | experiments.py | py | 3,556 | python | en | code | 1 | github-code | 13 |
834241665 | from bs4 import BeautifulSoup
import requests as req
import pandas as pd
SEASONS = [2018, 2019, 2020, 2021]
# code to find league - ES - Espanyol, 2 - second league level
CODE = 'ES2'
# link that works for all leagues (change only code & season for request)
# url = f'https://www.transfermarkt.com/laliga2/startseite/... | Daniel-Prus/segunda_division_draw_analysis | 3_external_variables/01_teams_market_value_web_scraping.py | 01_teams_market_value_web_scraping.py | py | 2,127 | python | en | code | 0 | github-code | 13 |
35210830454 | # Uses python3
import sys
def optimal_weight(W, weights):
table = [[0 for v in range(W + 1)] for w in range(len(weights) + 1)]
for w in range(1, len(weights) + 1):
for v in range(W + 1):
if v < weights[w - 1]:
table[w][v] = table[w - 1][v]
else:
... | vinaykudari/data-structures-and-algorithms | algorithmic-toolbox/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py | knapsack.py | py | 570 | python | en | code | 0 | github-code | 13 |
15624302930 | from embod_client import AsyncClient
import argparse
from datetime import datetime
import numpy as np
from uuid import UUID
class FPSMonitor:
def __init__(self, agent_ids):
self._times = []
self._frame_count = 0
self._max_frame_count = 1000
self._frame_time = np.zeros(self._max_f... | embod/embod-client | embod_client/example/fps_monitor.py | fps_monitor.py | py | 2,858 | python | en | code | 3 | github-code | 13 |
70102264018 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import pickle
try:
import emoji
except ImportError:
get_ipython().system('pip install emoji --user')
import emoji
#try:
# from bs4 import BeautifulSoup... | faber6911/meetup-topics | live_demo/app_jupy.py | app_jupy.py | py | 6,370 | python | en | code | 1 | github-code | 13 |
11976084663 | '''
随机裁剪指定大小的区域
'''
import matplotlib.pyplot as plt
from torchvision import transforms
from PIL import Image
img1=Image.open("sunflower.jpg")
img2=transforms.RandomResizedCrop(224)(img1)
img3=transforms.RandomResizedCrop(224)(img1)
img4=transforms.RandomResizedCrop(224)(img1)
plt.subplot(2,2,1),plt.imshow(img1),plt.tit... | pepperbubble/DL | function_practice/RandomResizedCrop.py | RandomResizedCrop.py | py | 532 | python | ru | code | 0 | github-code | 13 |
70612967697 | N = int(input())
gram = list(map(int, input().split()))
gram.sort()
if gram[0] != 1:
print(1)
else :
SUM = 1
for i in range(1, N):
if gram[i] > SUM+1:
break
else:
SUM+=gram[i]
print(SUM+1)
| yoonhoohwang/Algorithm | BackJoon/2437. 저울.py | 2437. 저울.py | py | 257 | python | en | code | 2 | github-code | 13 |
36876015669 | #!/usr/bin/env python3
import string
import sys
def parse(data):
return data
def readfile(sep="\n"):
try:
f = open("input.txt")
data = f.read().split(sep)
f.close()
except Exception as e:
sys.stderr.write(f"{e}\n")
sys.exit(1)
for line in data:
if l... | rodfer0x80/aoc2022 | src/day_3/part_2.py | part_2.py | py | 1,056 | python | en | code | 0 | github-code | 13 |
11835682715 | from PyQt5.QtCore import (
QEasingCurve,
Qt,
QPropertyAnimation,
QRect,
QPoint,
pyqtProperty,
)
from PyQt5.QtGui import QColor, QPainter
from PyQt5.QtWidgets import QCheckBox
class CustomCheckBox(QCheckBox):
def __init__(
self,
text,
parent=None,
width=40,
... | Aabdelmoumen/wang_grace | widgets/CustomCheckBox.py | CustomCheckBox.py | py | 2,925 | python | en | code | 0 | github-code | 13 |
29864312887 | import math
import multiprocessing as mp
import requests
from pytube import YouTube # local version -> able to fix things quickly in case youtube changes stuff
def download_audio(video_url, path):
"""Download audio from YouTube video using multiple connections in parallel.
:param video_url: YouTube video ... | cemfi/score-tube | backend/youtube.py | youtube.py | py | 1,858 | python | en | code | 2 | github-code | 13 |
15049024906 | from enum import IntEnum, auto
from typing import Optional
import pandas as pd
import python_lib_for_me as pyl
import tweepy
from tweepy.models import ResultSet
from twitter_app.util import const_util, pandas_util
from twitter_app.util.twitter_api_v1_1.standard import twitter_tweets_util, twitter_users_util
... | silverag-corgi/twitter-app | src/twitter_app/logic/twitter_tweet_stream.py | twitter_tweet_stream.py | py | 3,511 | python | ja | code | 0 | github-code | 13 |
31943752910 | from typing import List
# @lc code=start
class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
def area(p1: List[int], p2: List[int], p3: List[int]) -> float:
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
return 0.5 * abs(x1 * y2 + x2 * y3... | wylu/leetcodecn | src/python/p800to899/812.最大三角形面积.py | 812.最大三角形面积.py | py | 642 | python | en | code | 3 | github-code | 13 |
5185661086 | import sqlite3
import pymorphy2
import random
from PyQt5.QtGui import QColor, QPainter
def get_x(x, offset, hor):
if hor:
return x + offset
else:
return x
def get_y(y, offset, hor):
if hor:
return y
else:
return y + offset
class Board:
def __init__(self, log):
... | RustyGuard/PyQTProject | Board.py | Board.py | py | 5,386 | python | en | code | 0 | github-code | 13 |
27547071653 | from django.shortcuts import render
from django.http import JsonResponse
import pandas as pd
from django.views.decorators.csrf import csrf_exempt
# Notice: using different gensim version will cause errors
from gensim.models.doc2vec import Doc2Vec
# (1) Load news data--approach 1
# df = pd.read_csv('dataset/cnn_news_n... | guan-jie-chen/Term_Project-Django | app_news_rcmd/views.py | views.py | py | 5,726 | python | en | code | 1 | github-code | 13 |
31006642800 | from django.contrib.auth.models import User, Group
from rest_framework import serializers
from api.models import *
from . import customer_serializer
class ProductTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = producttype_model.ProductType
fields = ('id', 'title',)
cla... | samphillips1879/bangazon-python-api | api/serializers/product_serializer.py | product_serializer.py | py | 624 | python | en | code | 0 | github-code | 13 |
42757552721 |
import re
print("Bienvenido a la cedulacion! Porfavor introduzca su cedula.")
cedula = input("Coloca su cedula: ")
patron1 = '[1-13]{1}\-[0-9]{0,3}\-[0-9]{0,4}'
patron2 = '([PE]|[N]|[E]){1}\-[0-9]{0,3}\-[0-9]{0,4}'
if re.search(patron1, cedula):
print("La cedula " + cedula + " es valida y ha sido gu... | MCAlmond/uip-iig-pc3 | practica de expresiones reales y archivos.py | practica de expresiones reales y archivos.py | py | 1,421 | python | es | code | 0 | github-code | 13 |
24346426262 | # # This Program takes Training images from the directory and encode them using face_encoding function from face_recognition and save the encoded images as "train.pkl"
import face_recognition
import cv2
import os
import pickle # Create portable serialized representations of Python objects
print(cv2.__version__)
Encodi... | Vishvambar-Panth/Jetson-Nano-Exercise | FaceRecognizer/trainSave.py | trainSave.py | py | 1,582 | python | en | code | 0 | github-code | 13 |
43690461056 | ##Given three integers x,y and z you need to find the
##sum of all the numbers formed by having 4 atmost x
##times , having 5 atmost y times and having 6 atmost
##z times as a digit.
def sumcalc(x,y,z):
if x < 0 or y < 0 or z < 0: return -1
import itertools
sum = 0
for i, j, k in itertools.product(range(x + 1)... | Mythili895/python-coding | leetcode/given_permutation sum.py | given_permutation sum.py | py | 523 | python | en | code | 0 | github-code | 13 |
73720230096 | import numpy as np
import matplotlib.pyplot as plt
from plot_stencil import plot_stencil
plt.figure()
data = np.zeros((30, 30))
data[0, :] = 1
data[:, 0] = 1
data[29, :] = -1
data[:, 29] = -1
data[0,29] = 0
data[29,0] = 0
data2 = data.copy()
for i in range(1,29):
for j in range(1, 29):
data2[i,j] = (i+j) ... | bjmiao/HPC-animation | simulate_stencil.py | simulate_stencil.py | py | 1,446 | python | en | code | 0 | github-code | 13 |
30140632270 | import sys
import requests
from web_wrapper.web import Web
import logging
logger = logging.getLogger(__name__)
class DriverRequests(Web):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.driver_type = 'requests'
self._create_session()
# Headers Set/Get
... | xtream1101/web-wrapper | web_wrapper/driver_requests.py | driver_requests.py | py | 3,626 | python | en | code | 0 | github-code | 13 |
34768874302 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 15:35:11 2023
This is a program to calculate earning compound interest
P = Principal amount(initial investment)
r = annual nominal interst rate (as a decimal)
n = number of times the interest is compounded per year
t = number of years
A = final ... | ruyonga/py101 | homework.py | homework.py | py | 1,554 | python | en | code | 0 | github-code | 13 |
26818987991 | from typing import List
import ebooklib
from bs4 import BeautifulSoup
from ebooklib import epub
def __epub_to_html(epub_path: str) -> list:
"""
Reads and output contents of a specified EPUB file in HTML form
:param epub_path: The full path to the input file
:return: a new list
"""
book = ep... | QubitPi/peitho-data | peitho_data/datafication/epub.py | epub.py | py | 1,195 | python | en | code | 0 | github-code | 13 |
21586228021 | """
Valid Palindrome
----------------
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.
Note:
For the purpose of this problem, we define empty string as
valid palindrome.
Example 1:
- Input: "A man, a plan, a canal: Panama"
- Output: true
E... | corenel/lintcode | algorithms/415_valid_palindrome.py | 415_valid_palindrome.py | py | 1,745 | python | en | code | 1 | github-code | 13 |
3745351590 | from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render, redirect
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import... | umairkhan987/Django-React-Twitter-App | backend-django/twitterApi/tweets/views.py | views.py | py | 4,842 | python | en | code | 0 | github-code | 13 |
73828120656 | #!/usr/bin/python
import sys, time
from slackclient import SlackClient
class MySlackClient:
token = None
sc = None
default_ch = None
def __init__(self, token, default_ch):
self.token = token
self.sc = SlackClient(token)
self.default_ch = default_ch
def send_message_log(se... | danypr92/PySlackBot | my_slack/my_slack_client.py | my_slack_client.py | py | 3,590 | python | en | code | 0 | github-code | 13 |
10326522677 | def isPalindrome(self, head):
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
... | NikhilNarvekar123/Competitive-Programming | temp/palindromelinkedlist.py | palindromelinkedlist.py | py | 517 | python | en | code | 0 | github-code | 13 |
41506081333 | # -*- coding: UTF-8 -*-
from sqlitedict import SqliteDict
from nonebot import *
import math
import yaml
import json
import os
import re
bot = get_bot()
class Dict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def dict_to_object(dict_obj):
if not isinstance(dict_obj, dict):
... | sanshanya/hoshino_xcw | XCW/Hoshino/hoshino/modules/eclanrank/util.py | util.py | py | 3,692 | python | en | code | 231 | github-code | 13 |
27159994105 | import tkinter as tk
import json
from tkinter import messagebox
f1 = open("files/proveedorData.json", "r")
c = f1.read()
file = json.loads(c) #js
def formulario_proveedor(app):
codigoP = tk.StringVar()
cuilData = tk.StringVar()
razonSocialData = tk.StringVar()
domicilioData = tk.StringVar()
tele... | Christian-000/ParcialFinalAyED | forms/formProviders.py | formProviders.py | py | 4,192 | python | es | code | 0 | github-code | 13 |
36549522492 | #扫描py文件,根据匹配规则获取其中的函数以及调用方式
#2020.5.29-修复传参bug,精简代码,加入索引
#鸡贼的获取变量名的字符串https://www.zhihu.com/question/42768955#
# import re
# import traceback
# pattren = re.compile(r'[\W+\w+]*?get_variable_name\((\w+)\)')
# __get_variable_name__ = []
# def get_variable_name(x):
# global __get_variable_name__
# if not __get_v... | ezeeo/ctf-tools | Library/utils/get_func_from_pyfile.py | get_func_from_pyfile.py | py | 8,168 | python | en | code | 8 | github-code | 13 |
27949826519 | denom = 0
length = 0
for i in range(1,1000):
remainder = []
value = 1
position = 0
while value not in remainder:
position += 1
remainder.append(value)
value %= i
value *= 10
if position > length:
length = position
denom = i
... | ha36ad/Math | Project_Euler/reciprocal_cycles.py | reciprocal_cycles.py | py | 346 | python | en | code | 0 | github-code | 13 |
12089155933 | # 名片模型模块
class CardModel:
def __init__(self, name='', com_name='', phone=0, job='', id=0):
self.id = id # ID
self.name = name # 姓名
self.com_name = com_name # 公司名
self.phone = phone # 电话
self.job = job # 职位
@property
def phone(self): # 电话读取方法
return se... | 15149295552/Code | Month01/Day17/TestWork/code10/cardModel.py | cardModel.py | py | 576 | python | zh | code | 1 | github-code | 13 |
42332761559 | import yelp_api_galleries
import yelp_api_wineries
def yelp_api_calls(latitude, longitude):
api_call_galleries = yelp_api_galleries.main(latitude, longitude)
api_call_wineries = yelp_api_wineries.main(latitude, longitude)
all_wineries = api_call_wineries[0].get("businesses")
my_business_dictionary =... | jabrad0/Getgo | combine_galleries_wineries.py | combine_galleries_wineries.py | py | 3,690 | python | en | code | 17 | github-code | 13 |
36262459142 | def find_dicom_series(paths, search_directories = True, search_subdirectories = True,
log = None, verbose = False):
dfiles = files_by_directory(paths, search_directories = search_directories,
search_subdirectories = search_subdirectories)
nseries = len(dfiles)
n... | HamineOliveira/ChimeraX | src/bundles/dicom/src/dicom_format.py | dicom_format.py | py | 20,783 | python | en | code | null | github-code | 13 |
19435659017 | import sys
input = sys.stdin.readline
total = int(input())
N = int(input())
mySum = 0
for _ in range(N):
cost, cnt = map(int, input().split())
mySum += cost * cnt
if total == mySum:
print('Yes')
else:
print('No') | Youmi-Kim/problem-solved | 백준/Bronze/25304. 영수증/영수증.py | 영수증.py | py | 247 | python | en | code | 0 | github-code | 13 |
26503973043 | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
point_goal_config = {
'robot_base': os.path.join(BASE_DIR, 'xmls/point.xml'),
'action_scale': [1.0, 0.05],
'task': 'goal',
'lidar_num_bins': 16,
'lidar_alias': True,
'constrain_hazards': True,
'constrain_indicator': True,
... | jjyyxx/srlnbc | srlnbc/env/config.py | config.py | py | 1,677 | python | en | code | 15 | github-code | 13 |
14595964245 | from . import utils
from datetime import datetime, timedelta
class Predict:
def __init__(self, predict_file, predict_data_interval, horizon, logger):
self.predict_data_interval = predict_data_interval
self.logger = logger
self.horizon = horizon
self.predict_data = utils.load_json_f... | AgentGuo/PASS | e2e_test/predict_with_performance_model_exp/predict.py | predict.py | py | 961 | python | en | code | 0 | github-code | 13 |
73473285137 | import json
from django.core.management import BaseCommand
from recipes.models import Ingredient
TABLES = {
Ingredient: 'ingredients.json',
}
class Command(BaseCommand):
def handle(self, *args, **kwargs):
for model, csv_f in TABLES.items():
with open(f'data/{csv_f}', 'r', encoding='utf... | unnamestr/foodgram-project-react | backend/recipes/management/commands/load_data.py | load_data.py | py | 614 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.