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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33962354417 | import numpy as np
from sklearn.linear_model import LogisticRegression
from random import randrange
from math import ceil, floor
# Загрузка данных из текстового файла
data = np.genfromtxt('данные двумерная модель.txt', skip_header=1) # Пропустить первую строку с названиями столбцов
# Разделение данных на факторы (x)... | IlnazMmm/RKA | 3 lab/prog2.py | prog2.py | py | 1,708 | python | ru | code | 0 | github-code | 6 |
72742546747 | # -*- coding: utf-8 -*-
# @Author : yxn
# @Date : 2022/1/27 20:46
# @IDE : PyCharm(2021.3.1) Python3.98
def toStr(n, base):
"""递归实现"""
converSting = "0123456789ABCDEF"
if n < base:
return converSting[n]
else:
return toStr(n // base, base) + converSting[n % base]
if __name... | yxn4065/Data-structure-and-algorithm-Python- | 13_递归-转换任意进制.py | 13_递归-转换任意进制.py | py | 468 | python | en | code | 0 | github-code | 6 |
6253113584 | import torch
import torch.nn as nn
import torch.nn.functional as F
from _polytope_ import Polytope, Face
import utilities as utils
from collections import OrderedDict
import numpy as np
import time
import copy
import convex_adversarial.convex_adversarial as ca
import full_lp as flp
class PLNN(nn.Module):
#TODO: ... | revbucket/geometric-certificates | plnn.py | plnn.py | py | 29,208 | python | en | code | 40 | github-code | 6 |
71645960508 | from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name="index"),
path('detalhes/<int:pk>/<slug:slug>', views.detail, name="details"),
path('post/novo/', views.post, name="new_post"),
path('editar/post/<int:pk>', views.edit, name="edit"),
path... | eduardoferreira97/Blog | blog/urls.py | urls.py | py | 553 | python | en | code | 1 | github-code | 6 |
43371048993 | import pygame
from pygame.locals import KEYDOWN, K_ESCAPE, QUIT
from os import path
import parameters.enums as en
from Objects.player import Player, Wall
from Objects.map import Map
from Objects.robot import Robot
import numpy as np
from Objects.machinery import Machinery, Destiny
import sys
import torch
from Objects.u... | anfego22/rele | main.py | main.py | py | 3,394 | python | en | code | 0 | github-code | 6 |
74479990587 | import json
from random import uniform
import matplotlib.pyplot as plt
class Scanner:
def __init__(self, data_filename, n_neighbours):
self.data_filename = data_filename
self.n_neighbours = n_neighbours
def scanner(self, visualize_data=False):
f = open(self.data_filename, encoding="u... | SergeyBurik/profitable_apartments_parser | profitable_apartments_parser/scanner/scanner.py | scanner.py | py | 2,832 | python | en | code | 0 | github-code | 6 |
44531751826 | from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns, data = [], []
columns=get_columns()
data=get_data(filters,columns)
return columns, data
def get_columns():
return [
{
"label": _("Loan"),
"fieldname": "name",
"fieldtype": "Link",
"options... | erpcloudsystems/ecs_bank_loans | ecs_bank_loans/ecs_bank_loans/report/bank_loan_report/bank_loan_report.py | bank_loan_report.py | py | 5,926 | python | en | code | 0 | github-code | 6 |
36848412423 | import hashlib
import random
import sqlite3
from typing import List, Optional
import more_itertools
import numpy as np
import pandas as pd
import scipy.spatial
import skimage.transform
from carla_real_traffic_scenarios import DT
from carla_real_traffic_scenarios.ngsim import DatasetMode
from carla_real_traffic_scenar... | deepsense-ai/carla-real-traffic-scenarios | carla_real_traffic_scenarios/opendd/recording.py | recording.py | py | 13,416 | python | en | code | 67 | github-code | 6 |
35539138268 | from django.http import JsonResponse
from .models import Task
def _get_all_tasks():
task_objects = Task.objects.all()[:30]
tasks = []
for task_obj in task_objects:
task = task_obj.get_as_dict()
tasks.append(task)
return tasks
def index(request):
if request.method == 'GET':
... | bluepostit/django-js-todo | todos/views.py | views.py | py | 2,483 | python | en | code | 0 | github-code | 6 |
16373544563 | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense , Dropout , Lambda, Flatten
from keras.optimizers import Adam ,RMSprop
from sklearn.model_selection impo... | nicogab34/MNIST--Neural-Networks | augment_data.py | augment_data.py | py | 9,196 | python | en | code | 0 | github-code | 6 |
10900131686 | from flask import Flask
from flask import Flask, request, render_template, send_file
app = Flask(__name__)
@app.route('/cookiestealer/', methods=['GET'])
def cookieStealer():
filename = 'cookiemonster.jpg'
print("This is the cookie: \n")
print(request.cookies)
print("")
return send_file(f... | FelixDryselius/SecureDataSystemsGroup17 | lab1/xss/3rd_party_cookie_stealer.py | 3rd_party_cookie_stealer.py | py | 420 | python | en | code | 0 | github-code | 6 |
22200579634 | #!/usr/bin/env python
from __future__ import absolute_import
import apache_beam as beam
import argparse
import json
import logging
import sys
import urllib
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from google.cloud import bigquery
f... | mjcastner/edsm_bq | beam_parser.py | beam_parser.py | py | 8,112 | python | en | code | 1 | github-code | 6 |
73739270268 | from buildbot.worker import Worker
from maxscale.config.workers import WORKER_CREDENTIALS
def workerConfiguration():
"""Create worker configuration for use in BuildBot configuration"""
configuration = []
for credentials in WORKER_CREDENTIALS:
configuration.append(Worker(credentials["name"], creden... | dA505819/maxscale-buildbot | master/maxscale/workers.py | workers.py | py | 1,208 | python | en | code | 0 | github-code | 6 |
13321588984 | from airflow.models import Variable
import datetime
from .test_utils import create_test_database, db_connect
from dags.rock.rock_content_items import ContentItem
from dags.rock.rock_content_items_connections import ContentItemConnection
import vcr
create_test_database()
def test_run_fetch_and_save_content_item_conne... | CrossingsCommunityChurch/apollos-shovel | tests/test_rock_content_item_connections.py | test_rock_content_item_connections.py | py | 3,945 | python | en | code | 0 | github-code | 6 |
74918976186 | import networkx as nx
import re
def read_file(file):
first = set()
second = set()
G = nx.DiGraph()
prog = re.compile("Step ([A-Z]) must be finished before step ([A-Z]) can begin.")
with open(file) as f:
lines = f.readlines()
for line in lines:
r = prog.match(line.strip())
... | aarroyoc/advent-of-code-2018 | python/day7/day7.py | day7.py | py | 3,076 | python | en | code | 1 | github-code | 6 |
33548088967 | import os
from django.core.management.base import BaseCommand, CommandError
from main.settings import BASE_DIR, DEBUG
from costcenter.models import Fund, Source, CostCenter, FundCenter, FinancialStructureManager
from lineitems.models import LineForecast, LineItem
class Command(BaseCommand):
"""
A class to be... | mariostg/bft | encumbrance/management/commands/populate.py | populate.py | py | 5,663 | python | en | code | 0 | github-code | 6 |
13931896191 | from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.http import request
from odoo.addons.resident_management.enum import STATUS_TYPES, VEHICLE_TYPES, USER_GROUP_CODE, RELATIONSHIP_TYPES
str_bql = USER_GROUP_CODE[2][0]
str_bqt = USER_GROUP_CODE[3][0]
class tb_vehicle(models.Mod... | cntt0901taizero/residential-adminapp | src/resident_management/models/tb_vehicle.py | tb_vehicle.py | py | 9,234 | python | en | code | 0 | github-code | 6 |
12477031144 | import argparse
import os
import importlib.util
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import json
from collections import defaultdict
import utils
import transformers
parser = argparse.ArgumentParser()
parser.add_argument('--task')
parser.add_argument('--model')
parser.add_argument('--d... | mariopenglee/llm-metalearning | src/main.py | main.py | py | 3,965 | python | en | code | 0 | github-code | 6 |
89691500 | import wordgenerator
NUMBER_OF_WORDS = int(input("How many random words do you want? "))
NUMBER_OF_LETTERS = int(input("How many letters do you want the random words to have? "))
user_options = list()
for i in range(0 , NUMBER_OF_LETTERS):
user_choice = input("What letter " + str(i + 1) + " do you want? Enter 'v'... | caiopg/random-text-generator | randomtextgenerator.py | randomtextgenerator.py | py | 519 | python | en | code | 0 | github-code | 6 |
44343669715 | import sys
sys.stdin = open('input/19236-1.txt') # 33, 43, 76, 39
import copy
def find_fish(x, info):
for i in range(4):
for j in range(4):
if info[i][j][0] == x:
return i, j
return -1, -1
def bfs(x, y, info, total):
global answer
total += info[x][y][0] + 1
dir... | nayeonkinn/algorithm | baekjoon/[G2] 19236. 청소년 상어.py | [G2] 19236. 청소년 상어.py | py | 1,467 | python | en | code | 0 | github-code | 6 |
14391947993 | import glob
import json
def LoadTweets(directory):
directory = directory +"/*json"
files = glob.glob(directory)[:100]
twts = [a for fl in files for a in json.load(open(fl))]
twts.sort(key=lambda x: x['id'] if 'id' in x else int(x['id_str']) if 'id_str' in x else 0)
twts = [a for a in twts if 'id' i... | datumkg/electweet | ElecTweet/TweetLoader.py | TweetLoader.py | py | 1,092 | python | en | code | 0 | github-code | 6 |
1518966554 | from argparse import ArgumentParser, RawTextHelpFormatter
from glob import glob
from subprocess import check_call
import os
from shutil import rmtree
def compile_clm():
# Define and parse command line arguments
# ---------------------------------------
dsc = "Compile CLM on Piz Daint. A case will be cre... | COSMO-RESM/COSMO_CLM2_tools | COSMO_CLM2_tools/compile_clm.py | compile_clm.py | py | 5,769 | python | en | code | 1 | github-code | 6 |
34276132086 | """ Initializes Pickly Files"""
import pickle
import json
import requests
import urllib.request
def guiinit(sub):
#Gets information from Reddit
r = urllib.request.urlopen(r'http://www.reddit.com/r/' + sub + '/new/.json', timeout=60).read().decode("utf-8")
data = json.loads(r)
#Creates ists to hold da... | picklesforfingers/FeedMeReddit | pickleinit.py | pickleinit.py | py | 1,069 | python | en | code | 0 | github-code | 6 |
7720740035 | import sys
#f= open(sys.argv[1], 'r')
# for line in f:
# print(line.strip())
#
#
#f2= open(sys.argv[2],'r')
# for line in f2:
# print(line.strip())
f=open(sys.argv[1])
#create an empty dictionary
flydict= dict()
for line in f:
fields= line.strip().split('\t')
#assign gene name and protein id to the... | Hkhaira1/qbb2021-answers | day2-lunch/day2-lunch.py | day2-lunch.py | py | 775 | python | en | code | 0 | github-code | 6 |
9078103274 | import rospy
from geometry_msgs.msg import Point
import VariableManager
class MasterRecorder:
def __init__(self):
self.recording = VariableManager.recording
self.file = None
self.data_to_write = VariableManager.master_data
def main(self):
if(not self.recording... | adi232004/FDP-Project | MasterDataRecorder.py | MasterDataRecorder.py | py | 1,021 | python | en | code | 0 | github-code | 6 |
25860754920 | from typing import Any
from random import randint, random
import pygame as py
from engine.game_engine import Pygame
from engine.color import Color
from engine.game_objects import IGameObject
from engine.game_objects.modules import IAnimationModule, ICollisionModule
from engine.image import SpriteSheet
from engine.ui.t... | XCPika/Pygame-Extension-Framework | main.py | main.py | py | 8,838 | python | en | code | 0 | github-code | 6 |
29310445886 | from tkinter import *
window = Tk() #need a way of keeping the window on the screen
window.title("First GUI Program")
window.minsize(width = 500, height = 300)
window.config(padx=20,pady=20) #adds more space for our widgets
#Label
my_label = Label(text="taco",font =("Papyrus",20))
my_label["text"] = "cat"
my_label.co... | RoccoPic/100-Days-of-Code | Day-27/main.py | main.py | py | 818 | python | en | code | 0 | github-code | 6 |
6323470596 | import typing
from typing import (
Union,
Optional,
List,
)
import asyncio
import logging
from datetime import datetime
from hikari import ActionRowComponent, Embed, MessageCreateEvent, embeds
from hikari import ButtonStyle
from hikari.impl.special_endpoints import MessageActionRowBuilder, LinkButtonBuilde... | zp33dy/inu | inu/ext/commands/voice.py | voice.py | py | 3,792 | python | en | code | 1 | github-code | 6 |
33245759934 | import time
from collections import OrderedDict
from collections.abc import Callable, Sequence
from typing import Any, NamedTuple
DB = "timeseries"
TABLE_RAW = "paii_raw"
TIME_FIELD = "paii_time"
class Field(NamedTuple):
json_key: str
store_flag: bool
db_name: str
data_type: str
convert: Callable... | PaulSorenson/purpleair_sensor | paii/purple_data.py | purple_data.py | py | 9,065 | python | en | code | 1 | github-code | 6 |
28176871934 | import os
import time
import subprocess
import shlex
import os
from delete_big_files import deleteBigFilesFor1000experiment
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
train_dir = '/home/ubuntu/robust_transfer_learning/'
sample_size_to_number_of_seeds_epochs_and_log_freq = {
400 : (3, 150, 5),
1600 : (2, ... | utrerf/robust_transfer_learning | tools/batch.py | batch.py | py | 1,717 | python | en | code | 11 | github-code | 6 |
2559703297 | import os
from flask import Flask
from flask_jwt_extended import JWTManager
from flask_login import LoginManager
from .auth import ldap_handler
from .db import database
from .db.models import *
from .messages import messages
from .mocks import fake_ldap_handler
configuration_switch = {
"default": "backend.config... | elliecherrill/diligent | backend/__init__.py | __init__.py | py | 2,021 | python | en | code | 1 | github-code | 6 |
9975379557 | from django.conf.urls import url
from .views import *
urlpatterns = [
# 课程列表
url(r'^list/$', CourseListView.as_view(), name='list'),
# 课程详情
url(r'^detail/(?P<course_id>\d+)/$', DetailView.as_view(), name='detail'),
# 视频信息
url(r'^info/(?P<course_id>\d+)/$', InfoView.as_view(), name='i... | Liyb5/web | EduOnline/BlueSky/apps/courses/urls.py | urls.py | py | 635 | python | en | code | 0 | github-code | 6 |
5549915372 | from django.shortcuts import render, redirect
from django.utils import timezone
from .forms import ActivateSertificateForm
from programs.models import Category
from .models import Sertificate
# Create your views here.
def activate_sertificate(request):
if request.method == "POST":
form = ActivateSertifica... | vladisgrig/babeo | activation/views.py | views.py | py | 1,655 | python | en | code | 0 | github-code | 6 |
14254128596 | from __future__ import absolute_import, division, print_function, unicode_literals
from _GTW import GTW
from _MOM import MOM
from _TFL import TFL
import _GTW._OMP._PAP
from _MOM._Graph.Spec import Attr, Child, ET, IS_A, Role, Skip
import _MOM._Gr... | xiaochang91/tapyr | _GTW/_OMP/_PAP/graph.py | graph.py | py | 4,661 | python | en | code | 0 | github-code | 6 |
31535390686 | from functools import wraps
def vowel_filter(function):
vowels = ["a", "e", "i", "o", "u", "y"]
found_vowels = []
@wraps(function)
def wrapper():
for ch in function():
if ch.lower() in vowels:
found_vowels.append(ch)
return found_vowels
return wrapper... | iliyan-pigeon/Soft-uni-Courses | pythonProjectOOP/decorators/vowels_filter.py | vowels_filter.py | py | 416 | python | en | code | 0 | github-code | 6 |
7438577752 | from pathlib import Path
from vesper.tests.test_case import TestCase
from vesper.util.preference_manager import PreferenceManager
import vesper.tests.test_utils as test_utils
_DATA_DIR_PATH = Path(test_utils.get_test_data_dir_path(__file__))
_PREFERENCE_FILE_PATH = _DATA_DIR_PATH / 'Preferences.yaml'
_EMPTY_PREFEREN... | HaroldMills/Vesper | vesper/util/tests/test_preference_manager.py | test_preference_manager.py | py | 2,906 | python | en | code | 47 | github-code | 6 |
72935917627 | import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
app = Celery('backend')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.beat_schedule = {
'check_mail_everyday': {
'task': 'emailServic... | anunayajoshi/futureme | backend/backend/celery.py | celery.py | py | 426 | python | en | code | 0 | github-code | 6 |
33702704860 | import openpyxl as xl
import xlwings as xw
from Worksheet import Worksheet,QPreviewItem
from Workcell import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from copy import copy
#import time
import datetime
##################################################
# class for PS sheet handling
##################... | DericGitHub/excel-operator | model/PSsheet.py | PSsheet.py | py | 6,063 | python | en | code | 0 | github-code | 6 |
11004554798 | class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
totalLen = 0
cur = root
while cur:
totalLen += 1
cur = cur.next
length = totalLen // k
mod = totalLen % 3
res = []
cur = root
for i in range(k... | xixihaha1995/CS61B_SP19_SP20 | temp/toy/python/725. Split Linked List in Parts.py | 725. Split Linked List in Parts.py | py | 601 | python | en | code | 0 | github-code | 6 |
27831010517 | import numpy as np
import netCDF4 as nc4
import net_radiation
import atmospheric_parameters
import wind_shear_velocity
import datetime
# Using TerraClimate
# 2.5 arcminute (1/24 degree) resolution: ~5 km N-S
# Import step
# ... load files here or with a CLI
years = range(1958, 2019)
months_zero_indexed = range(12)
Te... | MNiMORPH/TerraClimate-potential-open-water-evaporation | penman.py | penman.py | py | 5,465 | python | en | code | 2 | github-code | 6 |
23380015513 | from gensim.models.doc2vec import Doc2Vec
import pickle
def get_most_similar_docs(test_data, model_path):
# Load the Doc2Vec model
model = Doc2Vec.load(model_path)
# Split the test_data string into a list of words
test_data_words = test_data.split()
# Infer the vector for the test document
inferred... | Tokarevmm/homework5 | homework_6/recommend.py | recommend.py | py | 1,287 | python | en | code | 0 | github-code | 6 |
44502183300 | from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Length, ValidationError
from urllib.parse import urlparse
from app.models import Business
def business_name_exists(form, field):
business_name = field.data
business = Business.query.filte... | stroud91/ReactFlaskProject | app/forms/bussiness_form.py | bussiness_form.py | py | 2,324 | python | en | code | 0 | github-code | 6 |
73535922429 | import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
def output_result(path, matrix):
f = open(path, "w+")
f.write(str(len(matrix)) + '\n')
for row in matrix:
f.write(str(row)[1:-1])
f.write('\n')
f.close()
def read_buildings(path_to_buildings):
'''
:p... | arsee2/numerical_modelling_diffusion_convection_process | nm_project.py | nm_project.py | py | 6,194 | python | en | code | 0 | github-code | 6 |
23066216205 | import wild_pokemon, wondertrade, pokemon
def index_species(symbols, rom, proj, ps):
""" Creates an index for all species
Parameters:
symbols : The symbol table
rom : The rom
proj : The pymap project
ps : The Pstring parser
Returns: A list of lists containing IndexEntry instances """
... | Fredd40/Violet_Sources | tools/indexer/core.py | core.py | py | 766 | python | en | code | 0 | github-code | 6 |
18004211915 | import os
import numpy as np
import torch
import transforms3d
def plane2pose(plane_parameters):
r3 = plane_parameters[:3]
r2 = np.zeros_like(r3)
r2[0], r2[1], r2[2] = (-r3[1], r3[0], 0) if r3[2] * r3[2] <= 0.5 else (-r3[2], 0, r3[0])
r1 = np.cross(r2, r3)
pose = np.zeros([4, 4], dtype=np.float32)
... | PKU-EPIC/UniDexGrasp | dexgrasp_policy/dexgrasp/utils/data_info.py | data_info.py | py | 669 | python | en | code | 63 | github-code | 6 |
12697223783 | from telegram import Update
from telegram.ext import (
Updater,
CallbackContext,
run_async,
CommandHandler,
)
from utils import Config
from pkgutil import walk_packages
from types import ModuleType
from typing import Dict
from utils import get_filter
submodules: Dict[str, ModuleType] = {
module_n... | finall1008/telegram-pusher-bot | commands/__init__.py | __init__.py | py | 1,483 | python | en | code | 5 | github-code | 6 |
30980411340 | from matplotlib.pyplot import draw
import pygame
from pygame.locals import *
pygame.init()
pygame.mixer.init()
# set screen resolution
resolution = (725,725)
# open a screen of above resolution
screen = pygame.display.set_mode(resolution)
# defining palette colours (global variables) as dictionary
gameColours={
... | jessica-leishman/high-rollers | analysis_static/manual slices/hrStatic3.py | hrStatic3.py | py | 4,288 | python | en | code | 0 | github-code | 6 |
21207331986 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.urls import reverse_lazy
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import *
from .filters ... | AlexAlexG/SF_lessons | NewsPaper/news/views.py | views.py | py | 3,331 | python | en | code | 0 | github-code | 6 |
31535896406 | from exam_python_OOP_22_august_2020.project.rooms.room import Room
class Everland:
def __init__(self):
self.rooms = []
def add_room(self, room: Room):
if room not in self.rooms:
self.rooms.append(room)
def get_monthly_consumptions(self):
monthly_consumptions = 0
... | iliyan-pigeon/Soft-uni-Courses | pythonProjectOOP/exam_python_OOP_22_august_2020/project/everland.py | everland.py | py | 2,108 | python | en | code | 0 | github-code | 6 |
28427023060 | # import os
# import time
# import random
# # 练习1:在屏幕上显示跑马灯文字。
# def main():
# content = "北京欢迎你为你开天辟地…………"
# while True:
# # 清理屏幕上的输出
# # os.system('cls')
# # os.system('clear')
# print(content)
# # 休眠200毫秒
# time.sleep(0.1)
# content = content[1:] + con... | sunhuimoon/Python100Days | day07/day0710.py | day0710.py | py | 1,929 | python | zh | code | 0 | github-code | 6 |
30056116646 | def find2NumbersThatAddTo(arr, expectedSum, lo, hi):
while lo < hi:
sum = arr[lo] + arr[hi]
if sum == expectedSum:
return lo, hi
elif sum < expectedSum:
lo = lo + 1
else:
hi = hi - 1
def find3NumbersThatAddTo(arr, expectedSum):
lo = 0
hi ... | nithish-thomas/adventOfCode2020 | aoc20/day1/day1_2.py | day1_2.py | py | 1,943 | python | en | code | 0 | github-code | 6 |
39349977880 | # Definition for double singly-linked list.
class DbListNode(object):
"""构建一个双向链表"""
def __init__(self, x, y):
self.key = x
self.val = y
self.next = None
self.prev = None
class LRUCache(object):
'''
leet code: 146
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。
它应该支持以下操... | smdzz/Geek_Point | data_structure_and_algorithm/python/linked_list/LRUCache.py | LRUCache.py | py | 4,050 | python | zh | code | 0 | github-code | 6 |
10137589364 | '''
File name: /ciphers/block_ciphers/anu/cipher.py
Author: Cesar Cruz
Project: cryptofeather
Python Version: 2.7
'''
import numpy
from constants import BLOCK_LENGTH, KEY_LENGTH, NUMBER_OF_ROUNDS, SBOX, PBOX, SBOX_INV
from utils.logic_operations import xor
from utils.crypto import sbox_operation, permutation_... | ccruz182/Lightweight-Cryptography | cryptofeather/ciphers/block_ciphers/anu/cipher.py | cipher.py | py | 3,372 | python | en | code | 1 | github-code | 6 |
70943725628 | import json
import os
class FolderWalker:
"""
Check folder with results. Walk through the folders and define paths to various files.
If any values are not counted in one of the frameworks, they will be excluded in competitors.
Thus, the class ensures consistency of results in the analysis.
"""
... | ITMO-NSS-team/pytsbe | pytsbe/report/walk.py | walk.py | py | 5,028 | python | en | code | 30 | github-code | 6 |
25018507922 | import base64
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
current_dir = os.path.dirname(os.path.abspath(__file__))
def encrypt_data(data, key_path='public.pem'):
p... | ivana-dodik/Blockchain | EP --zadatak 02/crypto.py | crypto.py | py | 1,898 | python | en | code | 0 | github-code | 6 |
36273987017 | from random import randint
from ..engine.enemy import Enemy
class Barrel(Enemy):
def __init__(self, level):
super(Barrel,self).__init__(level)
self.health = self.max_health = 100
self.speed = 0.35
self.set_die_sound('assets/sound/barrelguy/die.ogg')
self.set_sprit... | Timtam/ggj17 | wavomizer/enemies/barrel.py | barrel.py | py | 406 | python | en | code | 0 | github-code | 6 |
15298986512 | #!/usr/bin/python3.6
import requests, json, datetime
from time import sleep
try:
while True:
req = requests.get('https://www.mercadobitcoin.net/api/BTC/ticker/')
cot = json.loads(req.text)
d = datetime.datetime.now()
print(d.strftime('%c'))
print('BTC:', cot['ticker']['buy'][:8])
sleep(10)
... | andreMarqu3s/bit_value | cotacao.py | cotacao.py | py | 387 | python | en | code | 0 | github-code | 6 |
72810210107 | def create_piechart():
# Importamos las dependencias
import pandas as pd
import matplotlib.pyplot as plt
from config import engine
from sqlalchemy.orm import sessionmaker
engine = engine
# Intentamos leer desde la base de datos, la tabla "tabla_1"
try:
with engine.connect() as ... | NebyX1/data-science-engineering-end-to-end-project-bootcamp-milei-twitter-scraping | piechart_script.py | piechart_script.py | py | 1,239 | python | es | code | 0 | github-code | 6 |
43755877766 | '''
Measures the square area of colonies in an image file.
Written by George Walters-Marrah
Last updated: 6/26/2019
'''
# import needed packages
import imageio
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
import numpy as np
from skimage import morphology as morph
import os.path
from os ... | gwmarrah/colony-measurer | colSizeMeasurer.py | colSizeMeasurer.py | py | 9,835 | python | en | code | 1 | github-code | 6 |
23039179017 | import cv2
import numpy as np
from hand import HandRecognizer
from args import OLD_FONT_THRESHOLD
class OldRecognizer(HandRecognizer):
def __init__(self, imname, already_read=False):
super(OldRecognizer, self).__init__(imname, already_read)
self.cal_result()
def loop_process(self, func):
... | sjdeak/RoboMasters2017-RuneDetector | old.py | old.py | py | 1,379 | python | en | code | 0 | github-code | 6 |
10719487359 | import time
import xml.etree.ElementTree as Et
import random
import pathlib
import shutil
from zipfile import ZipFile
def name_for_ik():
"""
:return: выдает имена формата ###-###-###-###-### в шестнадцатиричной системе для интеграционных конвертов
"""
first_part = str(hex(random.randint(1000000000, 99... | Steelglowhawk/updateTool | generator_func.py | generator_func.py | py | 11,827 | python | ru | code | 1 | github-code | 6 |
8267514816 | from __future__ import annotations
from kombu.pools import producers
from .queues import task_exchange
priority_to_routing_key = {
'high': 'hipri',
'mid': 'midpri',
'low': 'lopri',
}
def send_as_task(connection, fun, args=(), kwargs={}, priority='mid'):
payload = {'fun': fun, 'args': args, 'kwargs'... | celery/kombu | examples/simple_task_queue/client.py | client.py | py | 994 | python | en | code | 2,643 | github-code | 6 |
41172517370 | # -*- coding: utf-8 -*-
import numpy as np
def abs_error(X, y):
"""
Calculates absolute error of a px2 matrix with its px1 predicted output
"""
y_hat = np.matrix(y).transpose()
y = X[:, 1]
m=len(y)
error = (1/m)*sum(abs(y-y_hat))
return float(error)
def mean_error(X, y):
... | SThornewillvE/Udacity-DataScience-Nanodegree | 01_supervised-models_learning-materials/linreg/01_calculate_cost.py | 01_calculate_cost.py | py | 1,014 | python | en | code | 29 | github-code | 6 |
22113638832 | import numpy as np
from grabscreen import grab_screen
import cv2
import time
from directkeys import PressKey, ReleaseKey, W, A, S, D
from grabkeys import key_check
import os
from keras.models import load_model
from scanner import process_img
#loading model
model = load_model('model.h5')
#W key press-time bounds
PRES... | pashok3d/GTA_AutoPilot | predictor.py | predictor.py | py | 2,723 | python | en | code | 0 | github-code | 6 |
15805513471 | from tkinter import N
import pygame
from pygame.locals import *
from Car import Car
import sys
import neat
import time
def on_init():
pygame.init()
on_init()
screen_width = 1920
screen_height = 1080
_running = True
screen = pygame.display.set_mode((screen_width, screen_height), pygame.HWSURFACE | pygame.DOUB... | styyxofficial/NEAT-AI-Racecar | Moving_Car.py | Moving_Car.py | py | 4,216 | python | en | code | 0 | github-code | 6 |
11615238643 | import random as r
i=1;c=0;p=0;d=0
while(i<=10):
rand=r.randint(1,10)
if rand<3:
comp='s'
elif rand>=3 and rand<6:
comp='w'
elif rand>=6 and rand<=10:
comp='g'
inp=input('Enter "S" for snake "W" for water and "G" for gun\n')
if comp=='s' and inp=='w':
print... | Coder-X27/Python-CWH | playlist exercise/exercise-6.py | exercise-6.py | py | 1,109 | python | en | code | 1 | github-code | 6 |
12700893052 | n = int(input())
numbers = sorted(map(int, input().split()))
def isGood(numbersWithoutTheNum, theNum):
lastIdx = len(numbersWithoutTheNum) - 1
p1, p2 = 0, lastIdx
while p1 < p2:
result = numbersWithoutTheNum[p1] + numbersWithoutTheNum[p2]
if result == theNum:
return True
... | MinChoi0129/Algorithm_Problems | BOJ_Problems/1253.py | 1253.py | py | 555 | python | en | code | 2 | github-code | 6 |
39525459958 | import pyttsx3
from gtts import gTTS
import os
#MALE
engine = pyttsx3.init()
engine.say("Hello there")
engine.runAndWait()
#FEMALE
mytext = 'You are welcome to Roles Academy Madam.'
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("welcome.mp3")
os.system("mpg321 welcome.mp3")
| adesolasamuel/EqualityMachine | texttospeech.py | texttospeech.py | py | 312 | python | en | code | 1 | github-code | 6 |
17040080901 | import requests
import time
from bs4 import BeautifulSoup
def ProfessorLunkedInScrapper(
ProfessorName,CollegeName
):
#ProfessorName = "Roel Verstappen"
#CollegeName = "University of Groningen"
query = 'https://google.com/search?q=site:linkedin.com/in AND "'+ProfessorName+'" AND "'+CollegeName+'"'
respo... | brucema94/Expertfinder | LinkedinUrl_From_Name.py | LinkedinUrl_From_Name.py | py | 664 | python | en | code | 0 | github-code | 6 |
10424840901 | #-*- coding: utf-8 -*-
"""
@author: Martí Congost
@contact: marti.congost@whads.com
@organization: Whads/Accent SL
@since: September 2009
"""
from cocktail.events import when
from cocktail.translations import (
translations,
set_language
)
from cocktail import schema
from cocktail.persistence import datast... | marticongost/woost | woost/extensions/shop/__init__.py | __init__.py | py | 5,539 | python | en | code | 0 | github-code | 6 |
35423067505 |
def isValid(puzzle: list, index: tuple, guess: int) -> bool:
# returning a True if the guess is in a correct place and False otherwise
# we compare 'guess' with it's row, column and 3x3 square
# first: check if the guess is already exist in its row
row = index[0]
col = index[1]
for val... | MartinaNaeem/SudokuSolver | Solve.py | Solve.py | py | 5,616 | python | en | code | 0 | github-code | 6 |
8317691335 | # A script for checking triangular arbitrage opportunities (Forward + Reverse)
# Using a general formula. (Pairs NEED to match the formula)
# ETH/USDT, BTC/USDT, BTC/ETH
# a/b, c/b, c/a
import ccxt
# Insert exchange
testexchange = ccxt.kucoin({
'enableRateLimit': True,
})
# Choose whatever 3 pairs match the g... | AgenP/AgenP-triangular-arb-cex-scanner-v1 | arb_ku_test.py | arb_ku_test.py | py | 2,318 | python | en | code | 0 | github-code | 6 |
7795403561 | from data_loader import SimpleDataset
import string
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
import numpy as np
# from run_exp... | geenen124/nlp_project | gru_regression.py | gru_regression.py | py | 12,316 | python | en | code | 0 | github-code | 6 |
40677441703 | """empty message
Revision ID: 37bd12af762a
Revises: fa12c537244a
Create Date: 2022-09-06 21:29:41.287889
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '37bd12af762a'
down_revision = 'fa12c537244a'
branch_labels = None... | magma/magma | dp/cloud/python/magma/db_service/migrations/versions/020_remove_cpi_related_fields.py | 020_remove_cpi_related_fields.py | py | 1,747 | python | en | code | 1,605 | github-code | 6 |
11245689019 | import torch
from torch.utils.data import DataLoader
from transformers import AdamW
from core.qa.utils import (
read_squad,
add_end_idx,
add_token_positions,
tokenizer,
model,
)
train_contexts, train_questions, train_answers = read_squad(
"squad-style-answers.json"
)
train_encodings = tokeni... | expectopatronm/FAQ-Generation-and-SQuaD-Style-QA-Answering-System | core/qa/trainer.py | trainer.py | py | 1,760 | python | en | code | 1 | github-code | 6 |
1528634365 | from random import randint
import cProfile
ARRAY_LENGTH = 10000
def insertion_sort(array):
for i in range(1, len(array)):
key_item = array[i]
j = i - 1
while j>=0 and array[j] > key_item:
array[j+1] = array[j]
j -= 1
array[j+1] = key_item
return array... | Harsh188/SSP-KVS | week1/a1_hc/insertionSort.py | insertionSort.py | py | 456 | python | en | code | 0 | github-code | 6 |
30165255260 | # Name: Milou Bisseling
# Studentnumber: 10427538
'''
This program converts CSV to JSON
'''
import csv
import json
import sys
inputfile = 'totalbirths.csv'
outputfile = 'totalbirths.json'
fieldnames = ("Perioden", "Enkelvoudige geboorten", "Tweelinggeboorten", "Drie- of meervoudige geboorten")
# Open and read CSV ... | miloubis/DataProcessing | Homework/week-6/convertCSV2JSON.py | convertCSV2JSON.py | py | 559 | python | en | code | 0 | github-code | 6 |
11594315825 | import TypeImg
from TypeImg import *
class WrapImg(TypeImage):
def __init__(self,img,imgThreshold=None,contours=None,biggest=None,max_area=None):
super().__init__(img,imgThreshold,contours,biggest,max_area)
self.imgWarpColored=self.imgWarpGray =None
def Repair_Biggest_Contour(self):
... | tvanh239/Document-Scanner | ImgWarp.py | ImgWarp.py | py | 2,041 | python | vi | code | 0 | github-code | 6 |
74370505788 | from .api_doc import ApiDoc
from .media_type import MediaType
class Request(ApiDoc):
def __init__(
self, content: MediaType, description: str = "", required: bool = False
):
self.content = content
self.description = description
self.required = required
def to_doc(self) -> ... | dkraczkowski/opyapi | opyapi/api/request.py | request.py | py | 525 | python | en | code | 6 | github-code | 6 |
41859484302 | # Open the input file for reading
with open("1601456737847_Plants_Release42_triticum_dicoccoides.txt", "r") as input_file:
# Open the output file for writing
with open("output.fa", "w") as output_file:
# Read the contents of the input file
content = input_file.readlines()
# Loop over the... | sejyoti/Questions-of-python-for-bioinformatics | Problem_1_solution/convert_to_fasta.py | convert_to_fasta.py | py | 863 | python | en | code | 0 | github-code | 6 |
75051539388 | from stratego.location import Location
from stratego.piece import Color, Piece, Rank
from stratego.printer import Printer
from testing_utils import build_test_board
# pylint: disable=protected-access
# noinspection PyProtectedMember
def test_printer_piece_movement():
r""" Verify piece movement as part of the \p ... | ZaydH/stratego | src/tests/test_printer.py | test_printer.py | py | 1,498 | python | en | code | 0 | github-code | 6 |
73979398907 | #!/usr/bin/env python3
import telebot
from telebot import types
import sqlite3
sqll = [0]
bot = telebot.TeleBot("TOKEN", parse_mode=None)
conn = sqlite3.connect('SQLdb.db', check_same_thread=False)
cursor = conn.cursor()
def updateUserBalance (id: int, balans: int):
cursor.execute('UPDATE users SET balans=? WH... | thebilderberg/telegram_bot_github | star_bot.py | star_bot.py | py | 10,747 | python | ru | code | 0 | github-code | 6 |
71916477308 | # coding:utf-8
from PyQt5.QtWidgets import QWidget, QGridLayout, QVBoxLayout, QSizePolicy, QListWidgetItem, QAbstractItemView
from PyQt5.QtCore import pyqtSignal
from qfluentwidgets import ListWidget, PrimaryPushButton, PillPushButton, FluentIcon, InfoBar
from common.style_sheet import StyleSheet
from common.config ... | xfz329/pk4adi_calculator | view/operate_interface.py | operate_interface.py | py | 10,462 | python | en | code | 0 | github-code | 6 |
18128239741 | from django.conf.urls import url, include
from . import views
#app_name = 'dmlpolls'
urlpatterns = [
url(r'^$', views.index, name='poll_index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='poll_detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='poll_results'),
url(r'^(?P<question... | Yobmod/dmlsite | dmlpolls/urls_old.py | urls_old.py | py | 457 | python | en | code | 1 | github-code | 6 |
26529448636 | #신입사원*
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
grade = []
n = int(input())
cnt = n
for _ in range(n):
paper, interview = map(int, input().split())
grade.append([paper, interview])
grade = sorted(grade, key= lambda a: a[0])
temp = grade[0][1]
... | Jaeheon-So/baekjoon-algorithm | 그리디/1946.py | 1946.py | py | 468 | python | en | code | 0 | github-code | 6 |
26327096081 | import money
from exceptions import *
from tkinter import *
from datetime import *
from decimal import Decimal
import math
import re
from tkinter import messagebox
from dateutil.rrule import *
from parkomat_interface import ParkomatInterface
class ParkomatFunctions:
""" Klasa realizująca funkcjonalności programu ... | DZietara/parkomat | main/parkomat_functions.py | parkomat_functions.py | py | 18,188 | python | pl | code | 0 | github-code | 6 |
37446576919 | from subprocess import call
from metux.util.specobject import SpecError
def rsync_ssh(username, hostname, source, path):
return (call([
'rsync',
'--progress',
'--rsh=ssh',
'-r',
source+"/",
username+"@"+hostname+":/"+path ]) == 0)
def run_upload(param):
if param... | LibreZimbra/librezimbra | deb_autopkg/util/upload.py | upload.py | py | 517 | python | en | code | 4 | github-code | 6 |
38463867669 | from django.urls import path, re_path
from app import views
urlpatterns = [
# Matches any html file - to be used for gentella
# Avoid using your .html in your resources.
# Or create a separate django app.
re_path(r'^.*\.html', views.gentella_html, name='index'),
# The home page
path('', views.... | pennng/Django-gentella | app/urls.py | urls.py | py | 752 | python | en | code | 0 | github-code | 6 |
72532296829 | # pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
from contextlib import contextmanager
from typing import Any, AsyncIterable, Callable, Iterator
from unittest.mock import AsyncMock
import pytest
from faker import Faker
from fastapi import FastAPI, status
from httpx import HTTPError, Response
fro... | ITISFoundation/osparc-simcore | services/director-v2/tests/unit/test_modules_dynamic_sidecar_client_api_public.py | test_modules_dynamic_sidecar_client_api_public.py | py | 11,510 | python | en | code | 35 | github-code | 6 |
41163745392 | import os.path
from compiler import compile_file
from interpreter import VirtualMachine
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
raise RuntimeError("Not enough argument to start the compiler")
else:
if sys.argv[1] == "--version":
print("0.2.0-dev")
else:
... | blitpxl/soil | soil/soil.py | soil.py | py | 509 | python | en | code | 1 | github-code | 6 |
73500508668 | import argparse
import copy
import csv
import os
import warnings
import numpy
import torch
import tqdm
import yaml
from torch.utils import data
from nets import nn
from utils import util
from utils.dataset import Dataset
warnings.filterwarnings("ignore")
def learning_rate(args, params):
def fn(x):
retu... | jahongir7174/YOLOv5-pt | main.py | main.py | py | 14,941 | python | en | code | 4 | github-code | 6 |
36464449846 | #!/usr/bin/env python
"""
Usage:
python detectface.py -i image.jpg
"""
from argparse import ArgumentParser
import boto3
from pprint import pprint
import sys
def get_client(endpoint):
client = boto3.client('rekognition')
return client
def get_args():
parser = ArgumentParser(description='Detect... | wwwins/aws-utils | detectface.py | detectface.py | py | 830 | python | en | code | 0 | github-code | 6 |
6849069742 | #三方库 xlrd /xlwt / xlutils
import xlrd
import xlwt
import xlutils
wb = xlrd.open_workbook('table/阿里巴巴2020年股票数据.xls')
#获取所有工作表的名字
# print(wb.sheet_names())
# sheet1 = wb.sheet_names('表格1') #通过工作表名获取
sheet = wb.sheet_by_index(0) #通过工作表的下标ID获取工作表
#获取工作表的行数,列数
# print(sheet.nrows,sheet.ncols)
#获取单元格数据 第一行的第一列
for ... | twlaladelala/pytest | 办公自动化.py | 办公自动化.py | py | 732 | python | zh | code | 0 | github-code | 6 |
20289463636 | import math
def isLeapYear(x):
if (x % 4 != 0):
return False
elif (x % 100 != 0):
return True
elif (x % 400 != 0):
return False
else:
return True
try:
y = int(input("Enter number to test: "))
if (y < 0):
raise ValueError()
except ValueError:
print("Input is not an positive integer.")
else:
if (isLe... | steffebr/cs362HW3 | leapyearV2.py | leapyearV2.py | py | 461 | python | en | code | 0 | github-code | 6 |
72592324348 | import configparser
import os
from core.constants import CONFIG_FILE_PATH
__all__ = [
'BotConfigurator'
]
class BotConfigurator(object):
""" Объект-конфигуратор приложения. """
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(BotConfigurator,... | balandin-nick/smart-telegram-bot | core/configurator.py | configurator.py | py | 1,174 | python | en | code | 0 | github-code | 6 |
31622032831 | import os
from flask import Flask, flash, request, redirect, url_for, send_from_directory, jsonify
from werkzeug.utils import secure_filename
from excel import Excel
from translator import Translator
UPLOAD_FOLDER = './text_files'
DOWNLOAD_FOLDER = './excel_files'
ALLOWED_EXTENSIONS = {'txt'}
app = Flask(__name__, st... | atakanzen/terminolator.web | app.py | app.py | py | 2,579 | python | en | code | 2 | github-code | 6 |
19880677789 | # cython:language_level=3
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
deltas = 2000
a = 215
r = 290
def fx(n):
global deltas, a, r
x1 = a+n
x2 = a-n
return deltas - (area(x2, r) - area(x1, r))
def fx1(n):
a = 215
r = 290
x1 = a+n
x2 = a-n
return... | rzyfrank/Internship | cal_deltaArea.py | cal_deltaArea.py | py | 1,006 | python | en | code | 0 | github-code | 6 |
23515104620 | T = int(input())
RS_list = []
for _ in range(T):
R, S = input().split()
temp = [i*int(R) for i in list(S)]
RS_list.append(''.join(temp))
for i in RS_list:
print(i)
| Soohee410/Algorithm-in-Python | BOJ/Bronze/2675.py | 2675.py | py | 182 | python | en | code | 6 | github-code | 6 |
7796423185 | # ############################################################################ #
# This is part of the PPLT project. #
# #
# Copyright (C) 2003-2006 Hannes Matuschek <hmatuschek@gmx.net> ... | BackupTheBerlios/pplt-svn | PPLT/Modules/Core/Master/Device/S7/SimaticS7.py | SimaticS7.py | py | 5,265 | python | en | code | 0 | github-code | 6 |
13864700033 | #!/usr/bin/python3.5
# -*-coding:Utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.decomposition import PCA
from matplotlib.ticker import FormatStrFormatter
from RBFKernelPCA import RBF_Kernel_PCA
# We create a dataset of two half moons and project them on... | PiggyGenius/MachineLearning | NoLibraries/RBFKernelPCA/ProjectNewDataPoints.py | ProjectNewDataPoints.py | py | 1,809 | 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.