seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
25893346960 | import pygame
from pygame.draw import *
from random import randint
pygame.init()
FPS = 60 #число новых кругов в секунду
number_of_balls=4 #число обычных шаров
points=0 #счетчик очков
base_points_multiplier=100 #базовый множитель начисления очков
x_res,y_res=1920/1.25, 1080/1.25 #разрешение
res=[x_res,y_res]
sp_mult=0.... | furs-aka-beast/mipt_inf | 1_sem/Lab8/balls.py | balls.py | py | 3,786 | python | ru | code | 0 | github-code | 6 |
11307160967 | from django.conf.urls import url
from .views import Discount_view, Category_view, Product_view, Product_detail_view, Category_detail_view
#These two added for viewsets
# from django.conf.urls import include
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from django.contrib impor... | wjbarng/INFO441-Wholesale | wholesale/urls.py | urls.py | py | 1,708 | python | en | code | 0 | github-code | 6 |
22278226365 | #python program to print number pattern using while loop
n = int(input("Enter number of rows: "))
k = 1
i = 1
while i<=n:
j = 1
while j<+i:
print(k,end= "")
j+=1
k+=1
print()
i+=1
| luckyprasu22/python-program | pattern1-15.py | pattern1-15.py | py | 262 | python | en | code | 0 | github-code | 6 |
16199644126 | ############################################################################
## Django ORM Standalone Python Template
############################################################################
# Turn off bytecode generation
from datetime import time
import sys
sys.dont_write_bytecode = True
# Django specific setti... | barrydaniels-nl/crypto-api | ctimanager/scripts/update_news_items.py | update_news_items.py | py | 15,028 | python | en | code | 0 | github-code | 6 |
3345686330 | import argparse
import subprocess
import os.path
import math
def dispatch(out_file, err_file, cmd, go, num_cores=1, num_nodes=1, max_hours=1, memory_in_gb=16):
"""
Populates 'runscript.sh' file to run 'dqn_original.py' file
on cluster's GPU partition for 'max_hours' hours with 1 node, 1 core, and 32GB mem... | osiajod/cs205_project | singlenode_parallel/src/cluster_serialtrain.py | cluster_serialtrain.py | py | 4,870 | python | en | code | 0 | github-code | 6 |
35007806774 | from src.main.python.Solution import Solution
# Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
# Find all unique quadruplets in the array which gives the sum of target.
#
# Note:
# Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b... | renkeji/leetcode | python/src/main/python/Q018.py | Q018.py | py | 1,844 | python | en | code | 0 | github-code | 6 |
7170828604 | #Answer to Find the Runner-Up Score!
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
j=-100
k=max(arr)
for i in arr:
if(i>j):
if(i!=k):
j=i
print(j) | CompetitiveCode/hackerrank-python | Practice/Basic Data Types/Find the Runner-Up Score!.py | Find the Runner-Up Score!.py | py | 247 | python | en | code | 1 | github-code | 6 |
17177402704 | """
Kaming Yip
CS677 A1 Data Science with Python
Apr 3, 2020
Assignment 9.3: Random Forest
"""
from pandas_datareader import data as web
import os
import pandas as pd
import numpy as np
from tabulate import tabulate
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics imp... | KamingYip/Trading_Strategies_with_Stock_Data | Random Forest.py | Random Forest.py | py | 18,943 | python | en | code | 3 | github-code | 6 |
36363712042 | import pyodbc
from db_connect_oop import *
class NWEmployees(MSDBConnection):
def all_employees(self):
query = 'select * from employees'
data = self._MSDBConnection__sql_query(query)
while True:
record = data.fetchone()
if record is None:
break
... | dilanmorar/pyodbc_connection | db_employees_oop.py | db_employees_oop.py | py | 931 | python | en | code | 0 | github-code | 6 |
28989994372 | if True:
from PyQt5.QtCore import pyqtSlot, QSettings
from PyQt5.QtWidgets import QApplication, QDialog, QDialogButtonBox, QTableWidgetItem
from PyQt5.QtXml import QDomDocument
else:
from PyQt4.QtCore import pyqtSlot, QSettings
from PyQt4.QtGui import QApplication, QDialog, QDialogButtonBox, QTableW... | falkTX/Cadence | src/catarina.py | catarina.py | py | 54,241 | python | en | code | 361 | github-code | 6 |
19887674480 | #
# -*- coding: utf-8 -*-
# OpenPGPpy OpenPGPcard : OpenPGP smartcard communication library for Python
# Copyright (C) 2020-2022 BitLogiK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... | bitlogik/OpenPGPpy | OpenPGPpy/openpgp_card.py | openpgp_card.py | py | 22,169 | python | en | code | 8 | github-code | 6 |
19523144511 | from celery import shared_task
from time import sleep
from .models import Movie
@shared_task
def increase_ranking():
# increase_ranking: This task increases the ranking of upcoming movies by 10 every 5 minutes. It gets a list of
# all upcoming movies from the database, iterates over them, and adds 10 to each ... | Optimustprime/cinema_program | app/movies/tasks.py | tasks.py | py | 853 | python | en | code | 0 | github-code | 6 |
8424293393 | from bs4 import BeautifulSoup
import spacy
import os
#nlp = spacy.load("nl_core_news_lg")
nlp = spacy.load("en_core_web_lg")
import regex as re
from nltk import ngrams
import pickle
import json
from augment.replace import BertSampler
from sacremoses import MosesDetokenizer
md = MosesDetokenizer(lang='en')
def position... | TallChris91/Neural-Data-to-Text-Small-Datasets | Data_Augmentation/Mark_Words_E2E.py | Mark_Words_E2E.py | py | 14,690 | python | en | code | 0 | github-code | 6 |
18399278652 | # SPDX-License-Identifier: GPL-2.0-only
import threading
from pprint import pprint
import pytest
from flask import url_for
import libeagle
from tests.simulator import eagle200sim
import re
@pytest.fixture(scope="session", autouse=True)
def app():
app = eagle200sim.create_app()
return app
@pytest.mark.use... | lrusak/py-eagle-200 | tests/test_eagle200.py | test_eagle200.py | py | 1,240 | python | en | code | 0 | github-code | 6 |
8978366140 | import os
import pandas as pd
from darts import TimeSeries
from darts.models import LightGBMModel
from enfobench import AuthorInfo, ModelInfo, ForecasterType
from enfobench.evaluation.server import server_factory
from enfobench.evaluation.utils import periods_in_duration
class DartsLightGBMModel:
def __init__(se... | attila-balint-kul/energy-forecast-benchmark-examples | models/dt-lightgbm-direct/src/main.py | main.py | py | 1,933 | python | en | code | 2 | github-code | 6 |
26038625786 | from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Iterable
from pants.backend.cc.subsystems.compiler import CCSubsystem, ExternalCCSubsystem
from pants.backend.cc.target_types import CCLanguage
from pants.core.util_rules.archive import ExtractedArchive
fr... | pantsbuild/pants | src/python/pants/backend/cc/util_rules/toolchain.py | toolchain.py | py | 7,547 | python | en | code | 2,896 | github-code | 6 |
73829193786 | # Usage:
import asyncio
from starknet_py.net.gateway_client import GatewayClient
from starknet_py.net.networks import TESTNET
from starknet_py.net import AccountClient, KeyPair
from starknet_py.contract import Contract
from starknet_py.net.models.chains import StarknetChainId
uuid = '2f530e87-a2c5-47c9-8ebf-e704dc06e9d... | feltroidprime/CTF-starknet-cc | challenges/solve-me/deploy.py | deploy.py | py | 1,531 | python | en | code | 0 | github-code | 6 |
39332700051 | # -*- coding: utf-8 -*-
import os
import networkx as nx
import sorcery_read
import sorcery_make
import sorcery_save
#
# メイン処理
#
def main(excelFileName):
# ディレクトリの作成
out_dir = os.path.splitext(
os.path.basename( excelFileName ) )[0]
if not os.path.exists( out_dir ):
os.makedirs( out_dir )
# エクセルファイルの読み込み... | NaotoNAKATA/my_sample | python/networkx/sorcery_graph.py | sorcery_graph.py | py | 1,779 | python | ja | code | 0 | github-code | 6 |
13239474097 | from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
from numpy import *
from matplotlib.pyplot import *
import sys
def solver(I, a, T, dt, theta):
"""Solve u'=-a*u, u(0)=I, for t in (0,T]; step: dt."""
dt = float(dt) # avoid ... | hplgit/doconce | doc/src/slides/src/solver.py | solver.py | py | 4,682 | python | en | code | 305 | github-code | 6 |
20665108806 | import os
from dataclasses import dataclass, field
from pathlib import Path
from .file_utils import CsvWriter, JsonWriter, PickleWriter
@dataclass
class File:
""" Класс, представляющий файл. """
name: str
size: int
parent: 'Directory'
path: str
def __str__(self):
return f"File: {self... | nadia3373/GeekBrains-Python-Developer | Diving into Python/s10/directory_traversal/directory_traversal.py | directory_traversal.py | py | 3,249 | python | en | code | 1 | github-code | 6 |
407829777 | import time
from subprocess import call
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
t = time.time()
reg = [1.0,2.04054585,-20.38379773,-3.93128902]
params = [0.5,0.2,0.1,0.3,0.006]
time_ = [0,10,100]
reg_s = [str(k) for k in reg]
params_s = [str(k) for k in params]
time_s = [str(k) for k in... | radluki/InvertedPendulum | test2/reader.py | reader.py | py | 681 | python | en | code | 0 | github-code | 6 |
27259261820 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""813. Largest Sum of Averages [Naive]
"""
class Solution:
def largestSumOfAverages(self, nums, k):
n = len(nums)
summ = [0]*n
summ[0] = nums[0]
for i in range(1, n):
summ[... | asperaa/back_to_grind | DP/813. Largest Sum of Averages_Naive.py | 813. Largest Sum of Averages_Naive.py | py | 740 | python | en | code | 1 | github-code | 6 |
27980959232 | import glob
import sqlite3
import csv
import time;
conn = sqlite3.connect('gdax_0.1.db')
cur = conn.cursor()
cur.execute("SELECT * FROM quotes_BTC_LTC") # WHERE start >?", (1420160461, ))
results1 = cur.fetchall()
conn2 = sqlite3.connect('gdaxLTC.db')
cur2 = conn2.cursor()
cur2.execute("SELECT * FROM quotes_BTC_LTC"... | HristoHr/backTestEngine | CheckDataCompletenessDB.py | CheckDataCompletenessDB.py | py | 1,226 | python | en | code | 0 | github-code | 6 |
25389647152 | import nltk
import numpy as np
import pandas as pd
import re
"""This code aims to perform text preprocessing and save processed texts as a new file"""
def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None):
"""Text processing: remove stopwords, stem or lemma"""
## clean (convert ... | nogibjj/Suicide-Text-Classification | a_01_text_preprocessing.py | a_01_text_preprocessing.py | py | 1,659 | python | en | code | 0 | github-code | 6 |
33255293229 | from typing import Optional
from fastapi.routing import APIRouter
from pydantic.main import BaseModel
from mongo import user_col, list_col
from auth_repo import ar
from dependencies import verify_token_dependency
from bson.objectid import ObjectId
from fastapi import Depends
from fastapi.routing import APIRouter
user_... | snokpok/listlive | backend/src/routers/user.py | user.py | py | 2,432 | python | en | code | 1 | github-code | 6 |
31591116775 | '''
Created on 2019年8月29日
@author: MR.Tree
'''
def save_txt(wea_group):
i=len(wea_group)
print('总条数:',i)
for t in wea_group:
my_file=open('E:\\weather_date01.txt','a')
my_file.write('\n'+t)
print('---写入完成---')
my_file.close() | roxasqiao/get_weather | get_weather/save_txt.py | save_txt.py | py | 312 | python | zh | code | 1 | github-code | 6 |
30522562696 | from django.urls import path
from django.views.generic import TemplateView
import mainapp.views as views
app_name = 'mainapp'
urlpatterns = [
path('',
views.WorkoutListView.as_view(),
name='index'),
path('about/',
TemplateView.as_view(template_name='mainapp/about.html'),
... | galla-okto/otus_training_site | mainapp/urls.py | urls.py | py | 969 | python | en | code | 0 | github-code | 6 |
74977715387 | import csv
import re
import logging
import gzip
import io
import sys
import os
import yaml
from dipper.sources.ZFIN import ZFIN
from dipper.sources.WormBase import WormBase
from dipper.sources.Source import Source
from dipper.models.assoc.Association import Assoc
from dipper.models.assoc.G2PAssoc import G2PAssoc
from... | monarch-initiative/dipper | dipper/sources/GeneOntology.py | GeneOntology.py | py | 24,532 | python | en | code | 53 | github-code | 6 |
14138130461 | from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField
class Rate(FlaskForm):
rating = SelectField('Выберите оценку',
choices=[(None, 'Не завершено'), (10, 'Шедевр(10)'), (9, 'Великолепно(9)'),
(8, 'Очень хорошо(8)'), (7, 'Хорошо(7)'... | DmitriyDog/WEB | Rate.py | Rate.py | py | 714 | python | ru | code | 0 | github-code | 6 |
27215234475 | import os
import sys
import click
import pytest
from click.exceptions import ClickException
CONTEXT_SETTINGS = dict(
help_option_names=['-h', '--help']
)
class _CustomClickException(ClickException):
exit_code = 0x20
@pytest.fixture()
def cli1():
@click.command('cli1', help='CLI-1 example', context_set... | HansBug/hbutils | test/testing/simulate/conftest.py | conftest.py | py | 955 | python | en | code | 7 | github-code | 6 |
39712277768 | import json
import sqlite3
from sqlite3 import Error
import requests
from lxml import html
def get_popular_drinks():
url = 'https://www.esquire.com/food-drink/drinks/a30246954/best-alcohol-bottles-2019/'
page = requests.get(url)
tree = html.fromstring(page.content)
alcohol = tree.xpath('/... | advaa123/cocktailcloset | models/basic.py | basic.py | py | 4,432 | python | en | code | 0 | github-code | 6 |
2908367696 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union
from httpx import AsyncClient
from supertokens_python.recipe.thirdparty.provider import Provider
from supertokens_python.recipe.thirdparty.types import (
AccessTokenAPI, AuthorisationRedirectAPI, UserInfo, UserIn... | starbillion/supertokens_python | supertokens_python/recipe/thirdparty/providers/github.py | github.py | py | 3,505 | python | en | code | 0 | github-code | 6 |
26898344474 | # Autor: David Martínez Acha
# Fecha: 04/02/2023 14:30
# Descripción: Permite cargar datasets
# Version: 1.2
from os.path import isfile
import numpy as np
import pandas as pd
from pandas import DataFrame
from pandas.api import types
from scipy.io import arff
from algoritmos.utilidades.filetype import Fi... | dma1004/TFG-SemiSupervisado | algoritmos/utilidades/datasetloader.py | datasetloader.py | py | 4,948 | python | es | code | 5 | github-code | 6 |
43491211360 | from rest_framework.serializers import ModelSerializer, SlugRelatedField
from products.models import (
Product,
ProductTag
)
class ProductSerializer(ModelSerializer):
'''
Make output appear as an array of strings:
"tags": ["first", "second", "third"]
Rather than an array of objects:
... | skeithtan/iris | products/serializers.py | serializers.py | py | 768 | python | en | code | 0 | github-code | 6 |
39672716054 | import fileinput
_PAIRS = {
"(": ")",
"[": "]",
"{": "}",
"<": ">",
}
_POINTS = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
class Stack(list):
push = list.append
def solve(input_file):
points = 0
for line in input_file:
# incomplete lines will return 0
... | cmatsuoka/aoc | 2021 - submarine/10 - syntax checker/solution1.py | solution1.py | py | 804 | python | en | code | 0 | github-code | 6 |
3480622108 | from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from .quant_func import fix_quant as quant
### ==============================================================================###
### quant for different data types ###
###... | jmluu/ICAIS_ML.Pytorch | Quantization/modules/qlayers.py | qlayers.py | py | 14,252 | python | en | code | 3 | github-code | 6 |
22853413046 | class Solution(object):
#Method 1: Solve by removing closed pair one by one
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pre = None
while s and pre != s:
pre = s
s = s.replace('()', '').replace('[]', '').replace('{}', '')
... | yuweishi/LeetCode | Algorithms/Valid Parentheses/solution.py | solution.py | py | 765 | python | en | code | 0 | github-code | 6 |
3975243099 | # -*- coding:utf-8 -*-
import torchvision
import torch.nn as nn
# def load_model(pretrained=True, num_classes=None):
# """加载model
# Parameters
# pretrained: bool
# True: 加载预训练模型; False: 加载未训练模型
# num_classes: int
# Alexnet最后一层输出
# Returns
# alexnet_model: model
... | ray0809/pytorch | retrieval/DeepHash/DSDH_PyTorch/models/alexnet.py | alexnet.py | py | 1,578 | python | en | code | 0 | github-code | 6 |
9273208977 | from flask import Flask, render_template, request
import joblib
import numpy as np
import pandas as pd
app = Flask(__name__)
# Load your model here
model = joblib.load('C:/Users/Dylan/exoplanets/models/exoplanet_classifier.joblib')
@app.route('/', methods=['GET', 'POST'])
def home():
prediction = Non... | DylanBerger/ExoplanetClassifier | app.py | app.py | py | 1,739 | python | en | code | 0 | github-code | 6 |
35743742294 | import sys
import pandas as pd
import numpy as np
import gzip
import read_write as rw
import LDA as lda
'''
finput_title = "Data/title"
finput_description = "Data/description"
finput_train_item_id = "Data/train_item_id"
finput_test_item_id = "Data/test_item_id"
foutput_title_similarity = "Data/title_simila... | clamli/Dissertation | Step1-Preprocessing/item_similarity.py | item_similarity.py | py | 3,185 | python | en | code | 28 | github-code | 6 |
30296220599 | # -*- encoding: utf-8 -*-
'''
@File : alien.py
@Time : 2021/10/25 23:48:17
@Author : James
@Version : 1.0
@Desc : 外星人类
'''
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
'''表示单个外星人'''
def __init__(self, ai_game):
'''初始化外星人并设置其初始位置'''
super().__init__()... | heisenberg000/python_practice | alien_invasion/alien.py | alien.py | py | 830 | python | zh | code | 0 | github-code | 6 |
37626769194 | import sys
from vmc import vmcCrawl
from clean import cleaner
from stow import stower
from stow import stow4me
from logWrite import logWriter
logName = ""
if sys.argv[1] == "clean":
print("Cleaning all Log diver txt files.")
cleaner(0)
if sys.argv[1] == "nuke":
print("Nuclear Option Activated...")
pr... | MThicklin/Veeam-LogDiver | logdiver.py | logdiver.py | py | 807 | python | en | code | 5 | github-code | 6 |
4785215660 | from collections import deque,defaultdict
n,m = map(int,input().split())
d = defaultdict(list)
for i in range(m):
u,v = map(int,input().split())
d[u].append(v)
d[v].append(u)
visited = [0]*n
ans = 0
for i in range(1,n+1):
if visited[i-1] == 1:
continue
q = deque()
q.append(i)
visited... | K5h1n0/compe_prog_new | VirtualContest/022/06.py | 06.py | py | 541 | python | en | code | 0 | github-code | 6 |
53220412 | from datetime import date
from zohocrmsdk.src.com.zoho.api.authenticator import OAuthToken
from zohocrmsdk.src.com.zoho.crm.api import Initializer
from zohocrmsdk.src.com.zoho.crm.api.dc import USDataCenter
from zohocrmsdk.src.com.zoho.crm.api.record import RecordOperations, ConvertBodyWrapper, LeadConverter, Record, ... | zoho/zohocrm-python-sdk-5.0 | samples/records/ConvertLead.py | ConvertLead.py | py | 4,997 | python | en | code | 0 | github-code | 6 |
27713115887 | # Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
# You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d.
# Return the maximum number of events you can attend.
# 1. Sor... | jemis140/DSA_Practice | amazon-questions/maximum_number_of_events.py | maximum_number_of_events.py | py | 2,142 | python | en | code | 0 | github-code | 6 |
23907212429 | #!/usr/bin/env python
# -*- coding:utf-8 -*
import pickle
import sys
import pandas as pd
from utils.change_column_names import changeToName
from utils.feature_engineering import *
from utils.labels import *
from utils.pipelines import transformation_pipeline
from utils.strategy import Strategy
input_path = sys.argv[... | TheLohia/Sultans | myModel_demo.py | myModel_demo.py | py | 1,090 | python | en | code | 0 | github-code | 6 |
6308148292 | from halo import Halo
from codetiming import Timer
import pandas as pd
import time
import os
import requests
from mj_formatter import mailjet
from BadEmailsData import *
# Default directories where input and output data located
INPUT_DIR_NAME = 'input/'
OUTPUT_DIR_NAME = 'output/'
DV_API_KEY = '' # ... | TaPhuocHai/simple-mailjet-data-checker | mj_automation.py | mj_automation.py | py | 6,995 | python | en | code | 0 | github-code | 6 |
14542676756 | import requests as rq
from bs4 import BeautifulSoup
import json
#-------------------------------------------
#Variables a utilizar
#-------------------------------------------
iLetras = 0 # variable para recorrer arreglo letras
aLetras=[
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','ñ','o','p','q'... | CamiloFerreira/Traductor-Esp-Mapuzungun | Obtener_palabras.py | Obtener_palabras.py | py | 9,734 | python | es | code | 1 | github-code | 6 |
42510851613 | import sys, pathlib
import pytest
sys.path.insert(0,str(pathlib.Path(__file__).parent.parent.joinpath("src").resolve()))
#import pytest
from certauth2.__main__ import main
from certauth2 import CertificateAuthority, Encoding
from certauth2.creds_store import ondiskPathStore, ondiskCredentialStore
from cryptography i... | jose-pr/pypki | tests/test_certauth2.py | test_certauth2.py | py | 2,188 | python | en | code | 2 | github-code | 6 |
35848910596 | from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
import crud
import models
import schemas
from db_handler import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI(
title="FDFC Server",
version="... | chris-vill/fdfc-server | main.py | main.py | py | 2,151 | python | en | code | 0 | github-code | 6 |
9624256552 | import csv
import subprocess
from math import ceil
import os
from amazonscraper.client import Client
from aliexpress.client import AliexpressClient
from db import AmazonProduct, AliexpressProduct, EbayProduct, ProductDetail, create_session
def amazon_transformer(product: dict) -> dict:
arg_transform = {
... | Solda1219/aliexpress-proxy-change-scrape-request | s3scraper/utils.py | utils.py | py | 8,491 | python | en | code | 0 | github-code | 6 |
22550276830 | #!/usr/bin/env python3
import argparse
import logging
import rdflib
import rdflib_util as ru
import re
import sys
# Implementation of "list study group members" query directly in Python using
# rdflib API calls.
# ------------------------------------------------------
# main()
# ------------------------------------... | dcppc/crosscut-metadata | sparql/v0.5/rdflib_list_study_group_members.py | rdflib_list_study_group_members.py | py | 8,716 | python | en | code | 7 | github-code | 6 |
21342569046 | import socket
import os
import subprocess
client_socket = socket.socket()
host = "10.228.164.122" # paste your server IP address
port = 9999
client_socket.connect((host, port))
while True:
data = str(client_socket.recv(1024), "utf-8")
print(data, end=" ")
| aniruddhamalkar/Simple-singledirection-Python3-Sockets | basicstringtransferclient.py | basicstringtransferclient.py | py | 269 | python | en | code | 0 | github-code | 6 |
26039871256 | from __future__ import annotations
import dataclasses
import hashlib
import os.path
from collections import deque
from dataclasses import dataclass
from pathlib import PurePath
from typing import Iterable, Mapping
from pants.backend.go.util_rules import cgo, coverage
from pants.backend.go.util_rules.assembly import (... | pantsbuild/pants | src/python/pants/backend/go/util_rules/build_pkg.py | build_pkg.py | py | 38,872 | python | en | code | 2,896 | github-code | 6 |
27280445528 | from aiogram import types
from aiogram.dispatcher.filters import BoundFilter
import config
import dispatcher
class IsOwnerFilter(BoundFilter):
"""
Custom filter "is_owner".
"""
key = "is_owner"
def __init__(self, is_owner):
self.is_owner = is_owner
async def check(self, message: type... | YarikATM/Metall | tg_bot/filters.py | filters.py | py | 819 | python | en | code | 0 | github-code | 6 |
3372040192 | import jieba
from os import path
import os
from wordcloud import WordCloud
def jieba_processing_txt(text, user_dict=[]):
for word in user_dict:
jieba.add_word(word)
mywordlist = []
seg_list = jieba.cut(text, cut_all=False)
liststr = "/ ".join(seg_list)
for myword in liststr... | gewas/VChaCha | wc.py | wc.py | py | 877 | python | en | code | 1 | github-code | 6 |
43417946445 | import cv2
import matplotlib.pyplot as plt
import pandas as pd
img1_path = 'U14.png'
csv_path = 'colours.csv'
img2 = cv2.imread(img1_path)
img2 = cv2.resize(img2, (800, 600))
plt.figure(figsize=(20, 8))
plt.imshow(img2)
grid_RGB = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(20, 8))
pl... | AnupCloud/Color_Detection | color_detection.py | color_detection.py | py | 1,604 | python | en | code | 0 | github-code | 6 |
39932475902 | import argparse
import requests
from tabulate import tabulate
def make_api_request(query, filters, page, pagesize):
url = 'http://localhost:3000/log/search'
data = {
'query': query,
'filters': filters,
'page': page,
'pageSize': pagesize
}
response = requests.post(url, ... | harikrishnanum/LogQube | cli/search.py | search.py | py | 2,041 | python | en | code | 0 | github-code | 6 |
22330842884 | import numpy as np
import matplotlib, gc
import matplotlib.pyplot as plt
from tensorflow import gradients
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops, math_ops
def hessian_vector_product(ys, xs, v):
""" Multiply the Hessian of `ys` wrt `xs` by `v` """
# Validate t... | jasjeetIM/AdversarialDetector | models/util.py | util.py | py | 4,254 | python | en | code | 1 | github-code | 6 |
31165098736 | from torch.utils.data import Dataset, DataLoader
from albumentations.pytorch import ToTensorV2
from augmix import RandomAugMix
from utils import in_colab
import albumentations as A
import torchvision.io as io
import pytorch_lightning as pl
import torch
import cv2
def get_default_transforms(img_size):
transform = ... | mtenenholtz/petfinder-pawpularity-score | dataset.py | dataset.py | py | 4,274 | python | en | code | 3 | github-code | 6 |
7967036430 | """aiohttp-based client to retrieve web pages.
"""
import asyncio
from contextlib import closing
import time
import aiohttp
async def fetch_page(session, host, port=8000, wait=0):
"""Get one page.
"""
url = '{}:{}/{}'.format(host, port, wait)
with aiohttp.Timeout(10):
async with session.get(... | asyncio-docs/asyncio-doc | examples/aiohttp_client.py | aiohttp_client.py | py | 1,359 | python | en | code | 196 | github-code | 6 |
16578681384 | """
"""
import csv
class Input:
def __init__(self):
self.users = {}
class User:
def __init__(self):
self.months = {}
class Month:
def __init__(self):
self.dates = {}
self.minBalance = float("inf") # to be converted to int
self.maxBalance = float("-inf") # to... | KaiserZZK/CSV-Assistant | ver1/util.py | util.py | py | 3,725 | python | en | code | 0 | github-code | 6 |
36849230183 | from google.cloud import bigquery
import pandas as pd
import os
def ReadAlreadyProcessedData():
vAR_client = bigquery.Client()
vAR_table_name = "DMV_ELP_GPT4_RECOMMENDATION"
vAR_sql =(
"select REQUEST_ID,REQUEST_DATE,ORDER_CONFIGURATION,ORDER_PAYMENT_DATE from `"+ os.environ["GCP_PROJECT_ID"]+"."+... | Deepsphere-AI/https-github.com-Deepsphere-AI-DMV_ELP_GPT4_Recommendation | DMV_Bigquery_Utility.py | DMV_Bigquery_Utility.py | py | 454 | python | en | code | 0 | github-code | 6 |
11890054314 | import math
L,R = map(int,input().split())
count = 0
for i in range(L,R+1):
if math.sqrt(i) == int(math.sqrt(i)):
count+=1
if count > 0:
print(count)
else:
print(-1)
| syedjaveed18/codekata-problems | Arrays/Q121.py | Q121.py | py | 187 | python | en | code | 0 | github-code | 6 |
43095853918 | from tython.main import run
from colorama import init
init(autoreset=True)
while True:
text = input("> ")
if text.strip() == "":
continue
result, error = run("<stdin>", text)
if error:
print(f"\033[31merror \033[0m" + f"{error}")
elif result:
if len(result.elements) == 1:... | traceover/tython | shell.py | shell.py | py | 411 | python | en | code | 0 | github-code | 6 |
31192442591 | """
Created on Fri Mar 4 19:28:46 2022
@author: Miguel
"""
from _legacy.exe_isotopeChain_taurus import DataTaurus
class Template:
com = 'com'
z = 'z'
a = 'a'
seed = 'seed'
b20 = 'b20'
varN2 = 'varN2'
iterartions = 'iters'
hamil = 'interaction'
TEMPLATE = """NUCLEUS {a... | migueldelafuente1/taurus_tools | _legacy/exe_q20pes_axial.py | exe_q20pes_axial.py | py | 33,646 | python | en | code | 1 | github-code | 6 |
7438419042 | """Module containing class `Settings`."""
from vesper.util.bunch import Bunch
import vesper.util.os_utils as os_utils
import vesper.util.yaml_utils as yaml_utils
class Settings(Bunch):
"""
Collection of software configuration settings.
A *setting* has a *name* and a *value*. The name must be a... | HaroldMills/Vesper | vesper/util/settings.py | settings.py | py | 2,132 | python | en | code | 47 | github-code | 6 |
4787539776 | # -*- coding: utf-8 -*
import sys
import re
import unicodedata
from Table import Table
import settings
reload(sys)
sys.setdefaultencoding("utf-8")
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\03... | rupinder1133/ln2sqlmodule | ln2sqlmodule/Database.py | Database.py | py | 4,930 | python | en | code | 16 | github-code | 6 |
40290816138 | """
Purpose : Find Half-Life of C14
Author : Vivek T S
Date : 04/11/2018
"""
import matplotlib.pyplot as pyplot
def halfLifeC14(originalAmount, dt):
k = -0.000121
c14amount = originalAmount
time = 0
while c14amount > originalAmount * 0.5:
c14amount = c14amount + ( k * c14amount * dt)
time = time + dt
ret... | vivekworks/learning-to-code | 4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 4/exercise443.py | exercise443.py | py | 382 | python | en | code | 0 | github-code | 6 |
74025598587 | import arcade
from src.characters.model import Player
class LuffyPlayer(Player):
life = 100
basic_attack = 5
special_attack = 15
speed = 5
def __init__(self, x, y, direction):
super().__init__()
self.x = x
self.y = y
self.direction = direction
self.animatio... | anthonykgross/One-fight | src/characters/luffy/model.py | model.py | py | 4,704 | python | en | code | 2 | github-code | 6 |
73817524986 | # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import json
import os
import re
import tests
import tests.mockbackend
import tests.utils
#################################
# 'bugzilla query' mock testing #
#################################
def test_query(run_... | python-bugzilla/python-bugzilla | tests/test_cli_query.py | test_cli_query.py | py | 7,747 | python | en | code | 120 | github-code | 6 |
12816084120 | import requests
import os
from dotenv import load_dotenv
class YaUploader:
BASE_URL = 'https://cloud-api.yandex.net/v1/disk/resources'
GET_FILES = '/files'
UPLOAD_LINK = '/upload'
def __init__(self, token) -> None:
self.token = token
def get_headers(self):
headers = {
... | SergeyMMedvedev/8_api_requests | task_2.py | task_2.py | py | 1,652 | python | en | code | 0 | github-code | 6 |
16315480908 | from dronekit import Vehicle, connect, VehicleMode, Command
import time
from pymavlink.dialects.v20 import ardupilotmega
from pymavlink import mavutil
class DKVehicle(Vehicle):
def __init__(self, connection):
print ("Connecting to vehicle on: %s" % connection)
self.vehicle = connect(connection, ba... | JarrydSteele/pythonscripts | First/dk_vehicle.py | dk_vehicle.py | py | 4,478 | python | en | code | 0 | github-code | 6 |
32466009573 | from tech_news.scraper import get_tech_news
from tech_news.analyzer.search_engine import (
search_by_title, search_by_date, search_by_tag, search_by_category)
from tech_news.analyzer.ratings import (
top_5_news, top_5_categories)
import sys
def choice_0():
amount = input("Digite quantas notícias serão bus... | janaolive/phyton_raspagem_de_dados | tech_news/menu.py | menu.py | py | 1,427 | python | pt | code | 1 | github-code | 6 |
32102918749 | def findMid(n, arr1, arr2):
if n == 1:
return arr1[0] if arr1[0] < arr2[0] else arr2[0]
s1, e1, s2, e2 = 0, n-1, 0, n-1
while s1 < e1:
mid1 = (e1-s1)//2 + s1
mid2 = (e2-s2)//2 + s2
# 元素个数为奇数,则offset=0, 元素个数为偶数, 则offset=1
offset = ((e1-s1+1) & 1) ^1
if arr1[mid... | Eleanoryuyuyu/LeetCode | 程序员代码面试指南/二分查找/在两个长度相等的排序数组中找到上中位数.py | 在两个长度相等的排序数组中找到上中位数.py | py | 712 | python | en | code | 3 | github-code | 6 |
69887984508 | import nltk
import gensim
import cleantext
import re
import xlrd
import sys
from gensim.models import word2vec
from data_treatment import data_treatment
from nltk.corpus import reuters
from nltk.corpus import wordnet as wn
from sklearn.externals import joblib
from nltk.stem import WordNetLemmatizer
class Synonyms_sugge... | caffe-in/TQLwriter | 后端/Synonyms_suggestion.py | Synonyms_suggestion.py | py | 7,026 | python | en | code | 0 | github-code | 6 |
30172432184 | #!/usr/bin/env python3
import io
import time
import serial
from serial.tools.list_ports import comports
class Arduino(object):
def __init__(self, port):
self.port= serial.Serial(port, 115200, timeout=0.1)
self.iow= io.TextIOWrapper(
io.BufferedRWPair(self.port, self.port, 1),
... | ComNets-Bremen/GDI-Tutorials | target/examples/21_atuino.py | 21_atuino.py | py | 2,069 | python | en | code | 0 | github-code | 6 |
12441870149 | import redis
from redis_lru import RedisLRU
from connect import connect
from models import Quote
client = redis.StrictRedis(host="localhost", port=6379, password=None)
cache = RedisLRU(client)
quotes = Quote.objects()
@cache
def find_by_name(value):
finding_quotes = []
full_name = value.spli... | DanielDDZ/web_modul_8 | MongoDB/main.py | main.py | py | 1,218 | python | en | code | 0 | github-code | 6 |
10159658078 | # 13. Input any 4 digit number and find out the sum of middle digits
number =int (input('enter a 4 digit no:'))
sum = 0
rem1 = 0
if number >= 10000:
print("you entered max no")
elif number <= 999:
print("you entered min no")
else:
while number >= 100:
rem1 = rem1 // 10
number = number//10
... | suchishree/django_assignment1 | python/looping/while loop/assignment2/demo13.py | demo13.py | py | 411 | python | en | code | 0 | github-code | 6 |
12884353742 | import pandas as pd
from constants import USERINFO
path = f"C:/Users/Asus/Desktop/solarFire/{USERINFO.NAME.replace(' ','_')}.xlsx"
df = pd.read_excel(f'{path}')
#set numeric columns
columns = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
df.columns = columns
print(df.columns)
if USERINFO.GENDER == "K":
pri... | furkancets/astro-bot | src/dataPrep.py | dataPrep.py | py | 592 | python | en | code | 0 | github-code | 6 |
13525657769 | #1bc test code against sklearn - optimizer
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from random import random, seed
import numpy as np
from sk... | gery2/FYS-STK-4155---Project-2 | Codes/1bcMLPReg2.py | 1bcMLPReg2.py | py | 3,760 | python | en | code | 0 | github-code | 6 |
1775721628 | import datetime
EXISTING_TYPES = (
(0, "Пионер"),
(1, "Педсостав"),
)
SIGN_SET = (
('dining_services+', "Дежурный в столовой"),
('activity+', "Активность"),
('salary+', "Зарплата"),
('fee+', "Гонорар"),
('purchase-', "Покупка"),
('fine-', "Штраф"),
)
SIGN_SET_ALL = (
('p2p+', "Лич... | RegSirius06/SWBM | constants/bank/forms.py | forms.py | py | 810 | python | en | code | 0 | github-code | 6 |
8318915337 | import mtools
from test.test_compiler import Toto
zones = range(1, 21) + [25]
tags = "SDT"
class Score:
def __init__(self, v, t):
self.value = v
self.tag = t
def __str__(self):
return '(%s, %s)' % (self.value, self.tag)
def init_points():
dps = [Score(2*x, "D"+str(x)) for x... | chrisliu529/euler_proj | src/p109.py | p109.py | py | 3,131 | python | en | code | 1 | github-code | 6 |
81653711 | import json
import os
from corai_util.tools.src.function_json import zip_json, unzip_json
def list_of_dicts_to_txt(parameter_options, column_size=15, file_name="config.txt"):
"""
Writes the parameter options in a formatted file, the header of the file contains the parameter names,
each following ... | Code-Cornelius/CorAI | corai_util/tools/src/function_writer.py | function_writer.py | py | 3,449 | python | en | code | 3 | github-code | 6 |
42842609252 | # This is a replacement for test/integration/inflate_tokens.sh.
# The original script had a lot of problems as described in https://app.zenhub.com/workspaces/current-sprint---engineering-615a2e9fe2abd5001befc7f9/issues/sifchain/issues/719.
# See https://www.notion.so/sifchain/TEST-TOKEN-DISTRIBUTION-PROCESS-41ad0861560... | Sifchain/sifnode | test/integration/framework/src/siftool/inflate_tokens.py | inflate_tokens.py | py | 18,307 | python | en | code | 106 | github-code | 6 |
3676061367 | a = input()
a = a.split()
k = int(a[0])
m = int(a[1])
n = 1
count = 1
while not n % m ==k:
count = count + 1
n = n * 10 + 1
print(count)
| yingziyu-llt/OI | c/Luogu/水题/U38228 签到题.py | U38228 签到题.py | py | 156 | python | en | code | 0 | github-code | 6 |
21888795134 | import time
from pyvisauto import Region
import api.api_core as api
import fleet.fleet_core as flt
import config.config_core as cfg
import nav.nav as nav
import stats.stats_core as sts
import util.kca as kca_u
from kca_enums.kcsapi_paths import KCSAPIEnum
from util.logger import Log
class FactoryCore(object):
ena... | XVs32/kcauto_custom | kcauto/factory/factory_core.py | factory_core.py | py | 8,911 | python | en | code | 5 | github-code | 6 |
4992730292 | import torch
import numpy as np
import math
import torch.nn.functional as F
import re
import nltk, json
from fairseq import pybleu, options, progress_bar, tasks, tokenizer, utils, strategies
from fairseq.meters import TimeMeter
from fairseq.strategies.strategy_utils import duplicate_encoder_out
def getSubstitutePair... | microsoft/SmartWordSuggestions | code/baselines/CMLM/updates/generate_cmlm.py | generate_cmlm.py | py | 12,369 | python | en | code | 18 | github-code | 6 |
22853474916 | class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
trie = {}
res = set()
for word in words:
self.insert(trie, word)
for i in range(len(board)):
... | yuweishi/LeetCode | Algorithms/Word Search II/solution.py | solution.py | py | 1,301 | python | en | code | 0 | github-code | 6 |
70647233789 | """
This is the simplest example of training NER (named entity recognizer).
NER is responsible for recognizing "Apple" as a 'company', "George Bush" as a 'person', and so on.
THE GOAL for training model is to recognize in text 'iPhone' as a 'GADGET' (for example), and so on.
How do we learn the model to recognizing spe... | koualsky/dev-learning | spacy/train_model/full_example.py | full_example.py | py | 4,664 | python | en | code | 0 | github-code | 6 |
36156665423 | import sys
N = 6
INFINITY = sys.maxsize
Kilometres = [[INFINITY,1,3,2,1,2],
[1,INFINITY,3,1,2,3],
[3,3,INFINITY,5,3,2],
[2,1,5,INFINITY,2,3],
[1,2,3,2,INFINITY,1],
[2,3,2,3,1,INFINITY]]
impaire = [0] * N
sousGraph = [[0] * N for i in range(N)]
co... | CSolatges/La-tournee-du-facteur | Python/HungroisC.py | HungroisC.py | py | 4,604 | python | en | code | 0 | github-code | 6 |
9437207469 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import glob
file_path_th = '.\data_processing\ex\*through_E*.csv'
file_path_cr = '.\data_processing\ex\*cross_E*.csv'
csv_1 = []
csv_2 = []
x_axis = []
th_sum = []
cr_sum = []
# through
for filename_1 in glob.glob(file_path_th, recursive=True):
... | jordan-kim/r_k_graph_fitting | src/fitting_r_k.py | fitting_r_k.py | py | 2,885 | python | en | code | 0 | github-code | 6 |
25231410593 | #! /usr/bin/env python
# encoding: utf-8
# vim: ai ts=4 sts=4 et sw=4
##
##
## @author Nadia
## nadia@gmail.com/joel@gmail.com
##
import MySQLdb
from datetime import datetime
from mako.template import Template
from creche import settings
class SysEventService:
"""Class that will be delegated with creating event... | projet2019/Creche_Parentale | creche/coreapp/service/sys_event_service.py | sys_event_service.py | py | 8,574 | python | en | code | 0 | github-code | 6 |
30984032152 |
employee_file = open("employees.txt", "a") # "w" overwrites everything, "r" read only, "a" is append
employee_file.write("\nEirin - Artist")
employee_file.close()
employee_file1 = open("employees.txt", "r")
print(employee_file1.read())
employee_file1.close()
| chrismykle/pythonBeginner | readingFiles.py | readingFiles.py | py | 270 | python | en | code | 0 | github-code | 6 |
74286055227 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 16:29:22 2019
@author: swh
"""
'''两个栈完成一个队列
队列先进先出,栈后进先出'''
class Queue:
def __init__(self):
self.stockA=[]
self.stockB=[]
def push(self, node):
self.stockA.append(node)
def pop(self):
if self.stockB==[]:
... | buptswh/coding_offer | offer9_两个栈实现一个队列.py | offer9_两个栈实现一个队列.py | py | 757 | python | en | code | 2 | github-code | 6 |
2122328128 | import stripe
from celery import task
from django.conf import settings
from users.models import Buyer
@task
def create_customer(card_token, buyer_id):
stripe.api_key = settings.STRIPE_API_KEY
buyer = Buyer.objects.get(id=buyer_id)
customer = stripe.Customer.create(
email=buyer.email,
... | HackBulgaria/Web-Development-with-Django | week11/stripe_integration/payments/tasks.py | tasks.py | py | 420 | python | en | code | 25 | github-code | 6 |
26310859237 | from hmm import ViterbiTagger, SimpleTagger
import util
DEBUG = False
def train(train_data_filename, rare_train_data_filename, hmm_model_filename, rare_words_rule):
print ('1. train hmm model')
hmm_model = ViterbiTagger(3)
hmm_model.rare_words_rule = rare_words_rule
hmm_model.train(open(train_data_f... | Tuanlase02874/HMM-Demo | src/p2.py | p2.py | py | 1,587 | python | en | code | 0 | github-code | 6 |
27618070046 | from operator import itemgetter
# ######################################## Mapper ########################################### #
class Mapper(object):
def __init__(self, mapping_m):
self.mapping_m = mapping_m
if self.mapping_m['type'] == 'packing':
self.worker_l = lambda j, w_l: self.worker_l_w_p... | mfatihaktas/deep-scheduler | mapper.py | mapper.py | py | 936 | python | en | code | 12 | github-code | 6 |
5088106926 | from global_settings import integration_host, integration_table
from pandas import DataFrame, concat
from cdapython import Q
df = DataFrame()
for i in (
Q("subject_identifier_system = 'GDC'")
.ORDER_BY("days_to_birth:-1")
.subject.run(show_sql=True, host=integration_host, table=integration_table)
.pag... | CancerDataAggregator/cda-python | tests/paging.py | paging.py | py | 417 | python | en | code | 7 | github-code | 6 |
12741310305 | import sqlite3
con = sqlite3.connect('d_students.db')
cur = con.cursor()
# Create table
#cur.execute('''CREATE TABLE s_information
#(first_name text, last_name text, course text, age real)''')
# Insert a row of data
#cur.execute("INSERT INTO s_information VALUES ('Ade','Ola','product_design', 29)")
# ... | kehindeorolade/Module_4_lesson_3 | Module_4_less_3.py | Module_4_less_3.py | py | 1,043 | 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.