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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20914400525 | import sqlite3
import requests
from xml.dom import minidom
from prettytable import PrettyTable
def create_kns_factions_db():
"""
create sql database with all information on factions that run to the israeli knesset.
"""
# request data
database_url = 'http://knesset.gov.il/Odata/ParliamentInfo.svc/K... | MeirNizri/Python-Assignments | Python Exercise 5/create_kns_db.py | create_kns_db.py | py | 1,847 | python | en | code | 0 | github-code | 13 |
29217854861 | import base64
from typing import List, Optional, cast, Dict, Any
class StackPrinterConfig:
DEFAULT_MAX_VALUE_WIDTH: int = 30
def __init__(
self, max_value_width=DEFAULT_MAX_VALUE_WIDTH, top_of_stack_first=True
):
self.max_value_width = max_value_width
self.top_of_stack_first = top... | algorand/py-algorand-sdk | algosdk/dryrun_results.py | dryrun_results.py | py | 6,981 | python | en | code | 242 | github-code | 13 |
32544639538 | import argparse
import numpy as np
import cv2
from PIL import Image
from pathlib import Path
from tensorflow import keras
from utils import read_helpers as rh
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_directory',
default='../../data/still_images'... | kiarastempel/explaining-echo-prototypes | src/utils/single_prototype_selection.py | single_prototype_selection.py | py | 4,620 | python | en | code | 2 | github-code | 13 |
15479952150 | from peewee import *
database = MySQLDatabase(
'telethon',
host="ls-05e88db820c0415c07abb89eec7d3f57e39a3e64.cu5yrqifxqtg.us-east-2.rds.amazonaws.com",
user='dbmasteruser',
password='[jbMhN029vJ6:bf2=M+{f&;89p7HaU`Z'
)
class Campaign(Model):
id = AutoField(primary_key=True, unique=True, null=Fals... | Cragser/tel-graham-52 | src/application/campaign/create_all_campaign_table.py | create_all_campaign_table.py | py | 684 | python | en | code | 0 | github-code | 13 |
72672548498 | #!/usr/bin/python env
#python 3 standard library
import argparse
from argparse import HelpFormatter
import sys
def main():
parser = argparse.ArgumentParser(prog='SPARKLE', description='''Proof of concept: alignment of FASTQ sequences to a refernece genome using clustered SPARK''', epilog='''This program was develo... | Daniele-db2/SPARKLE | SPARKLE/SPARKLE.py | SPARKLE.py | py | 3,879 | python | en | code | 0 | github-code | 13 |
74564480018 | #!/usr/bin/env python
"""
_TaskSummary_
List the summary of job numbers by task given a workflow
"""
from WMCore.Database.DBFormatter import DBFormatter
from WMCore.JobStateMachine.Transitions import Transitions
from future.utils import listvalues
class TaskSummaryByWorkflow(DBFormatter):
sql = """SELECT wmbs_w... | dmwm/WMCore | src/python/WMCore/WMBS/MySQL/Monitoring/TaskSummaryByWorkflow.py | TaskSummaryByWorkflow.py | py | 3,581 | python | en | code | 44 | github-code | 13 |
17745906012 | # Algorithms and Uncertainty (2019) - PUC-Rio
#
# MWU Classifier to distinguish two digits based on one pixel (MNIST)
#
# Last updated: 27/04/2019
#
# Authors: Ítalo G. Santana & Rafael Azevedo M. S. Cruz
from __future__ import print_function
import random
import numpy as np
import time
import sys
import pandas as pd
... | italogs/boosting-mwu-character-recognition | main.py | main.py | py | 14,805 | python | en | code | 1 | github-code | 13 |
34572652062 | divisor = int(input())
boundary = int(input())
number = 0
previous_number = 0
for i in range(boundary, divisor, -1):
if i % divisor == 0 and i > 0 and i <= boundary:
number = i
break
print(i)
| TinaZhelyazova/02.-Python-Fundamentals | 02. Exercise Basic Syntax, Conditional Statements and Loops/04. Maximum Multiple.py | 04. Maximum Multiple.py | py | 214 | python | en | code | 0 | github-code | 13 |
70135986577 | import tqdm
import unicodedata, json
import torch
from torch.utils.data import DataLoader as DataLoader, TensorDataset
class DataProcessor:
def __init__(self, config_dir):
with open(config_dir, 'r') as openfile:
json_object = json.load(openfile)
self.max_seq_length = json_object["max... | XuanLoc2578/ner_mluke_vnese | ner_mluke/mydataset.py | mydataset.py | py | 14,889 | python | en | code | 0 | github-code | 13 |
6757339317 | import os
import pickle
import numpy as np
from torch.utils.data import Dataset
from e2edet.utils.det3d.general import read_from_file, read_pc_annotations
class PointDetection(Dataset):
"""An abstract class representing a pytorch-like Dataset.
All other datasets should subclass it. All subclasses should ove... | kienduynguyen/BoxeR | e2edet/dataset/helper/point_detection.py | point_detection.py | py | 5,338 | python | en | code | 126 | github-code | 13 |
220033965 | from pathlib import Path
from qtpy.QtCore import Qt, QItemSelection, Signal, QModelIndex
from qtpy.QtGui import QIcon, QStandardItemModel, QStandardItem
from qtpy.QtWidgets import QVBoxLayout, QWidget, QTreeView, QAbstractItemView
from happi import Client, Device, HappiItem, from_container
from happi.backends.mongo_db ... | ihumphrey/Xi-cam.plugins.Acquire | xicam/Acquire/devices/happi.py | happi.py | py | 5,153 | python | en | code | null | github-code | 13 |
43359486143 | import numpy as np
import torch
import trimesh
import os
source_dir = "bosphorusReg3DMM/"
export_dir = "bosphorus_mesh/"
os.mkdir(export_dir)
faces = np.load("tri.npy")
files = [f for f in os.listdir(source_dir) if f.endswith('.pt')]
for f in files:
name = f.split(".")[0]
vertices = torch.load(source_dir+f).nu... | w00zie/3d_face_class | data/create_mesh.py | create_mesh.py | py | 435 | python | en | code | 8 | github-code | 13 |
71082098257 | import random
import numpy as np
from activation import linear_function
class perceptron:
def __init__(self):
random.seed(1)
"""
the weight matrix with random values between -1 and 1.
The weight matrix has shape (3, 1) as it corresponds to 3 input
features and 1 output.
... | wayneotemah/ML-from-scratch | perceptron/perceptron.py | perceptron.py | py | 1,926 | python | en | code | 0 | github-code | 13 |
12696829725 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import Crypto.Cipher.PKCS1_v1_5
import Crypto.Hash.SHA
import Crypto.PublicKey.RSA
import Crypto.Random
import Crypto.Signature.PKCS1_v1_5
def _to_string(val):
if isinstance(val, str):
return val
if isinstance(val, unicode):
return ... | plusplus1/rsademo | python/RSAUtil.py | RSAUtil.py | py | 3,459 | python | en | code | 0 | github-code | 13 |
285293555 | #https://leetcode.com/problems/reverse-only-letters/submissions/
class reveseCharacters(object):
def main(self):
print(self.reverseCharacters("a-bC-dEf-ghIj"))
def reverseCharacters(self, S):
S = list(S)
start = 0
end = len(S) - 1
while start <= end:
... | soniaarora/Algorithms-Practice | Solved in Python/LeetCode/String/reverseonlyCharacters.py | reverseonlyCharacters.py | py | 690 | python | en | code | 0 | github-code | 13 |
74792261778 | from django.shortcuts import render
from .models import Product, ProductImages
# get all products
def productlist(request):
productlist = Product.objects.all()
context = {'product_list' : productlist}
template = 'Product/product_list.html'
return render(request, template, context)
# get all the dat... | LawrenceDavy13/resaleshop | venv/src/product/views.py | views.py | py | 683 | python | en | code | 0 | github-code | 13 |
38661183060 | #!/usr/bin/python
import Adafruit_DHT
import datetime
import sqlite3
from sqlite3 import Error
def create_connection(db):
con = None
try:
con = sqlite3.connect(db)
except Error as e:
print(e)
return con
def create_table(con, create_sql):
try:
c = con.cursor()
c.ex... | kamil271e/embedded-systems-lab | lab5/src/main.py | main.py | py | 1,830 | python | en | code | 0 | github-code | 13 |
28432568546 | import uuid
from datetime import datetime
from src.common.database import Database
class Installment(object):
def __init__(self, installment_num, intent_id, district, center, units_required, garment_type, uploaded_date,
deadline, total_wages, units_pm, user_id, units_received=None, units_assign... | karthigeyankalyan/CooperativeSocieties | src/models/installment.py | installment.py | py | 6,193 | python | en | code | 0 | github-code | 13 |
17332218981 | import re
from MarriageValidation import create_date, at_least_age
#############################################
#### US 12
#### Check that the parents aren't too old
#############################################
def old_parents_too_old(tags, ged_file):
for family in ged_file: #loop through ged file
... | EricLin24/SSW555-DriverlessCar | ParentsNotTooOld.py | ParentsNotTooOld.py | py | 1,784 | python | en | code | 0 | github-code | 13 |
9069122628 | import crawl as crawler
import crawl_from_files as crawler_files
import os
from os import path
import preprocessor as pre
import measure as mea
print('* '*10+'MENU'+'* '*10)
print('* 1.crawler from default directory *')
print('* 2.crawler from your website *')
print('* '*10+'* * '+'* '*10)
choo... | nvtuehcmus/datamining | main.py | main.py | py | 2,300 | python | en | code | 0 | github-code | 13 |
24724836441 | # The Weather app
# Write a console application which takes as an input a city name and returns current weather in the format of your choice.
# For the current task, you can choose any weather API or website or use openweathermap.org
import requests
KEY = "5fdd472908385dc9e4ee0706958a2a6e"
def get_weather(lat, lon)... | alex-raspopov/python_group_01.11.2022 | Homework/Oleksandr Raspopov/lesson_36_http/les36_tsk3_weather.py | les36_tsk3_weather.py | py | 1,520 | python | en | code | null | github-code | 13 |
24846814594 | from random import Random
import numpy as np
import pandas as pd
def split_dataset(data, val_perc=0.2):
val_size = int(len(data) * val_perc)
TR, TS = data[:-val_size], data[-val_size:]
features = 1 if len(data.shape) == 1 else data.shape[-1]
return \
TR[:-1].reshape(-1, features), \
T... | GeremiaPompei/esn | src/dataloader/dataloader.py | dataloader.py | py | 1,320 | python | en | code | 0 | github-code | 13 |
69975976019 | """
const int ARRAY_SIZE = 10;
int intArray[ARRAY_SIZE] = {87, 28, 100, 78, 84, 98, 75, 70, 81, 68};
int start = 0;
int end = ARRAY_SIZE - 1;
for (int i = start + 1; i <= end; i++) {
for (int j = i; j > start && intArray[j-1] > intArray[j]; j--) {
int temp = intArray[j-1];
intArray[j-1] = intArray[... | chicocheco/tlp-python | insertion-sort.py | insertion-sort.py | py | 1,654 | python | en | code | 0 | github-code | 13 |
40980097668 | from django.urls import path
from .views import List_medico, Update_medico, Create_medico
url_patterns = [
path('', List_medico, name='list_medico'),
path('new', Create_medico, name='create_medico'),
path('Update', Update_medico, name='update_medico'),
]
#Crude de médicos | Pachequim/MedicalSys | MedicalSys/main/projeto/urls.py | urls.py | py | 288 | python | pt | code | 0 | github-code | 13 |
16914609932 | #!/usr/bin/python
import os
import argparse as ap
from mailman.interfaces.messages import IMessageStore
from github3 import login
def main():
description = """Turn a mailing list discussion into a Github issue"""
parser = ap.ArgumentParser(description=description)
disc = 'the url of the list discussion... | gidden/list2issue | list2issue.py | list2issue.py | py | 677 | python | en | code | 0 | github-code | 13 |
73685125777 | import sys, io
from PIL import Image
def convert_to_png(infile):
im = Image.open(infile)
xsize, ysize = im.size
size = xsize if xsize > ysize else ysize
im_res = Image.new('RGBA', (size, size), (255, 255, 255, 0))
im_res.paste(im, (int((size-xsize)/2), int((size-ysize)/2) ))
if xsize ... | Graftiger/Lab4_XLA | ImageToSticker_converter/src/ToPng.py | ToPng.py | py | 755 | python | en | code | 0 | github-code | 13 |
6396271465 | '''
WAP to sort the given URLs based on their frequency.
When two or more URLs have same frequency count then print the lexicographically smaller URL first.
'''
from collections import Counter
from collections import OrderedDict
url_list = list(input("Enter URL: ").split())
frequency = Counter(url_list)
... | miral25/SIMPLE-PYTHON-PROGRAM | PYTHON SIMPLE PROGRAM/45.py | 45.py | py | 562 | python | en | code | 0 | github-code | 13 |
38258474111 | # find best model
import numpy as np
import tensorflow as tf
import autokeras as ak
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train[:6000].reshape(-1, 28, 28, 1)/255.
x_test = x_test[:1000].reshape(-1, 28, 28, 1)/255.
y_train = y_train[:6000]
y_... | dongjaeseo/study | keras3/keras105_ak_best_model.py | keras105_ak_best_model.py | py | 1,107 | python | en | code | 2 | github-code | 13 |
30141748620 | from tkinter import * # Импорт библиотеки для создания графического интерфейса
import random # подключение модуля случайных чисел random
import Task_One
import Task_Two
import Task_Three
# Создание графического интерфейса
# Создаем окно
root = Tk()
root.title("Лабораторная работа 1")
root.geometry('720x480')
theLab... | xtrdnrmnd/python_practice_2 | Main.py | Main.py | py | 7,561 | python | ru | code | 0 | github-code | 13 |
29746689844 | from datetime import datetime
from . import lib
class CenteredTextWidget(lib.CenterWidgetMixin, lib.TextWidget):
def __init__(self, **kwargs):
super(CenteredTextWidget, self).__init__(**kwargs)
class TimeWidget(CenteredTextWidget):
@property
def text(self):
return datetime.now().strft... | insertjokehere/ntpbox-display | ntpbox_display/widgets.py | widgets.py | py | 1,096 | python | en | code | 0 | github-code | 13 |
9616803935 | # %%
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import scipy
from scipy import ndimage
from sklearn.decomposition import PCA
from augumentation import ima... | teruko9126/ML-ubuntu | augumentation/main.py | main.py | py | 11,213 | python | en | code | 0 | github-code | 13 |
20774679041 | class LR:
def __init__(self, g):
self.g = g
def goto(self, s, symbol):
# s = [(S0, .S), (S, .aA)]
if (symbol not in self.g.E) and (symbol not in self.g.N) and (symbol != self.g.S):
raise ValueError("Symbol " + symbol + " is neither a terminal nor a nonterminal")
res... | alexandra-murariu/FLCD | lab2+scanner/parser/LR.py | LR.py | py | 2,031 | python | en | code | 0 | github-code | 13 |
34607272555 | import logging
import random
from django.http import HttpResponse
from testapp.models import EagleTails
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
filename="log/testapp.log",
filemode="a",
format="%(levelname)s %(message)s",
)
def testapp(request):
logger.info("... | e6ton1set/specialization | django/seminars/project1/testapp/views.py | views.py | py | 718 | python | en | code | 0 | github-code | 13 |
1333634784 | from urllib.parse import urljoin
from django.conf import settings
from django.urls import reverse
from templated_email import send_templated_mail
def send_battle_result(battle):
battle_detail_path = reverse("battles:battle-detail", args=(battle.pk,))
battle_details_url = urljoin(settings.HOST, battle_detail... | gabrielaleal/pokebattle | backend/battles/utils/email.py | email.py | py | 2,149 | python | en | code | 1 | github-code | 13 |
1838378502 | import collections
import functools
import numbers
import os
def coroutine(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
generator = function(*args, **kwargs)
next(generator)
return generator
return wrapper
@coroutine
def sender(receiver=None, maximum=None):... | DanyR2001/Codice-Percorso-Universitario | Terzo anno/Programmazione Avanzata/Primi esercizi/ripasso/Esercizio 6-12-2022/Es1.py | Es1.py | py | 3,581 | python | it | code | 0 | github-code | 13 |
35012222378 | import os
import csv
import sqlite3
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
################################################
... | JGelotin/klm-editor | klmeditor/MainWindow.py | MainWindow.py | py | 19,752 | python | en | code | 1 | github-code | 13 |
26739942345 | import pandas as pd
import numpy as np
import os
import xlsxwriter
from Retrieve_emails import *
import shutil
from datetime import datetime
import statistics
import matplotlib
import matplotlib.pyplot as plt
from io import BytesIO
import sys
year = str(input("Enter year:"))
# year = '2020'
path = os.path.abspath(o... | andreac0/Annual-Report-Statistics | reporting_stats.py | reporting_stats.py | py | 7,373 | python | en | code | 0 | github-code | 13 |
15171613582 | from datetime import date, timedelta, datetime, time
from sqlalchemy.sql.expression import text
from sqlalchemy import create_engine
import os
from util import config, logger, only_allow_one_instance
triggers_sql = text("""
SELECT
id,
from_host_trigger,
sys_log_tag_trigger,
message_trigger
FROM
`... | systemconsole/syco-signer | signer/signer_trigger_delete.py | signer_trigger_delete.py | py | 2,438 | python | en | code | 0 | github-code | 13 |
21570779167 | """Show the homepage."""
import os
import uuid
import copy
import flask
import equations
from equations.data import rooms_info, user_info, MapsLock
from equations.models import Game
@equations.app.route("/favicon.ico")
def show_favicon():
"""Deliver the favicon asset."""
return flask.send_from_directory(os.p... | tonyb7/equations | equations/views/index.py | index.py | py | 6,150 | python | en | code | 0 | github-code | 13 |
41910143735 | #!/usr/bin/python3
#
# Part of RedELK
#
# Authors:
# - Outflank B.V. / Mark Bergman (@xychix)
# - Lorenzo Bernardi (@fastlorenzo)
#
from modules.helpers import *
from config import interval, alarms
from iocsources import ioc_vt as vt
from iocsources import ioc_ibm as ibm
from iocsources import ioc_hybridanalysis as ha
... | qx-775/redelk | elkserver/docker/redelk-base/redelkinstalldata/scripts/modules/alarm_filehash/module.py | module.py | py | 8,144 | python | en | code | 1 | github-code | 13 |
14322784088 | # Standard libs
import datetime, os, sqlite3
class Database():
"""
Class representing the database and its methods to interact with it.
"""
def __init__(self):
# Checking if the DB already exists; if not, create the schema
if not os.path.exists("data/boomerang.sqlite3"):
sel... | Ailothaen/boomerang | models.py | models.py | py | 6,420 | python | en | code | 1 | github-code | 13 |
16867454231 | import socket
import sys
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
message = 'This is the message. It will be repeated.'
try:
# Send data
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, server_address)
... | utra-robosoccer/soccer-embedded | Development/Ethernet/f7ethtut/chuck_data.py | chuck_data.py | py | 541 | python | en | code | 32 | github-code | 13 |
40787810982 | vals = {}
for line in open('Day 05.input'):
x0, y0, x1, y1 = [int(c) for p in line.split(' -> ') for c in p.split(',')]
if x0 == x1:
for i in range(min(y0, y1), max(y0, y1)+1):
vals[x0, i] = vals.get((x0, i), 0) + 1
elif y0 == y1:
for i in range(min(x0, x1), max(x0, x1)+1):
... | Mraedis/AoC2021 | Day 05/Day 05.1.py | Day 05.1.py | py | 408 | python | en | code | 1 | github-code | 13 |
42257091778 | import trainer, Course, student, assigment, Student_per_course, Trainer_per_course, Assignments_per_course, Assignments_per_student
trainer_list = trainer.Trainer_records()
assigment_list = assigment.assigment_record()
course_list = Course.Course_records()
student_list = student.Student_records()
# course menu!
def c... | tatoulis/CRUD_python_term_menu | crud_term_menu/origin.py | origin.py | py | 8,684 | python | en | code | 0 | github-code | 13 |
14819758793 | import os
import subprocess
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.requests import Request
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# from gradio_client imp... | Myangsun/Streetview-app | backend/app/api.py | api.py | py | 1,746 | python | en | code | 0 | github-code | 13 |
23966520169 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
tick_interval = 0
stop_count = 0
win_count = 0
stopwatch_running = False
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
tenths = t % 10
t = t // 10
seco... | segolily04/Intro_to_Interactive_Programming_With_Python | stopwatch_mini_project_4.py | stopwatch_mini_project_4.py | py | 1,804 | python | en | code | 0 | github-code | 13 |
41619179886 | import pygame
from settings import *
from button import Button
class UI:
def __init__(self, surface) -> None:
#setup
self.display_surface = surface
#health
self.health_bar = pygame.image.load(".//JUEGO 2//graphics//ui//health_bar.png").convert_alpha()
self.h... | AgustinSande/sandeAgustin-pygame-tp-final | codefiles/ui.py | ui.py | py | 3,077 | python | en | code | 0 | github-code | 13 |
44464470701 | #!/usr/bin/env python3
import itertools
import json
import neptune
import yaml
from transformer import *
from reader import *
def load_list_of_params(path):
with open(path, 'r') as f:
obj = json.load(f)
return obj['parameters'], obj['items']
def load_params(path):
""" Get input for paramete... | pixelneo/dialogue-transformer-e2e | implementation/tf/runner.py | runner.py | py | 2,179 | python | en | code | 5 | github-code | 13 |
22853548802 | import sys
import random
DEBUG = True # False when you submit to kattis
# function which queries the next set of neighbors from kattis
if DEBUG:
N = 21000000 # the number of nodes
eps = 0.1 # desired accuracy
maxWeight = 3 # largest weight in our graph
# we will simulate a graph that is just one large c... | pedroggbcampos/ADA-proj | src/spanningforest-example.py | spanningforest-example.py | py | 2,242 | python | en | code | 1 | github-code | 13 |
22738478576 |
from keras.preprocessing.sequence import pad_sequences as pad
def tokenize(
dataset,
sent,
anno,
):
tokenized_sent = []
tokenized_anno = []
for i, word in enumerate(sent):
tokenized_word = dataset.tokenizer.convert_tokens_to_ids(dataset.tokenizer.tokenize(word))
tokenized_s... | trungtv/COVID-19-Named-Entity-Recognition-for-Vietnamese | source/utils/preprocessing.py | preprocessing.py | py | 1,351 | python | en | code | 0 | github-code | 13 |
39807063985 | import io
from django.test import TestCase
import unittest
from django.utils import timezone
from model_mommy import mommy
from rest_framework.test import APIClient
from api.models import MusicalWork
from api.reconcile import get_iswc_index, obj_params_count, perform_each_line
# These are unit tests no db operation... | bishnusyangja/single_view | app/api/tests.py | tests.py | py | 4,651 | python | en | code | 0 | github-code | 13 |
72778108498 | '''
Created on 2013-6-7
@author: Yubin Bai
'''
if __name__ == '__main__':
N = 1000000
sieve = [True] * (N + 1)
sieve[0] = sieve[1] = False
results = []
for i in range(2, N):
if sieve[i] == True:
results.append(i)
for j in range(i * 2, N, i):
sieve[j]... | yubinbai/Codejam | round1B 2008/numberSet/prototype.py | prototype.py | py | 352 | python | en | code | 8 | github-code | 13 |
7784924696 | """Univercidad interamericana de Panama
Sistemas de encuestas
Proyecto Final de Programacion de Computadoras 4
Integrantes:
Omar Gonzalez
Franklin Vanegas
Vladimir Batista
Grimaldo Castro
"""
from flask import Flask, flash, url_for, redirect, render_template, request
from flask_sqlalchemy import SQLAlchemy
app ... | grimaldom/Mini-encuestas | __init__.py | __init__.py | py | 3,424 | python | es | code | 0 | github-code | 13 |
70852488018 | from aocd import data, submit
for line in data.splitlines():
line = line.strip()
sum1 = 0
sum2 = 0
for i in range(len(line)):
if line[i] == line[(i + 1) % len(line)]:
sum1 += int(line[i])
if line[i] == line[(i + int(len(line) / 2)) % len(line)]:
sum2 += int(line[... | charvey/advent-of-code | 2017/01.py | 01.py | py | 378 | python | en | code | 0 | github-code | 13 |
39576625133 | class Solution:
def largestWordCount(self, messages: List[str], senders: List[str]) -> str:
my_dict = {}
for _ in range(len(senders)):
if senders[_] in my_dict.keys():
my_dict[senders[_]] += len(messages[_].split())
else:
my_dict[senders[_]] = ... | KillerStrike17/CP-Journey | LeetCode/BiWeekly Contest/Contest 79/2284.py | 2284.py | py | 688 | python | en | code | 0 | github-code | 13 |
74970636818 | from typing import Tuple
from typing import List
from typing import Optional
from typing import Dict
from typing import Union
import pandas as pd
import geopandas as gpd
from osmgt.helpers.logger import Logger
from osmgt.apis.nominatim import NominatimApi
from osmgt.apis.overpass import OverpassApi
from osmgt.helpe... | amauryval/OsmGT | osmgt/compoments/core.py | core.py | py | 8,212 | python | en | code | 4 | github-code | 13 |
21793578416 | import unittest
from modules.csv_to_db import DataBase
class MyTestCase(unittest.TestCase):
def setUp(self):
self.db = DataBase("../data/first9000.db")
self.austria = self.db.execute_selection_by_country("Austria")
self.france = self.db.execute_selection_by_country("France")
def test... | 8bit-number/coursework-project | tests/csv_to_db_test.py | csv_to_db_test.py | py | 1,202 | python | en | code | 0 | github-code | 13 |
22283779806 | """
How do you find all pairs of an integer array whose sum is equal to a given number
"""
def printpairs(arr,arr_size,sum):
s = set()
for i in range(0,arr_size):
temp = sum -arr[i]
if (temp in s):
print('Pair with given sum '+str(sum)+" is : ("+str(arr[i])+','+str(temp)+")")
... | zac11/algorithms-in-diff_lang | Python/pair_matching_give_sum.py | pair_matching_give_sum.py | py | 519 | python | en | code | 0 | github-code | 13 |
123175327 | import os
import re
from typing import Dict, List, Union # for type hinting
from db import db
from datetime import datetime
from sqlalchemy.sql import (
func,
) # 'sqlalchemy' is being installed together with 'flask-sqlalchemy'
from services.models.pairs import PairModel
from services.models.tickers import Ticke... | ozdemirozcelik/pairs-api | services/models/signals.py | signals.py | py | 33,255 | python | en | code | 9 | github-code | 13 |
35933055105 | import pygame
###########################################################(반드시 필요)
pygame.init() #처음 초기화 하는 기능
#화면 크기 설정
screen_width= 480
screen_height = 640
screen = pygame.display.set_mode((screen_width,screen_height)) #실제로 적용됨
#화면 타이틀 설정
pygame.display.set_caption("Nado Game") #게임 이름 설정
# FPS
clock... | zookeeper464/py_game_ex | game.py | game.py | py | 6,384 | python | ko | code | 0 | github-code | 13 |
10173308345 | import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from math import sqrt
def mse_(y, y_hat):
"""
Description:
Calculate the MSE between the predicted output and the real output.
Args:
y: has to be a numpy.array, a vector of dimension m * 1.
y_hat: has to be a numpy.... | jmcheon/ml_module | 00/ex09/other_losses.py | other_losses.py | py | 5,110 | python | en | code | 0 | github-code | 13 |
73498084497 | import os, re, json
from flask import Flask
from datetime import datetime
app = Flask(__name__)
def read_data():
with open('./data.json') as json_file:
json_data = json.load(json_file)
return json_data
def write_data(data):
with open('./resume.tex', "wb+") as f:
f.write(data)
f.cl... | xuchen81/XNemo | generate_pdf.py | generate_pdf.py | py | 2,103 | python | en | code | 0 | github-code | 13 |
8842716085 | ## Modules
import numpy as np
import math as m
import matplotlib.pyplot as plt
## Part imports
import TeamProject_Part1 as p1
import TeamProject_Part2 as p2
import TeamProject_Part3 as p3
## UDFs
# Main function
def gkern(sig, x, y):
gauss = (1 / (2 * m.pi * m.pow(sig,2)))
gauss *= m.exp(... | AviDube/Engr133Docs | TeamProject.py | TeamProject.py | py | 2,590 | python | en | code | 0 | github-code | 13 |
70971937938 | from flask import render_template
from project import app, db
from project.routes import dictionaryOfProjects
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html',
the_title='404',
dictionaryOfProjects=dictionaryOfProjects), 404... | GlennMiller1991/PythonPortfolio | project/errors.py | errors.py | py | 584 | python | en | code | 0 | github-code | 13 |
22906240614 | from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
class Venue(models.Model):
foursquare_id = models.CharField(
max_length=64, unique=True
)
name = models.CharField(max_length=256)
location = models.PointField()
categories = models.ManyToManyField(
'... | gareth-lloyd/python-geodata-talk | api/venues/models.py | models.py | py | 2,898 | python | en | code | 3 | github-code | 13 |
29041939538 | import collections
# time complexity: n
# space complexity: n
def two_sum(array):
visited = collections.defaultdict(lambda:-1)
for i in range(len(array)):
nextValue = array[i]
if -nextValue in visited.keys():
return "{} {}".format(visited[-nextValue]+1, i+1)
else:
... | egavett/CS473Algorithms | 2Sum/rosalind_2sum.py | rosalind_2sum.py | py | 772 | python | en | code | 0 | github-code | 13 |
6482114659 | import cv2
import os
import runlength
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from sklearn.svm import SVR, LinearSVR
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, Grad... | mfkaradeniz/astronomy-compression | src/compression_with_linear_models.py | compression_with_linear_models.py | py | 9,174 | python | en | code | 0 | github-code | 13 |
74614901456 | import cv2
import numpy as np
from RiskMapRegion import RiskMapRegion
def func(x):
return (-x.risk, -x.area)
def getWatershed(data, w):
height = np.array(data)
image = np.zeros(height.shape)
for i in range(len(data)):
for j in range(len(data[0])):
height[i][j] = data[i][j].elevatio... | yhgupta/Flood_Rescue | watershed.py | watershed.py | py | 8,010 | python | en | code | 0 | github-code | 13 |
17047781074 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AntMerchantExpandProductionOrderSyncModel(object):
def __init__(self):
self._amount = None
self._batch_no = None
self._item_id = None
self._project_no = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AntMerchantExpandProductionOrderSyncModel.py | AntMerchantExpandProductionOrderSyncModel.py | py | 3,344 | python | en | code | 241 | github-code | 13 |
32227445689 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 06 11:01:57 2018
@author: deepe
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('affairs.csv')
features = dataset.iloc[:,:-1].values
labels = dataset.iloc[:,-1].values
from sklearn.preprocessing import LabelEncoder,OneHot... | sherwaldeepesh/Forsk-Python_Machine_Learning | Day 19/code1.py | code1.py | py | 1,353 | python | en | code | 1 | github-code | 13 |
40336485475 | from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
from time import sleep
from time import time
from utils.evaluations import do_roc, save_results
class BIGANTrainer(BaseTrain):
def __init__(self, sess, model, data, config, summarizer):
super(BIGANTrainer, self).__init__(sess, ... | yigitozgumus/Polimi_Thesis | trainers/bigan_trainer.py | bigan_trainer.py | py | 12,797 | python | en | code | 5 | github-code | 13 |
38167691902 | #!/usr/bin/python
# -*- coding:utf-8 -*-
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open(fp="niuniu.jpg")
# 输出图片属性
print('format:', img.format, '\n', 'size:', img.size, '\n', 'mode:', img.mode)
# 分割 RGB 通道
r, g, b = Image.Image.split(img)
image = [img, r, g, b]
fig = plt.figure(figs... | Funail/webdriver | python_study/test16.py | test16.py | py | 913 | python | zh | code | 0 | github-code | 13 |
27208537651 | from rest_framework.decorators import api_view, permission_classes
from rest_framework.request import Request
from rest_framework.response import Response
from leaderboard.models import UserStats, UserStatsSummary
from rest_framework import status
from main.models import Country
from rest_framework.permissions import I... | PBP-E-03/proyek-tengah-semester | leaderboard/views.py | views.py | py | 3,909 | python | en | code | 0 | github-code | 13 |
39947264182 | import io
import typing
import socket
def as_bytes(s: str) -> bytes:
return s.encode('utf-8')
def from_bytes(b: bytes) -> str:
return b.decode('utf-8')
def annotate(src: typing.Any, *ansi_escape_codes: int) -> str:
length: int = len(ansi_escape_codes)
if length == 0:
return str(src)
... | jtmr05/spln-2223 | TP2/utils.py | utils.py | py | 1,174 | python | en | code | 0 | github-code | 13 |
32507202912 | import psycopg2
from pprint import pprint
def create_db(cur):
'''Создание таблиц клиентов и телефонов'''
cur.execute("""
CREATE TABLE IF NOT EXISTS client(
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
surname VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
PRIMARY KEY("id" ... | s-evg/netology_SQLPY | hm_5/main.py | main.py | py | 7,862 | python | ru | code | 0 | github-code | 13 |
43085210862 | #
# @lc app=leetcode.cn id=83 lang=python3
#
# [83] 删除排序链表中的重复元素
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
... | Guo-xuejian/leetcode-practice | 83.删除排序链表中的重复元素.py | 83.删除排序链表中的重复元素.py | py | 679 | python | en | code | 1 | github-code | 13 |
71995469459 | import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('covid_19_data.csv')
daily_country_cases = data.groupby(
['ObservationDate', 'Country/Region'])['Confirmed'].sum().reset_index()
countries_of_interest = ['China', 'Italy', 'United States', 'India']
plt.figure(figsize=(10, 6))
for country... | tyron200/capstone | comparative.py | comparative.py | py | 728 | python | en | code | 0 | github-code | 13 |
14042408077 | import logging
import os
import sys
from transformers import AutoConfig, AutoTokenizer
from transformers import (
HfArgumentParser,
set_seed,
)
from arguments import ModelArguments, DataArguments, BiEncoderTrainingArguments
from dataloader import BiEncoderDataset, BiEncoderCollator, GenericDataLoader, NoisyBi... | Fantabulous-J/BootSwitch | train_crop_sent.py | train_crop_sent.py | py | 4,513 | python | en | code | 0 | github-code | 13 |
7553329038 |
from numpy import random
import pandas as pd
Age=[]
height=[]
weight=[]
BMI=[] #body math index
Gender=[]
athlete=[]
smoker=[]
AnotherChronicIllness=[]
riskGroup=[] # if 0 there is no risk-------- if 1 there is medium risk----- if 2 there is high risk
Sex=["Male","Female"]
YesNo=["Yes","No"]
for i in range(20000):... | kutayAlaaeddin/Covid19_risk_group_classification | CreateDataset.py | CreateDataset.py | py | 2,218 | python | en | code | 0 | github-code | 13 |
36052585149 | # build a neural network that classifies images
# 1. Build a neural network that classifies images
# 2. Train the neural network
# 3. And, finally, evaluate the accuracy of the model
# import libraries
import tensorflow as tf
# load data
def loadData():
mnist = tf.keras.datasets.mnist
(xTrain, yTrain), (xTes... | SanchitJain123/ML-Implementations | Basics/TFBasics.py | TFBasics.py | py | 1,270 | python | en | code | 0 | github-code | 13 |
22790201993 | from typing import List, Sequence
import dezero as dz
from dezero import functions as F
from dezero import layers as L
from dezero import utils
class Model(dz.Layer):
def plot(self, *inputs: dz.Variable, to_file='model.png'):
y = self.forward(*inputs)
return utils.plot_dot_graph(
y, ve... | teijeong/deeplearning-from-scratch | dezero/models.py | models.py | py | 921 | python | en | code | 0 | github-code | 13 |
7390476439 | from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class User(AbstractUser):
def serialize(self):
return {
"id": self.id,
}
class Quiz(models.Model):
owner = models.ForeignKey("User", on_delete=models.CASCADE, related_n... | wallace9320/CS50W-Project | quiz/models.py | models.py | py | 1,558 | python | en | code | 0 | github-code | 13 |
1954949464 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 20:30:52 2021
Problem 57: Square root convergents
https://projecteuler.net/problem=57
@author: kuba
"""
import time
def solution():
# Main score
score = 0
# [[x,y]] where x - numerator, y - denominator
list_of_number = [[3, 2], [7, 5]]
# Main l... | KubiakJakub01/ProjectEuler | src/Problem57.py | Problem57.py | py | 790 | python | en | code | 0 | github-code | 13 |
71979272659 | #!/usr/bin/env python
#CHRIS SEQUEIRA CAS8903
import socket
#prints output for each iteration may be more than 2-3 000 character
for i in range (1000,3000):
ip = "172.16.237.128"
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(5)
s.connect((ip, 9999))
s.recv(2048)
badstr = "A"*i
... | apotheosik/SvrExploits | VulnServer/VulnServerFuzzer.py | VulnServerFuzzer.py | py | 949 | python | en | code | 1 | github-code | 13 |
30803286868 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(1)
print('Loading train and test data...')
df1=pd.read_csv('exoTrain.csv')
#print(df1)
df2=pd.read_csv('exoTest.csv')
#print(df2)
"""
In the traning data, We have light intensites of stars measured at 3198 time instances.
The t... | anandnwarrier/Exoplane_host_star_detection | exoplanet_prediction_using_RNN_with_fourier_transformed_data.py | exoplanet_prediction_using_RNN_with_fourier_transformed_data.py | py | 6,509 | python | en | code | 0 | github-code | 13 |
42148539511 | animals = input('Heyvanlari girin: ').split(', ')
prices = { 'inek': 500, 'toyuq': 50, 'qoyun': 120, 'at': 900, 'keci': 210 }
try:
if not 3<len(animals)<10:
raise ValueError('3-den cox ve 10-dan az sayda heyvan yazmalisiniz')
print('Umumi qiymet:', sum(map(lambda animal: prices[animal], animals)))
exc... | elminazmirzelizade/python | homework33/index.py | index.py | py | 520 | python | tr | code | 0 | github-code | 13 |
40783940072 | def has_double(num):
digits = [char for char in str(num)]
last = digits[0]
last2 = digits[1]
dubs = last == last2
trips = False
hasdubs = False
for digit in digits[2:]:
if digit == last2:
trips = dubs
dubs = True
else:
if dubs and not trips:
hasdubs = True
dubs = digi... | Mraedis/AoC2019 | Day4.2.py | Day4.2.py | py | 754 | python | en | code | 0 | github-code | 13 |
31283683405 | import jsonpath
import requests
import json
from comm.write_log import log
'''
获取魔镜token
验证码获取
↓
验证码图像识别
↓
token获取
'''
def get_token():
# 获取验证码图像识别后的结果, 预期为4个字符
url = "http://localhost:8081/"
captcha = ""
while len(captcha) != 4:
response = requests.request("GET", url, data=... | storeview/LEARN__HTTP-Interface-Automate-Test | task1/comm/get_token.py | get_token.py | py | 1,144 | python | en | code | 0 | github-code | 13 |
34527274449 | import time
from ui import read_input, print_output, should_exit
from solver import GreedySolver
while True:
input = read_input()
greedy_solver = GreedySolver(input)
start = time.perf_counter()
result = greedy_solver.solve()
end = time.perf_counter()
print_output(result, start, end)
if ... | martinbudinsky3/N-puzzle-greedy-solver | n_puzzle_greedy_algo.py | n_puzzle_greedy_algo.py | py | 349 | python | en | code | 0 | github-code | 13 |
22137785429 | import Augmentor
from invoke import run
from PIL import Image
from random import randint
import glob
import os
def augmentor():
WrinklePath="./Wrinkle_templates"
p = Augmentor.Pipeline(WrinklePath)
p.rotate(probability=1, max_left_rotation=20, max_right_rotation=20)
p.process()
p = Augmentor.Pip... | AbtinDjavadifar/SimpleNet | Augmentor/utils.py | utils.py | py | 7,030 | python | en | code | 2 | github-code | 13 |
40640210681 | #!/usr/bin/env python3
"""
Given a rasterized DEM in Cartesian coordinates (e.g., UTM),
compute the slope and slope-aspect maps.
The DEM should be provided as a gdal-readable file, preferably
in GeoTiff format.
"""
### IMPORT MODULES ---
import numpy as np
import matplotlib.pyplot as plt
from osgeo import gdal... | EJFielding/InsarToolkit | SlopeAnalysis/ComputeTopoVectors.py | ComputeTopoVectors.py | py | 5,434 | python | en | code | 4 | github-code | 13 |
1375913621 | from classes import DBManager, HH
import utils as ut
data = DBManager()
hh_agent = HH()
user_input = None
print(f'Перед вами программа для работы с базой данных PostgreSQL.\n'
f'После подтверждения, будет созданна база данных вакансий компаний, id которых хранятся'
f' в файле ./data/selected_employers_id... | perf-il/vacancy-analysis | main.py | main.py | py | 4,158 | python | ru | code | 0 | github-code | 13 |
25106620173 | import pytest
from subprocess import check_output, check_call
from os.path import dirname, join
import json
@pytest.mark.usefixtures('sim_hocr_file')
def test_split_combine_plaintext(sim_hocr_file):
sim_hocr_file = str(sim_hocr_file)
basedir = dirname(sim_hocr_file)
split_pages = join(basedir, 'split-%0... | internetarchive/archive-hocr-tools | tests/test_hocr_split_recombine.py | test_hocr_split_recombine.py | py | 837 | python | en | code | 24 | github-code | 13 |
22224137314 | import base64
import time
import requests
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
def rsa_decode(data):
key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsgDq4OqxuEisnk2F0EJFmw4xKa5IrcqEYHvqxPs2CHEg2kolhfWA2SjNuGAHxyDDE5MLtOvzuXjBx/5YJtc9zj2xR/0moesS+Vi/xtG1tkVaTCba+TV+Y5C61iyr3FGq... | qifiqi/codebase | python_codebase/爬虫/爬虫逆向进阶实战-案例/login_10086_cn.py | login_10086_cn.py | py | 4,718 | python | en | code | 3 | github-code | 13 |
13103767544 | # https://school.programmers.co.kr/learn/courses/30/lessons/84512
def solution(word):
dict = {
'A': 0,
'E': 1,
'I': 2,
'O': 3,
'U': 4
}
answer = 0
mul = 1
word_len = len(word)
for i in range(1, 6):
if word_len > 5-i:
answer +... | olwooz/algorithm-practice | practice/2022_12/221208_Programmers_VowelDict/221208_Programmers_VowelDict.py | 221208_Programmers_VowelDict.py | py | 404 | python | en | code | 0 | github-code | 13 |
15304098669 | """ Tower of Hanoi Interactive
"""
import sys
N = 3
towers = {
'A': list(reversed(range(1, N + 1))),
'B': [],
'C': []}
def move(start, end):
disk = towers[start].pop()
towers[end].append(disk)
def show_board():
rows = []
for key, values in towers.items():
rows.append('[' + ''.join... | minte9/algorithms-pages | practice/tower_of_hanoi/tower_of_hanoi2_play.py | tower_of_hanoi2_play.py | py | 1,247 | python | en | code | 0 | github-code | 13 |
20296055415 | #!/usr/bin/env python
from copy import copy
import game_assets
from utils import get_logger
from string import capwords
class Model:
""" This is the base class for all model classes. It provides the basic
methods that all model objects (e.g. Innovations, Resources, etc.) have to
support."""
def __ini... | chummer5a/kdm-manager | v1/models.py | models.py | py | 23,466 | python | en | code | null | github-code | 13 |
70270411857 | '''
calc.py Version: 1.0 by Affe_130
Important:
This program should be runned in a console with the py command!
Help:
Modes: -add, -sub, -mul, -div, -exp, -root, -stat, Example: py calc.py -add 1 2 3
'''
import sys
arg = sys.argv
values = []
for i in range(2, len(arg)): #Adds all values in the argument list to... | Affe130/Calculator | calc.py | calc.py | py | 2,387 | python | en | code | 0 | github-code | 13 |
5232720034 | '''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 1B of Niriksha... | serenaraju/Pragmatic-Implementation-Reinforcement-Learning-Path-Planning-Raspberry-Pi-Bot | task_1b_detect_and_encode_maze/task_1b.py | task_1b.py | py | 12,704 | python | en | code | 1 | github-code | 13 |
15428823317 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0002_movimentodeestoque'),
]
operations = [
migrations.CreateModel(
name='Compras',
fields=[
('id', models.BigAutoField(auto_created=True, pri... | CarolPera/OPE-Vulcano | app/migrations/0003_compras_vendas.py | 0003_compras_vendas.py | py | 1,086 | python | en | code | 2 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.