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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70954029949 | # OO style
import matplotlib.pyplot as plt
data_uas = [['Bejo', 70],
['Tejo', 83],
['Cecep', 62],
['Wati', 74],
['Karti', 71]
]
fig, ax = plt.subplots()
table = plt.table(cellText = data_uas, loc = 'center')
table.set_fontsize(14)
table.scale(.5, 2) # ukura... | yusrilarzaqi/Matplotlib-Indonesia-belajar | 07--Table Plot/1.py | 1.py | py | 383 | python | en | code | 2 | github-code | 6 |
6827006318 | '''
$Id: gvars.py 44 2010-10-11 11:24:33Z goffer.looney@gmail.com $
'''
from datetime import datetime, date
from models import Global_Var
from django.conf import settings
from django.core.cache import cache
''' see gsettings.models.Global_Var_Type '''
VAR_TYPE_STRING = 1
VAR_TYPE_INT = 2
VAR_T... | kingsdigitallab/eel | django/gsettings/gvars.py | gvars.py | py | 5,370 | python | en | code | 0 | github-code | 6 |
1445709781 | from datetime import datetime
import pandas as pd
import numpy as np
import quandl
from arctic.exceptions import NoDataFoundException
from .base import BaseBacktestObject
from ..utils import keys
from ..utils.config import AdagioConfig
from ..utils.const import (FutureContractMonth, Denominator, PriceSkipDates,
... | thoriuchi0531/adagio | adagio/layers/contract.py | contract.py | py | 14,880 | python | en | code | 0 | github-code | 6 |
14256127266 | from _PMA import PMA
import _PMA.V_Mailbox
class Filter_Mailbox (PMA._V_Mailbox_) :
"""A mailbox which does not contain real messages but presents a filtered
view of a mailbox (or a virtual mailbox).
"""
def __init__ (self, name, matcher, mailbox, prefix = None, ** ckw) :
sel... | xiaochang91/tapyr | _PMA/Filter_Mailbox.py | Filter_Mailbox.py | py | 1,282 | python | en | code | 0 | github-code | 6 |
32044432835 | import re
import io
keywords=["int","void","main","print"]
operators = { '=': 'Assignment Operator','+': 'Additon Operator', '-' : 'Substraction Operator', '/' : 'Division Operator', '*': 'Multiplication Operator'}
optr_keys = operators.keys()
symbols = {';':'semi_colon','{' : 'left_brace', '}':'right_brace'... | Ashwintlp/CD-Mini-Project | lexical_analyser.py | lexical_analyser.py | py | 3,333 | python | en | code | 0 | github-code | 6 |
70474045307 |
from api.models import Term
from sqlite3 import Error
from api.services.connection import create_connection
import sqlite3
import json
def obtener_correcciones():
lista = {'correcciones':[]}
conn = create_connection('db.sqlite3')
cur = conn.cursor()
cur.execute("SELECT * FROM api_correcciones")
... | annemarierolo/tesis-back | api/correciones/services.py | services.py | py | 1,475 | python | es | code | 0 | github-code | 6 |
72602216509 | class Solution:
def numUniqueEmails(self, emails):
s = set()
for email in emails:
email_list = email.split("@")
local_name = email_list[0].split("+")[0].replace(".", "")
email = local_name+"@"+email_list[1]
print(email)
s.add(email)
... | CodingBuye/PythonForLeetcode | Easy/929.Unique Email Address.py | 929.Unique Email Address.py | py | 532 | python | en | code | 0 | github-code | 6 |
31965379047 | #!/usr/bin/env python3
import numpy as np
import urllib.request
import cv2
import binascii
import lorem
import math
import matplotlib.pyplot as plt
def encode_as_binary_array(msg):
"""Encode a message as a binary string."""
msg = msg.encode("utf-8")
msg = msg.hex()
msg = [msg[i:i + 2] for i in range(0... | damiankoper/iobLab | ex2.py | ex2.py | py | 3,584 | python | en | code | 0 | github-code | 6 |
41655800194 | import dash
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import base64
import pandas as pd
import io
import dash_table
import os
import ast
from seaborn.matrix import heatmap
from .layouts.layout import... | DaPraxis/Interactive-Machine-Learning-Tool-for-Risk-Factor-Analysis2 | application/plotlydash/dataDownload.py | dataDownload.py | py | 34,472 | python | en | code | 0 | github-code | 6 |
71476890109 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import grad
import numpy as np
from torch.autograd import Variable
from collections import OrderedDict
class Discriminator(nn.Module):
def __init__(self, input_size, hidden_size, batch_size, dp_keep_prob):
super(Discrimi... | gchafouleas/IFT6135_Assignment3 | discriminator.py | discriminator.py | py | 3,131 | python | en | code | 0 | github-code | 6 |
42985095858 | def commaCode(spam):
try:
i = 0
while i != len(spam) - 1:
print(spam[i], end=', ')
i += 1
print('and ', end=str(spam[-1]))
except IndexError:
print('List is empty')
print('This commaCode puts ... | oqolarte/python-noob-filez | comma_code.py | comma_code.py | py | 550 | python | en | code | 0 | github-code | 6 |
43599298295 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
from time import sleep
import smtplib
url = "https://www.coronatracker.com/pt-br/"
driver = webdriver.Chrome()
driver.get(url)
sleep(5)
save = driver.find_element_by_xpath('//*[@id="__layout"]/div/main/div/... | vinihtao/Projeto-Webscrapping | CasosCOVID.py | CasosCOVID.py | py | 1,266 | python | en | code | 0 | github-code | 6 |
19707587162 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
s=[]
while(head):
s.append(head)
head=head.next
tail=p=ListNode()
... | admaxpanda/LeetCode | 206. Reverse Linked List.py | 206. Reverse Linked List.py | py | 615 | python | en | code | 1 | github-code | 6 |
5792709387 | from collections import OrderedDict
from rest_framework import serializers, relations
class RelatedField(serializers.PrimaryKeyRelatedField):
def __init__(self, **kwargs):
self.serializer = kwargs.pop("serializer", None)
self.lookup = kwargs.pop("lookup", "id")
if self.serializer is not No... | lotrekagency/camomilla | camomilla/serializers/fields/related.py | related.py | py | 4,402 | python | en | code | 8 | github-code | 6 |
20240957628 | """
This file contains the definition of the SMPL model
"""
from __future__ import division, print_function
import torch
import torch.nn as nn
import numpy as np
try:
import cPickle as pickle
except ImportError:
import pickle
from pyrender import PerspectiveCamera, \
DirectionalLight, SpotLight, PointLig... | ZhengZerong/PaMIR | networks/neural_voxelization_layer/smpl_model.py | smpl_model.py | py | 10,840 | python | en | code | 179 | github-code | 6 |
35986807996 | import datetime
import os
# From https://www.quora.com/Whats-the-best-spaced-repetition-schedule. Not really scientific, but it seems decent.
schedule = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
if __name__ == '__main__':
today = datetime.date.today()
schedule_days = [today - datetime.timedelta(days=i) for i in sc... | cgrebosky/SpacedRepetitionReminder | main.py | main.py | py | 779 | python | en | code | 0 | github-code | 6 |
3901687808 | from copy import copy
import pygame
from pygame.math import Vector2, Vector3
from pygame.locals import *
import pygame_gui
from pygame_gui.elements.ui_text_box import UITextBox
from utils import *
from cube import Cube
from hero import Direction
from gold import Gold
from chest import Chest
from box import Box
from ... | odrevet/isometric-map | game.py | game.py | py | 13,216 | python | en | code | 0 | github-code | 6 |
73491954428 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def better_solution(self, head):
tot = 0
cur = head
while cur:
tot += 1
cur = cur.next
mid = (tot // 2) + 1
... | ishmam-hossain/problem-solving | leetcode/876_middle_of_the_linked_list.py | 876_middle_of_the_linked_list.py | py | 722 | python | en | code | 3 | github-code | 6 |
72496131069 | import json
import logging
import os
import requests
from django.http import JsonResponse
from django.shortcuts import redirect
from dotenv import load_dotenv
from rest_framework import status, permissions, response, views
from rest_framework_simplejwt import tokens
from rest_framework_simplejwt.tokens import Refresh... | Rahmet97/TestProjectBackend | oneid/views.py | views.py | py | 8,211 | python | en | code | 0 | github-code | 6 |
9650271610 | from tornado.web import RequestHandler
from tornado.web import gen
from controller import favoriteTopicController
import json
# 收藏话题
class AddFavoriteTopic(RequestHandler):
@gen.coroutine
def post(self):
session_id = self.get_argument('session_id')
topicId = self.get_argument('topicId... | zhuxiyulu/sugar | handlers/favoriteTopicHandler.py | favoriteTopicHandler.py | py | 1,145 | python | en | code | 1 | github-code | 6 |
22546037501 | import pprint
import copy
import numpy as np
class Arete:
"""
Deux extremités (x, y)
weight
"""
def __init__(self, x, y, weight):
self.x = x
self.y = y
self.weight = weight
def __str__(self):
return f"({self.x}, {self.y}, {self.weight})"
... | PsychoLeo/Club_Informatique | 2-Graphes/Graphe.py | Graphe.py | py | 9,677 | python | fr | code | 0 | github-code | 6 |
72531832829 | """add cluster id in comp_runs
Revision ID: 83f9d2a470ef
Revises: dd8220be55ad
Create Date: 2021-08-31 20:02:45.709839+00:00
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "83f9d2a470ef"
down_revision = "dd8220be55ad"
branch_labels = None
depends_on = None
de... | ITISFoundation/osparc-simcore | packages/postgres-database/src/simcore_postgres_database/migration/versions/83f9d2a470ef_add_cluster_id_in_comp_runs.py | 83f9d2a470ef_add_cluster_id_in_comp_runs.py | py | 980 | python | en | code | 35 | github-code | 6 |
70488671227 | # accepted on coderun
def closed_keys_q():
gcd, lcm = get_pars()
if lcm % gcd != 0:
return 0
gcd_factors, lcm_factors = factors(gcd), factors(lcm)
for _ in range(len(gcd_factors)):
lcm_factors.remove(gcd_factors[_])
return 2 ** len(set(lcm_factors))
def factors(number) -> list[in... | LocusLontrime/Python | Yandex_fast_recruit_days/Easy/Closed_key.py | Closed_key.py | py | 976 | python | en | code | 1 | github-code | 6 |
7866989954 | from cs50 import get_string
def main():
st = get_string("Text: ")
cWords = 0
cSent = 0
cLetters = 0
n = len(st)
# Loop over all the char and increment
for i in range(n):
if (st[i] == ' '):
cWords += 1
if (st[i].lower().isalpha()):
cLetters += 1
... | jashnimje/CS50 | Lecture 6/pset6/readability/readability.py | readability.py | py | 720 | python | en | code | 0 | github-code | 6 |
8595210611 | import util
import os
def run():
filespath = 'files'
lists = os.listdir(filespath)
print("发现文件:", len(lists), "个")
for i, file in enumerate(lists):
print(os.path.join(filespath, file))
df = util.get_xlsx_to_dataframe(os.path.join(filespath, file))
if (len(list(df.values)) > 0):... | zjz7304/xlsx_to_database | main.py | main.py | py | 623 | python | en | code | 0 | github-code | 6 |
22186680287 |
import os
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
from main import classify_image # imports function from main.py
app = Flask(__name__, static_url_path='/static')
app.config['UPLOAD_FOLDER'] = 'static/uploads'
@app.route('/')
d... | princemexy/Cervical-cell-classification-using-various-Deep-Learning-Models | app.py | app.py | py | 1,115 | python | en | code | 0 | github-code | 6 |
45805692666 | from selenium import webdriver
import math
import time
import os
import eel
eel.init('web')
def getUrl(url, volume, chapter):
if url[-1] != '/':
url += '/'
return str(url) + 'v' + str(volume) + '/c' + str(chapter)
def startDriver(url, chapterNumbers, outputFolder='', outputName='output', firstChapt... | STmihan/RanobeLib-downloader | main.py | main.py | py | 3,255 | python | en | code | 3 | github-code | 6 |
25070637475 | import graphene
from graphene.types import generic
from graphene_django.rest_framework.serializer_converter import (
convert_serializer_to_input_type as serializer_to_input,
)
from purplship.server.core import serializers
from purplship.server.serializers import make_fields_optional, exclude_id_field
import purpls... | danh91/purplship | server/modules/graph/purplship/server/graph/extension/base/inputs.py | inputs.py | py | 7,522 | python | en | code | null | github-code | 6 |
24988059811 | __author__ = "Luis Manuel Angueira Blanco (Pexego)"
"""
Inheritance of account invoce to add some fields.
"""
from osv import osv, fields
class account_invoice(osv.osv):
"""
Inheritance of account invoce to add some fields
"""
_inherit = 'account.invoice'
_columns = {
'refund_invoices_d... | factorlibre/openerp-extra-6.1 | account_refund_original/account_invoice.py | account_invoice.py | py | 659 | python | en | code | 9 | github-code | 6 |
37077568029 | T = int(input())
num_list = [2, 3, 5, 7, 11]
for i in range(1, T+1):
answer = []
n = int(input())
for j in num_list:
cnt = 0
while n % j == 0:
n /= j
cnt += 1
answer.append(cnt)
print(f'#{i}', *answer) | JeonggonCho/algorithm | SWEA/D2/1945. 간단한 소인수분해/간단한 소인수분해.py | 간단한 소인수분해.py | py | 267 | python | en | code | 0 | github-code | 6 |
74796407546 | import torchvision
from torch import nn
# train_dataset = torchvision.datasets.ImageNet(root="../dataset_ImageNet", transform=torchvision.transforms.ToTensor(),
# split='train', download=True)
vgg16 = torchvision.models.vgg16(pretrained=False)
vgg16_pretrain = torchvision.... | ccbit1997/pytorch_learning | src/model_change.py | model_change.py | py | 737 | python | en | code | 0 | github-code | 6 |
43969342716 | #!/usr/bin/env python
import argparse
from Bio import SeqIO
def extract_starts(fasta):
codon_usage = {}
for record in SeqIO.parse(fasta, "fasta"):
seq = record.seq[0:3]
sseq = str(seq)
try: # If key exists, count += 1
codon_usage[sseq] = (codon_usage[sseq][0] + 1, seq)
... | TAMU-CPT/galaxy-tools | tools/fasta/start_stats.py | start_stats.py | py | 950 | python | en | code | 5 | github-code | 6 |
23759924215 | import requests
import json
def test_shorten_new_url():
orig_url = "http://google.com"
resp = requests.post("http://localhost:8888/shorten", params={"orig_url":orig_url})
url = json.loads(resp.text).get("url")
resp = requests.post("http://localhost:8888", params={"short_url": url})
assert (resp.url... | anandjeyahar/urlshortener | test_url_shorten.py | test_url_shorten.py | py | 421 | python | en | code | 1 | github-code | 6 |
39399812817 | import os
import sys
from functools import partial
from typing import List, Tuple
import numpy as np
import tensorflow as tf
from custom_utils import *
# ------------------------- Function for building cnn ------------------------ #
def build_cnn(filters_list: List[int],
conv2d_regularizer_decay: flo... | YangWu1227/python-for-machine-learning | neural_network/projects/cnn_mnist_classification_sagemaker/src/train_entry.py | train_entry.py | py | 5,786 | python | en | code | 0 | github-code | 6 |
35914283024 | class Solution:
"""
@param A: an integer array
@param k: a postive integer <= length(A)
@param targer: an integer
@return: A list of lists of integer
"""
def kSumII(self, a: list, k: int, target: int) -> list:
a_copied = list(a)
a_copied.sort()
results = []
s... | Super262/LintCodeSolutions | algorithms/search_methods/dfs/problem0090.py | problem0090.py | py | 860 | python | en | code | 1 | github-code | 6 |
22416441261 | import numpy as np
import math
from gridmap2d import *
from bresenham_algorithm import *
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Circle
from matplotlib.animation import ArtistAnimation
def pose2transform(pose):
"""
@brief convert (x, y , yaw) to transform matrix
@param pose:... | democheng/PythonRobotics | SLAM/test.py | test.py | py | 3,620 | python | en | code | 15 | github-code | 6 |
14637749495 | # -*- coding: iso-8859-1 -*-
# Caelan Garrett, Edge Detection
from random import *
import math
from copy import *
global G_HIGH
global G_LOW
G_HIGH = 50
G_LOW = 25
"""initial = open('shapes.pgm').read().replace('\n',' ')
image=initial.split(' ')[:-1]
header = image[:4]
image = image[4:]"""
"""l = int(header[2])
w = in... | caelan/TJHSST-Artificial-Intelligence | Edge Detection/Lab13.py | Lab13.py | py | 6,685 | python | en | code | 0 | github-code | 6 |
4516368952 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Xiaoy LI
# Description:
# run_machine_comprehension.py
# Please Notice that the data should contain
# multi answers
# need pay MORE attention when loading data
import os
import argparse
import numpy as np
import random
import torch
from data_load... | wusongxu/mrc-for-flat-nested-ner | run/train_bert_mrc.py | train_bert_mrc.py | py | 14,951 | python | en | code | null | github-code | 6 |
41058889196 | class Poly:
def __init__(self,*terms):
# __str__ uses the name self.terms for the dictionary of terms
# So __init__ should build this dictionary from terms
self.terms = {}
# Fill in the rest of this method, using *terms to intialize self.terms
for x in t... | solomc1/python | ics 33/solutions/ile2 solutions/Lab 7/YamadaKimberly/poly.py | poly.py | py | 6,076 | python | en | code | 0 | github-code | 6 |
26284510734 | """Makes POST requests to the openai API to find three main topics relating to the article title"""
import re
from datetime import datetime
import json
import pandas as pd
CURRENT_TIMESTAMP = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
JSON_FILE = f'response.json'
def read_response_json() -> list[dict]:
"""Ex... | IADesai/media-sentiment | tagging_pipeline/transform.py | transform.py | py | 2,522 | python | en | code | 0 | github-code | 6 |
15285571367 | from os.path import isfile
import pandas as pd
import logging
from io import BytesIO
from django.http import HttpResponse, JsonResponse, HttpResponseNotFound, Http404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic, View
from django.db import transaction, IntegrityError
from... | LewisResearchGroup/ProteomicsQC | app/maxquant/views.py | views.py | py | 8,789 | python | en | code | 3 | github-code | 6 |
8530766170 | from application import app, db
from flask import render_template, request, redirect, url_for
from flask_login import login_required
from flask_user import roles_required
from application.vehicles.models import Vehicle
from application.vehicles.forms import VehicleForm
@app.route("/vehicles/new/")
@roles_required('A... | skoskipaa/VehicleLogs | application/vehicles/views.py | views.py | py | 1,144 | python | en | code | 0 | github-code | 6 |
7935267536 | import random
import cv2
import numpy
import pygame
# 单个粒子
class Particle():
def __init__(self, rect, w):
self.rect = rect
self.w = w
self.dis = 0
self.hist = []
self.dx = 0
self.dy = 0
def update(self, pixelArray, width, height):
self.rect.centerx =... | 2015211289/pygame | auto_review.py | auto_review.py | py | 12,073 | python | en | code | 1 | github-code | 6 |
36504902063 | #Brendan Simms is the main author of this file
#I, Brendan Simms, acknowledge and promise to adhere to the conditions of the DCU integrity policy
import CPU
def rr(ListofTasks):
z = 0
temp_burst = [] # create a new list
quantum = 10
waittime = 0
turnaround = 0
print("Round Robin:\n")
for line in ListofTasks... | BrendanSimms8898/Python | Second-Year/Ca216-Scheduling/schedule_rr.py | schedule_rr.py | py | 1,756 | python | en | code | 0 | github-code | 6 |
27679628120 | #!/usr/bin/env python
# https://github.com/drf5n/drf5n-public/blob/master/gdalwarp2match.py
from osgeo import gdal, gdalconst
import argparse
parser = argparse.ArgumentParser(description='Use GDAL to reproject a raster to match the extents and res of a template')
parser.add_argument("source", help="Source file")
par... | comet-licsar/licsar_proc | python/gdalwarp2match.py | gdalwarp2match.py | py | 1,620 | python | en | code | 9 | github-code | 6 |
26277293350 | import functools
import logging
import os
import Bio.Seq
import Bio.SeqRecord
import six
from . import conf, errors
logger = logging.getLogger(__name__)
configs = conf.CONFIGS
ELASPIC_LOGO = """
8888888888 888 d8888 .d8888b. 8888888b. 8888888 .d8888b.
888 888 d88888 d88P Y88b 888 ... | elaspic/elaspic | elaspic/pipeline.py | pipeline.py | py | 3,833 | python | en | code | 7 | github-code | 6 |
71452829947 | import numpy as np
from functools import partial
#from multiprocessing import Pool
import matplotlib.pyplot as plt
from matplotlib import cm
from pandas import DataFrame
import scipy as sc
import scipy.signal
import os
import pdb
import time
def group_into_bands(fft, fft_freq, nfreq_bands):
if nfreq_bands == 178:
... | Anmol6/kaggle-seizure-competition | preprocess/pre_processing.py | pre_processing.py | py | 7,809 | python | en | code | 0 | github-code | 6 |
12294385591 | import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba
import pandas as pd
import os
import jieba.analyse
positiondata= pd.read_excel('positiondata.xlsx')
position_detail = positiondata['position_detail']
detail_list = []
for detail in position_detail:
detail_list.append(str(detail).replace(... | woinews/lagou_position | Position_WordCloud.py | Position_WordCloud.py | py | 1,136 | python | en | code | 2 | github-code | 6 |
18626707386 | #!/usr/bin/env python
"""Tests for module parallel"""
import unittest
import os
from mandelbrot.parallel import ParallelCalculator
from mandelbrot import tests
DATA_FILE = os.path.join(tests.OUTPUT_DIR, ParallelCalculator.file_name_data)
PLOT_FILE = os.path.join(tests.OUTPUT_DIR, ParallelCalculator.file_name_plot)
c... | kidmose/python-course-mini-project | mandelbrot/tests/test_parallel.py | test_parallel.py | py | 763 | python | en | code | 0 | github-code | 6 |
30451465881 | from calendar import c
from re import S
import sys
import time
import smbus
import spidev
import RPi.GPIO as GPIO
import logging
from ctypes import *
logger = logging.getLogger()
# logger.setLevel(logging.INFO) # Display all print information
logger.setLevel(logging.FATAL) # If you don’t want to display too many... | DFRobot/DFRobot_BME280 | python/raspberrypi/DFRobot_BME280.py | DFRobot_BME280.py | py | 22,063 | python | en | code | 9 | github-code | 6 |
4509313124 | # Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
# input: root of a binary tree
# output: sum of all integers in the tree
def tree_paths_sum(root):
# initiate a count
count = 0
# initi... | rupol/Code-Challenges | Trees/tree_paths_sum.py | tree_paths_sum.py | py | 1,070 | python | en | code | 0 | github-code | 6 |
21354450845 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.n = 0
self.nums = []
def addNum(self, num: int) -> None:
if not self.n:
self.nums.append(num)
self.n += 1
return
l = 0
... | Alex-Beng/ojs | FuckLeetcode/295. 数据流的中位数.py | 295. 数据流的中位数.py | py | 1,026 | python | en | code | 0 | github-code | 6 |
33180005513 | with open('27-A.txt') as f:
conts = [int(x) for x in f]
conts.pop(0)
trash = []
mid = len(conts)//2
leng = len(conts)
conts = conts+conts
prices = []
for i in range(leng):
d = conts[i:i+leng]
print(d)
price = 0
pricef = 1000000
P = mid+i+1
index = 0
for k in range(len(d)):
... | Ethryna/InfTasks | 2 полугодие/27-A.py | 27-A.py | py | 492 | python | en | code | 2 | github-code | 6 |
29150918130 | import os
import torch
import torchmetrics
from pathlib import Path
# Huggingface datasets and tokenizers
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.trainers import WordLevelTrainer
from tokenizers.pre_tokenizers import Whitespace
os.environ["TOKENIZERS_PARALLELISM"] = "t... | swapniel99/erav1s15 | utils.py | utils.py | py | 5,016 | python | en | code | 0 | github-code | 6 |
44738680071 | import spacy
from spacy.lang.en.stop_words import STOP_WORDS
from heapq import nlargest
class SpacyStrategy:
def summarize_from_text(self, text):
raw_text = text
stopwords = list(STOP_WORDS)
nlp = spacy.load('en')
docx = nlp(raw_text)
# Build Word Frequency
# word.... | andredantasrocha/contact-summarizer | summarization/spacy_strategy.py | spacy_strategy.py | py | 1,691 | python | en | code | 1 | github-code | 6 |
18215247751 | def get_tag(text):
tag = ''
flag = False
for char in text:
if char == "<":
flag = True
if flag:
tag += char
if char == ">":
flag = False
yield tag
tag = ''
#txt = "<head>nottag</head><title><dog></dog></title><marquee></mar... | andrew-qu2000/Schoolwork | cs1134/get_tag.py | get_tag.py | py | 1,047 | python | en | code | 0 | github-code | 6 |
35297756546 | def func():
a=int(input("first number is"))
b=int(input("second number is"))
c=int(input("third number is"))
if a==b and b==c:
print("all are same")
elif a>b and b>c:
print("a is greater")
elif a<b and b<c:
print("c is greater")
elif a<b and b>c:
print("b is greater")
func() | nannurinithinsaireddy/python-programmes | inuput.py | inuput.py | py | 293 | python | en | code | 0 | github-code | 6 |
4668550364 | from django.core.exceptions import PermissionDenied
class UserIsAuthorMixin(object):
"""
Checks that the user is the author of the object. If they are not, raise a
403 error
"""
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated and request.user.profile.pk is no... | hotwire-django/hotwire-django-realworld | articles/mixins.py | mixins.py | py | 468 | python | en | code | 31 | github-code | 6 |
8537819463 |
def analyze():
# test_file = open("../result/test.txt", 'r')
dict_file = open("../data/dict.txt", 'r')
correct_file = open("../data/correct.txt", 'r')
misspell_file = open("../data/misspell.txt", 'r')
misspell_not_in_dict = open("../data/misspell_not_in_dict.txt","w")
dict = []
for line i... | MooTong123/Unimelb-Subject | COMP90049 Introduction to Machine Learning/Project/project1/Project1_MuTong_28_04_2019/code/analyze_dataset.py | analyze_dataset.py | py | 1,580 | python | en | code | 3 | github-code | 6 |
34002077692 | # SWEA 5105 미로의 거리
from collections import deque
def bfs(x, y):
q = deque([(x, y)])
arr[x][y] = 0
dr = [-1, 1, 0, 0]
dc = [0, 0, -1, 1]
while q:
r, c = q.popleft()
for i in range(4):
nr = r + dr[i]
nc = c + dc[i]
if 0 <= nr < N and ... | jinmoonJ/algorithm | 0825/SWEA_5105.py | SWEA_5105.py | py | 1,147 | python | en | code | 0 | github-code | 6 |
3361094578 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from functions import noso
from functions import dtdu_backward
from functions import dodt
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.float
class fcn(nn.Module):
def __init__(self, task, ... | dooseokjeong/BPTC-NOSO | SNN_folded/network.py | network.py | py | 5,968 | python | en | code | 3 | github-code | 6 |
21776740540 | import sys
import os
import click
import json
import re
import pandas as pd
import numpy as np
from PIL import ImageTk, Image
from tkinter import Tk
from .modules.interface import AnnotationInterface
@click.version_option("0.0.1")
@click.command()
@click.argument('image_dir', required=True)
@click.argument('bindings... | jacobhepkema/annotpics | annotpics/__main__.py | __main__.py | py | 3,726 | python | en | code | 1 | github-code | 6 |
8733632634 | from hmmlearn import hmm
import numpy as np
class CustomHMM:
def __init__(self):
def build_hmm():
model = hmm.GMMHMM(n_components=3, n_mix=3, covariance_type="diag", init_params="t")
model.transmat_ = np.array([[0.5, 0.5, 0.0],
[0.0, 0.5, 0.5],
... | mattschaff/upennvoicerecog | CustomHMM.py | CustomHMM.py | py | 986 | python | en | code | 1 | github-code | 6 |
9202548056 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
import h5py
import random
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset
from torchvision import models, transforms
from su... | SuperBruceJia/NLNet-IQA | Cross Database Evaluations/data_process/get_data.py | get_data.py | py | 6,026 | python | en | code | 8 | github-code | 6 |
70329767867 | import requests, re, os, json
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
class Check_Influences(object):
def __init__(self):
self.folder_data_name = '../../files/data'
self.json_name_link = '../../files/name_links.json'
self.good_json_file_name = '../../files/good_name_links.json... | LucaTomei/Computer_Scientists | src/Second_Phase/check_influences.py | check_influences.py | py | 4,271 | python | en | code | 1 | github-code | 6 |
10502969372 | from rest_framework.test import APITestCase
from ...services.notification_service import NotificationService
from ...api_services.notification import NotificationAPIService
from django.urls import reverse
class TestNotificationAPIServices(APITestCase):
def setUp(self):
self.payload = {
"title"... | anojkr/onboarding-project | push_notification/apps/notification/tests/unit/test_notification_api_services.py | test_notification_api_services.py | py | 1,441 | python | en | code | 0 | github-code | 6 |
24696329244 | """
Author : Animesh Bhasin
Version : 1
Version Date : 16th Nov 2022
Description : This script is to read the data from City of New York API and load into postgres db
"""
import requests
import pandas as pd
from datetime import date, timedelta
from sqlalchemy import create_engine
import os
def main():
"""
Mai... | Sapphirine/202112-26-NYC-Vehicle-Crash-Analysis | get_crashes.py | get_crashes.py | py | 5,844 | python | en | code | 1 | github-code | 6 |
2614278018 | # topics = ['动态规划']
from typing import List
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
"""
Dynamic Programming
time O(mn), space O(mn), m 和 n 分别为 nums1 和 nums2 的长度
"""
m, n = len(nums1), len(nums2)
dp = [[0] * (n + 1) fo... | show-me-code/signInHelper-using-face- | algorithms/[1035]不相交的线/solution.py | solution.py | py | 655 | python | en | code | 0 | github-code | 6 |
7295749579 | import discord, datetime, time
from discord.ext import commands, tasks
from itertools import cycle
start_time = time.time()
class Events(commands.Cog):
def __init__(self, client):
self.client = client
self.status = cycle(['Bind', 'Haven', 'Ascent','Split','Fracture'])
@tasks.loop(seconds... | awesomedustyn/CAP-N- | cogs/Events.py | Events.py | py | 908 | python | en | code | 0 | github-code | 6 |
43367360996 | # `shutil` module provides many functions of high-level operations
# on files and collections of files.
# https://www.geeksforgeeks.org/python-shutil-copyfile-method/
from shutil import copyfile
from subprocess import Popen
import os, time, stat
bteq_glue_tester_path = r'C:\Users\oseledko.a\Desktop\AWS Database Tester... | SimaFish/python_practice | generate_test_json.py | generate_test_json.py | py | 1,445 | python | en | code | 0 | github-code | 6 |
14133753716 | #!/usr/bin/env python3
# File: code/remove_email.py
import csv
import club
source = club.EMAIL_JSON
if __name__ == '__main__':
with open(source, newline='') as inf:
reader = csv.DictReader(inf)
print("so far so good")
| alexKleider/sql | code/remove_email.py | remove_email.py | py | 239 | python | en | code | 0 | github-code | 6 |
21246199914 | import os
import pytest
import pandas as pd
from typing import List
from faker import Faker
from dataclasses import dataclass
from prepare_dataset import read_data, train_target
@dataclass()
class TrainingPipelineParams:
input_data_path: str
@pytest.fixture()
def dataset_path(tmpdir):
fake... | made-ml-in-prod-2021/alexshevchuk7 | ml_project/tests/test_prepare_data.py | test_prepare_data.py | py | 1,815 | python | en | code | 0 | github-code | 6 |
36345253262 | """
EECS 445 - Winter 2017 - Project 2
FER2013 - Skeleton
This file reads the dataset and provides a function `preprocessed_data`
that returns preprocessed images, labels
Usage: python -m data_scripts.fer2013
"""
import numpy as np
from scipy.misc import imresize
from sklearn.utils import resample
import pandas
from ... | lixhuang/EECS445p2 | data_scripts/fer2013.py | fer2013.py | py | 6,969 | python | en | code | 0 | github-code | 6 |
26038606960 | #!/usr/bin/env python3
import os
import sys
def auto_tune_area():
command = "xdpyinfo | grep dimensions | awk '{print $2;}'"
w, h = os.popen(command).read().split('x')
tune_area(w, h)
def tune_area(screen_w, screen_h):
screen_w = float(screen_w)
screen_h = float(screen_h)
with os.popen('xse... | Valera/Scratchpad | tune-wacom.py | tune-wacom.py | py | 1,250 | python | en | code | 0 | github-code | 6 |
33781322730 | import copy
import datetime as dt
import decimal
import re
import pytest
import pytz
from google.cloud import bigquery
from google.cloud import bigquery_storage_v1beta1
from google.protobuf import timestamp_pb2
def _to_bq_table_ref(proto_table_ref, partition_suffix=""):
"""Converts protobuf table reference to b... | silverdev/google-cloud-python | bigquery_storage/tests/system/test_reader.py | test_reader.py | py | 15,016 | python | en | code | 0 | github-code | 6 |
7377958665 | from flask import Flask,request,jsonify
import numpy as np
from scipy.signal import find_peaks
import pandas as pd
app = Flask(__name__)
@app.route('/data_process',methods=['GET'])
def data_process():
dict1={}
if '[' and ']' and "," in request.args['C1 raw']:
input_control=request.args['C1 raw'].str... | Owaiskhan9654/Pelican-API-for-data-Processing-Canary-Global | app.py | app.py | py | 2,388 | python | en | code | 1 | github-code | 6 |
40639327200 | import random
def married_random():
boys = ["ali", "reza", "yasin", "benyamin", "mehrdad", "sjjad", "aidin", "shahin"]
girls = ["sara", "zari", "neda", "homa", "eli", "goli", "mari", "mina"]
size1 = len(boys)
size2 = len(girls)
random_boys = list()
random_girls = list()
while l... | AmiraliRahbari/OsLab_assignment7 | marriage.py | marriage.py | py | 843 | python | en | code | 0 | github-code | 6 |
22633446316 | import ply.lex as lex
# List of token names. This is always required
tokens = (
'PROP',
'TRUE',
'FALSE',
'NOT',
'AND',
'OR',
'IMPLY',
'X',
'U',
'F',
'G',
'R',
'LPAREN',
'RPAREN',
)
# Regular expression rules for simple tokens
t_PROP = r'[a-zA-Z_][a-z... | AriRodriguezCruz/mcfgpr | parser.py | parser.py | py | 1,058 | python | en | code | 0 | github-code | 6 |
38903741775 | #SIEMPRE SIEMPRE SIEMPRE que abrimos un fichero lo tenemos que CERRAR después
#Si abrimos un fichero con with, python hace el close() por nosotros :))
fichero = 'nombres2.txt' #qué tengo que poner como fichero?
#qué pasa si no está en la misma carpeta?
import pickle
import csv
with open(fichero)... | rjvillen/clases-particulares-python | ficheros/ficheros_ejemplos_sol.py | ficheros_ejemplos_sol.py | py | 2,343 | python | es | code | 0 | github-code | 6 |
36837369973 | """
Ex 43.
Given the arrays, arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) and arr1 = np.array([2, 3, 4]), find the common items present in both arrays.
Program Description: The objective of this program is to find the common items between two arrays using numpy. The common items get added to a new array.
Note: Use ... | Deepsphere-AI/AI-lab-Schools | Grade 08/Unit-3/Python/Eight_PPT_43.py | Eight_PPT_43.py | py | 529 | python | en | code | 0 | github-code | 6 |
70267284349 |
from epyk.core.Page import Report
from epyk.mocks import urls as data_urls
page = Report()
page.headers.dev()
# https://codepen.io/sgratzl/pen/qBWwxKP
records = [
{"name": "France", "value": 23}
]
page.ui.geo.chartJs.choropleths.world(records, y_columns=["value"], x_axis="name")
page.ui.geo.chartJs.choropleths.... | epykure/epyk-templates | locals/geo/chartjs.py | chartjs.py | py | 368 | python | en | code | 17 | github-code | 6 |
776580237 | from pprint import pprint
import requests
import json
# Задание 1 Посмотреть документацию к API GitHub, разобраться как вывести список репозиториев для конкретного пользователя,
# сохранить JSON-вывод в файле *.json.
url = 'https://api.github.com/users/Karamba278/repos' #Сразу вставил имя юзера (себя) в ссылку, но мо... | Karamba278/parsing | DZ1/lesson1.py | lesson1.py | py | 1,643 | python | ru | code | 0 | github-code | 6 |
74186588989 | """ Loading logic """
import sqlite3
import sys
from decimal import Decimal
from datetime import datetime
def load_data(database_uri: str, data: list) -> bool:
"""
Loads Bitcoin rate data into an SQLite database.
Args:
database_uri (str): The URI of the SQLite database.
data (list): The l... | richardogoma/bitcoin-rate-etl | etl/load/loader.py | loader.py | py | 2,943 | python | en | code | 0 | github-code | 6 |
4387851550 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para buenaisla
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
t... | TuxRneR/pelisalacarta-personal-fork | tags/xbmc-addons/plugin.video.pelisalacarta/pelisalacarta/channels/buenaisla.py | buenaisla.py | py | 11,599 | python | en | code | 0 | github-code | 6 |
38761817494 |
def two_strings(s1, s2):
"""
Prints "YES" if s1 and s2 share a common substring
or "NO" otherwise.
@param s1: The first string to check
@param s2: The second string to check
return: None
rtype: None
"""
# Since we're only looking for a simple "YES" or "NO"
# with regards to wh... | WhosKhoaHoang/hacker_rank_fun | Interview Preparation Kit/2. Dictionaries and Hashmaps/two_strings.py | two_strings.py | py | 831 | python | en | code | 0 | github-code | 6 |
74536427068 | from tkinter import *
from tkinter import filedialog
import snapshot
import pickle
class SaveSyncGui():
def __init__(self):
root = self.root = Tk()
Label(root, text="Save Game Synch").pack()
self.frame = Frame(root)
self.frame2 = Frame(root)
self.listbox1 = Listbo... | keyvin/savesync | SaveSync/gui.py | gui.py | py | 2,583 | python | en | code | 0 | github-code | 6 |
31357581621 | import os
from setuptools import setup, find_packages
from nats import __version__
this_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(this_dir, 'requirements.txt')) as f:
requirements = f.read().splitlines()
setup(
name='nats-client',
version=__version__,
description='NATS cl... | nats-io/nats.py2 | setup.py | setup.py | py | 834 | python | en | code | 62 | github-code | 6 |
716717090 | from plenum.common.constants import SERVICES, VALIDATOR, TARGET_NYM, DATA
from sovrin_common.roles import Roles
from stp_core.network.port_dispenser import genHa
import pytest
from sovrin_client.test.cli.helper import doSendNodeCmd
def testSuspendNode(be, do, trusteeCli, newNodeAdded):
"""
Suspend a node an... | hyperledger-archives/indy-client | sovrin_client/test/cli/test_node_suspension.py | test_node_suspension.py | py | 2,820 | python | en | code | 18 | github-code | 6 |
75246891067 | import collections
import copy
import numpy as np
import mindspore as ms
from mindspore import nn, ops
from mindspore import Tensor, Parameter
from mindspore.nn.layer.normalization import _BatchNorm
from mindspore.nn.probability.distribution import Normal
from mindspore_gl import Graph
from mindspore_gl import GNNCe... | shuoliu0-0/EDIS | model.py | model.py | py | 21,685 | python | en | code | 1 | github-code | 6 |
19692262120 | #Socratica Video 22 List Comprehension
#list comprehension [expression for variable in collection if test1 and test2]
#list comprehension [expression for variable1 in collection1 and variable2 in collection2]
squares = []
for i in range(1, 11):
squares.append(i**2)
print(squares) #print [1, 4, 9, 16, 25, 36, 49, 64,... | raymondmar61/pythonoutsidethebook | listcomprehension.py | listcomprehension.py | py | 10,585 | python | en | code | 0 | github-code | 6 |
21215563455 | # -*- coding: utf-8 -*-
from django.db.models import Count, Case, When
from django.db.models.functions import TruncDate
from django.utils.translation import gettext as _
from django.utils.translation import get_language
import plotly.offline as plotly
import plotly.graph_objs as go
from core.utils import duration_par... | babybuddy/babybuddy | reports/graphs/diaperchange_intervals.py | diaperchange_intervals.py | py | 2,953 | python | en | code | 1,766 | github-code | 6 |
8631506734 | #!/usr/bin/env python3
import argparse
import logging
import requests
import sys
from alert_autoconf.config import read_from_file
from json import JSONDecodeError
LOG_LEVEL = "DEBUG"
def parse_params() -> dict:
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument(
"-u",
"--ur... | avito-tech/alert-autoconf | bin/validate.py | validate.py | py | 2,475 | python | en | code | 1 | github-code | 6 |
37950158304 | import copy
import matplotlib.pyplot as plt
from numpy import sqrt, inf
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from models.cnn import CNN
from linegeneration.generate_lines import create_image_set
from utils.logger impor... | 3it-inpaqt/line-classification-slope | models/run_cnn.py | run_cnn.py | py | 6,433 | python | en | code | 0 | github-code | 6 |
21884520657 | """Use simple rate comparisions, try predicting event rates."""
import numpy as np
import matplotlib.pyplot as plt
from frbpoppy import Survey
from tests.convenience import plot_aa_style, rel_path
ALPHAS = np.around(np.linspace(-0.2, -2.5, 7), decimals=2)
SURVEYS = ('parkes-htru', 'arecibo-palfa', 'askap-fly', 'fast... | TRASAL/frbpoppy | tests/rates/alpha_analytical.py | alpha_analytical.py | py | 1,884 | python | en | code | 26 | github-code | 6 |
20281103184 | pessoa = {}
pessoas = []
soma = media = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Nome: '))
while True:
pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper()[0]
if pessoa['sexo'] in 'MF':
break
print('ERRO! Por favor, digite apenas M ou F.')
pessoa['idad... | JoooNatan/CursoPython | Mundo03/Exs/Ex094.py | Ex094.py | py | 1,130 | python | pt | code | 0 | github-code | 6 |
10790083831 | import html
import os
import re
import requests
class DirFile:
def __init__(self, shop_data_dict, img_list, path, shop):
self.shop_data_dict = shop_data_dict
self.img_list = img_list
self.path = path
self.shop = shop
def save_to_local(self):
try:
folder_nam... | kimbackdoo/Hareubang-Crawler | crawl/dir_file.py | dir_file.py | py | 1,955 | python | en | code | 0 | github-code | 6 |
19238997232 | from collections import deque
N = int(input())
def bfs():
cnt = -1
q = deque()
for i in range(10):
q.append(i)
while q:
s = q.popleft()
cnt += 1
if cnt == N:
print(s)
break
for i in range(s%10):
q.append(s * 10 + i)
else:
... | sdh98429/dj2_alg_study | BAEKJOON/backtracking/b1038.py | b1038.py | py | 344 | python | en | code | 0 | github-code | 6 |
71783932668 | from setuptools import setup, find_packages
def readme():
with open('README.rst', encoding='utf-8') as f:
content = f.read()
return content
def get_version():
with open('VERSION', encoding='utf-8') as f:
version = f.read()
return version
setup(
name='thonny-quecpython',
ver... | wcache/thonny_quecpython | setup.py | setup.py | py | 1,267 | python | en | code | 0 | github-code | 6 |
29951529490 | import csv
class CatalogItem:
"""def __init__(self, id, name, colors, group, sport, category, subcategory, sex):
self.id = id
self.name = name
self.colors = colors.split(str="/")
self.group = group
self.sport = sport
self.category = category
self.subcategory... | disulfiram/SoftUni-PythonProgramming | 07 The Great Task/CatalogItem.py | CatalogItem.py | py | 1,425 | python | en | code | 0 | github-code | 6 |
41349777605 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
WTF_CSRF_ENABLED = True
SECRET_KEY = "4c2cc707e708b9b2ad8a5d427868d580e85ea3943912d916"
SECURITY_PASSWORD_SALT = "3e5fade13026ad4d6121d428c6eb43adf078d1719d1f4615"... | Aurantia/AurantiaWebService | settings.py | settings.py | py | 667 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.