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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33918027336 | import hydra
import logging
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score, StratifiedShuffleSplit
from sklearn import metrics
from joblib import load
from transformers import pipeline
logger = logging.getLogger(__name__)
def evaluate_H... | Vachonni/ChatbotWiz | src/modelling/evaluate.py | evaluate.py | py | 3,005 | python | en | code | 0 | github-code | 1 |
22497223453 | #!/usr/bin/env python3
import argparse
import sys
import shutil
from utils import utils
from typing import List
def parse_args(av: List[str]):
parser = argparse.ArgumentParser(description="Run / check clang-tidy on staged cpp files.")
parser.add_argument(
"--clang-tidy-executable", help="Specific clan... | CesiumGS/cesium-omniverse | scripts/clang_tidy.py | clang_tidy.py | py | 1,188 | python | en | code | 27 | github-code | 1 |
73042146593 | # This program returns the current weather description of a requested place.
import requests
def get_weather(city):
api_key = "6259067ceac0680e898834ae9b3e9835"
url = "http://api.openweathermap.org/data/2.5/weather?q=" \
+ city + "&appid=" + api_key + "&units=metric"
request = requests.get(url)... | JadaTijssen/Portfolio | weather.py | weather.py | py | 1,652 | python | en | code | 0 | github-code | 1 |
22051285843 | import numpy as np
import random
import math
def wieksze(a, b):
if a>b:
return a
else:
return b
def funkcja(x):
return x
def losowanie(x, y):
return x + random.random()/(random.random()+1) * (y-x)
def czyNadY(x, y):
if (y>0 and y<=funkcja(x)):
return 1... | Kernos308/MIW | monte_carlo_prostokat.py | monte_carlo_prostokat.py | py | 1,472 | python | pl | code | 0 | github-code | 1 |
14724616321 | from decimal import Decimal, getcontext
import requests
from utils.utils import get_data
from utils import config
DB_API_URL = config.DB_API_URL
async def rate(valute):
RATE_CNY = requests.get('https://www.cbr-xml-daily.ru/daily_json.js').json()
rate = RATE_CNY['Valute'][valute]['Value']/10
url = f'{DB_... | IgorOlenchuk/bot_mypoison | bot/utils/settings.py | settings.py | py | 790 | python | en | code | 1 | github-code | 1 |
14335682579 | class Solution:
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
d = {}
for i in magazine:
if d.get(i):
d[i] += 1
else:
d[i] = 1
... | DeronW/leetcode | 383.py | 383.py | py | 577 | python | en | code | 1 | github-code | 1 |
32134064982 | #GET() - Is used to request data from a specified resource. when you access a websites page your
#browser makes a get request to your api. The api will return the front end that is displayed
#in the browser
#for example - get request is printing "bye world" for us in the local host port no. 8000.
#POST() - is us... | manasvijain20/flask-project | app.py | app.py | py | 1,849 | python | en | code | 0 | github-code | 1 |
25474598848 |
"""
Picomon executable module.
This module can be executed from a command line with ``$python -m picomon`` or
from a python programme with ``picomon.__main__.run()``.
"""
import concurrent.futures
import signal
import argparse
import logging
import traceback
import sys
import os
from time import sleep
from datetim... | StrasWeb/picomon | picomon/__main__.py | __main__.py | py | 4,947 | python | en | code | 0 | github-code | 1 |
41654548036 | import numpy as np
import keras
import pandas as pd
from sklearn.model_selection import train_test_split
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPoolin... | wasi-9274/DL_Directory | DL_Projects/mnist_advanced.py | mnist_advanced.py | py | 2,351 | python | en | code | 0 | github-code | 1 |
29326716419 | from bs4 import BeautifulSoup
import requests
from csv import writer
url = "https://www.linkedin.com/jobs/search?keywords=backend&location=India&geoId=102713980&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0"
page = requests.get(url)
soup = BeautifulSoup(page.content,'html.parser')
lists = soup.f... | entrepreneur123/web-scrapping | scrap.py | scrap.py | py | 1,542 | python | en | code | 0 | github-code | 1 |
12388878470 | # asyncio实现了tcp udp ssl等协议,aiohttp是基于asyncio实现的http框架
import asyncio
from aiohttp import web
# 编写一个http服务器处理以下url
# / - 首页返回 b'<h1>Index</h1>';
# /hello/{name} - 根据 URL 参数返回文本 hello, %s!。
async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'<h1>index</h1>')
async def hello(reque... | chikchikL/pythonLearning | aiohttp_demo.py | aiohttp_demo.py | py | 969 | python | en | code | 0 | github-code | 1 |
16706436069 | import argparse
import ConfigParser
import cStringIO
import gzip
import logging
import json
import os
import sys
import traceback
import urllib
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def _init_config():
conf_parser = argparse.ArgumentParser(
description="Downloads a file from a ... | zacharyozer/curlitos | curlitos.py | curlitos.py | py | 4,486 | python | en | code | 1 | github-code | 1 |
27368861795 | import numpy
from sympy import symbols, exp, sqrt, diff, N, solve, integrate
def function(x):
return numpy.exp(-numpy.sqrt(x))
def function_symbolic():
return exp(-sqrt(symbols('x')))
# noinspection SpellCheckingInspection
def m_n_plus_one(n, a, b, func):
x = symbols('x')
extremums = solve(diff(fu... | Miralius/LabsNumericalMethods | Lab3/functions.py | functions.py | py | 1,459 | python | en | code | 0 | github-code | 1 |
1306455244 | import argparse
import glob
import os
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from params import logmel_predictions_root, emb_root, saved_models_root
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def main... | polimi-ispl/speech_reconstruction_embeddings | dataset/logmel_predictions.py | logmel_predictions.py | py | 2,750 | python | en | code | 1 | github-code | 1 |
14149292573 | import sys
sys.path.insert(0,'python')
from geo_trans import *
import numpy as np
from scipy.interpolate import griddata
from fast_rw import *
def get_coords(h,v):
mgrss = get_lon_lat(27, 5).ravel()
mgrss = np.array([(i[:5],i[-8:-4],i[-4:]) for i in mgrss]).reshape(2400,2400,3)
index = np.where(mgrss[:,:... | MarcYin/S2_MODIS | scripts/standard_mask.py | standard_mask.py | py | 792 | python | en | code | 2 | github-code | 1 |
11572477017 | from collections import deque
idx = 1
while True:
N = int(input())
if N == 0:
exit()
arr = [list(map(int, input().split())) for _ in range(N)]
cost = [[999]*N for _ in range(N)]
visited = [[False]*N for _ in range(N)]
q = deque([[0,0]])
cost[0][0] = arr[0][0]
dx = [-1, 1, 0, 0... | hyojeong00/BOJ | boj4485.py | boj4485.py | py | 796 | python | en | code | 0 | github-code | 1 |
23787043311 | import torch as th
import pandas as pd
import numpy as np
import dgl
from bipartite_graph import BipartiteGraph
#######################
# user-item Subgraph Extraction
#######################
def map_newid(df, col):
old_ids = df[col]
old_id_uniq = old_ids.unique()
id_dict = {old: new for new, old in e... | venzino-han/graph-transfer | dataset.py | dataset.py | py | 7,605 | python | en | code | 1 | github-code | 1 |
24879538563 | import pathlib
from typing import Any, Callable, NamedTuple
import pytest
from fastapi.testclient import TestClient
from starlette import status
from tests.conftest import authenticate, find_username
PROGRESS_REPORT_URL = "/progress"
def _prepare_settings_and_summary(
proposal_code: str, tmp_path: pathlib.Path... | saltastroops/salt-api | tests/integration/progress_report/test_submit_progress_report.py | test_submit_progress_report.py | py | 5,922 | python | en | code | 0 | github-code | 1 |
71835741475 | import random
import sys
import numpy
import torch
import pygad
import pygad.torchga
from nn import create_ga, create_network
import math
class Gym:
def __init__(self, w, h, left_ai, right_ai):
self.turn_i = 0
self.w = w
self.h = h
self.left_ai = left_ai
self.right_ai = r... | enchantinggg4/pytorch_experiment | src/mygym.py | mygym.py | py | 9,940 | python | en | code | 0 | github-code | 1 |
22110756450 | """ Posts Models """
#Django
from users.models import Profile
from django.contrib.auth.models import User
from django.db import models
class Post(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE)
profile=models.ForeignKey('users.Profile',on_delete=models.CASCADE)
title= models.CharField... | jjestrada2/jjestrada2.github.io | platziGram/juanjoGraming/posts/models.py | models.py | py | 576 | python | en | code | 1 | github-code | 1 |
33318878173 | import rpyc
import sys
server = "localhost"
if len(sys.argv) > 1:
if int(sys.argv[1]) > 0:
try:
conn = rpyc.connect(server, 18811)
if conn.root:
conn.root.initialize_connections(int(sys.argv[1]))
while True:
try:
remote_command = input("Input the Command:\t").lower().split(" ")
conn.... | bodias/ds2022-mini-proj-1 | ra_program_client.py | ra_program_client.py | py | 793 | python | en | code | 0 | github-code | 1 |
6884041126 | from torch import nn
import torch.nn.functional as f
class LSTM(nn.Module):
def __init__(self, in_channels, hidden_dim, n_layer, n_classes):
super(LSTM, self).__init__()
self.n_layer = n_layer
self.latent_dim = 32
self.hidden_dim = hidden_dim
self.map = nn.Linear(in_channe... | Huasheng-hou/deep-fin | src/model/LSTM.py | LSTM.py | py | 657 | python | en | code | 0 | github-code | 1 |
2333300703 | from openpyxl import Workbook
arquivo_excel = Workbook()
planilha1 = arquivo_excel.active
planilha1.title = "Relatorios"
planilha2 = arquivo_excel.create_sheet("Ganhos")
planilha1['A1'] = 'Categoria'
planilha1['B1'] = 'Valor'
planilha1['A2'] = "Restaurante"
planilha1['B2'] = 45.99
planilha2.cell(row=3, column=1, value=... | DeMouraSS/dados-detran | planilha.py | planilha.py | py | 409 | python | pt | code | 0 | github-code | 1 |
10913773933 | from flask import Flask, render_template, request
import pandas as pd
import numpy as np
app = Flask(__name__)
# Reading dataset in global scope
df = pd.read_csv("winequalityN.csv")
# This is the home page
@app.route("/")
def home():
return render_template("home.html")
# This is the page where we will load the d... | ayushraina2028/basic-machine | app.py | app.py | py | 18,393 | python | en | code | 2 | github-code | 1 |
36427808018 | from win32com.client import Dispatch
from tkinter import *
import tkinter as tk
from PIL import Image
from PIL import ImageTk
import os
import re
import random
from threading import Thread
import pythoncom
import time
stu_path = "名单.txt" # 学生名单路径
def speaker(str):
"""
语音播报
:param str: 需要播放语音的文字
"""
... | huangguifeng/callroll | rollcall.py | rollcall.py | py | 5,577 | python | zh | code | 1 | github-code | 1 |
2774942212 | from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "applifting.settings")
app = Celery("applifting")
# Using a string here means the worker will n... | ondrej-ivanko/applifting | applifting/celery.py | celery.py | py | 949 | python | en | code | 0 | github-code | 1 |
2710936445 | import os
import shlex
import subprocess
import datetime
import time
import shutil
from setuptools import setup, Extension
cwd = os.path.dirname(os.path.abspath(__file__))
def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
if shell:
cmdstring_list = cmdstring
else:
cmdstring... | caozhanhao/opqr-python | setup.py | setup.py | py | 1,983 | python | en | code | 1 | github-code | 1 |
8877029762 | """
FILE: kernelregression.py
LAST MODIFIED: 24-12-2015
DESCRIPTION: Module for Gaussian kernel regression
===============================================================================
This file is part of GIAS2. (https://bitbucket.org/jangle/gias2)
This Source Code Form is subject to the terms of the Mozilla Publ... | musculoskeletal/gias2 | src/gias2/learning/kernelregression.py | kernelregression.py | py | 5,059 | python | en | code | 0 | github-code | 1 |
71571428834 | import heapq
import sys
from typing import (
Generic,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Set,
Tuple,
TypeVar,
)
from termcolor import cprint
from aoc.utils import Coord2D, Grid
H = TypeVar(
"H",
# technically can be anything comparible but obviously python's t... | Lexicality/advent-of-code | src/aoc/y2021/day15.py | day15.py | py | 4,908 | python | en | code | 0 | github-code | 1 |
6163615912 | import os
from time import sleep, time
import sys
import threading
from threading import Thread
from _thread import interrupt_main
from signal import signal
from signal import SIGINT
lst = []
def star(s):
result = ""
for i in range(len(s)):
if (i % 3 == 2):
result += "*"
result += s... | Markit125/OS | Lab4/fork.py | fork.py | py | 677 | python | en | code | 0 | github-code | 1 |
39996367304 | import numpy as np
import pandas as pd
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
train_labels = pd.read_csv('../resources/train_labels.csv', names=['label'], head... | mokleit/text-classification-scikit | src/main/svm/find_best_svm_estimator.py | find_best_svm_estimator.py | py | 1,137 | python | en | code | 0 | github-code | 1 |
74825619552 | """
ProgramTwo.py
Implementation for programming assignment two of Artificial Intelligence.
"""
import numpy as np
import pandas as pd
from prog2.Environment import Environment
from prog2.UniformCostAgent import UniformCostAgent
__author__ = "Chris Campell"
__version__ = "9/18/2017"
def main(training_file):
df =... | campellcl/ArtificialIntelligence | prog2/ProgramTwo.py | ProgramTwo.py | py | 1,210 | python | en | code | 0 | github-code | 1 |
27496332734 |
import re
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == "__main__":
test_string = "+375 (29) 299-00-00"
match = re.search(r"^\+\d{1,3}\s\(\d{2}\)\s\d{3}\-\d{2}\-\d{2}$", test_string)
if match:
logger.info(f"Found {match.group()}")
... | akinfina-ulyana/lesson | lesson_10/classwork_01.py | classwork_01.py | py | 369 | python | en | code | 0 | github-code | 1 |
10106930125 | #!/usr/bin/python3.5
import threading
import time
class MyThread(threading.Thread):
def __init__(self,name,run_time):
super(MyThread,self).__init__()
self.name = name
self.run_time = run_time
def run(self):
print("running task:",self.name)
time.sleep(self.run_time)
... | ruoxiaojie/reptile | day02/e/1.py | 1.py | py | 517 | python | en | code | 0 | github-code | 1 |
38523258836 | import csv
import models
from operator import attrgetter
import statistics
def filter_data(columns, row):
ENERGYSTARScore = row[columns.index('ENERGYSTARScore')]
if ENERGYSTARScore == '':
return False
YearBuilt = row[columns.index('YearBuilt')]
if int(YearBuilt) < 1920:
return False
... | the-non-binary-tree/ada_data_challenge_c15 | utils.py | utils.py | py | 9,974 | python | en | code | 0 | github-code | 1 |
12855628615 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ('Arial', 16, 'normal')
class Score(Turtle):
def __init__(self):
"""
Default constructor, constructs the object during it's declaration
"""
super().__init__()
self.score = 0
self.penup()
self.c... | Mqondisi-Mavuso/Online_Courses | Udemy/100_days_python_bootcamp/Day20/score_board.py | score_board.py | py | 1,203 | python | en | code | 0 | github-code | 1 |
11358971713 | import sys
try:
x = int(input("x: "))
y = int(input("y: "))
except ValueError:
print("Erro: Invalid input")
sys.exit(1) #0: salida limpia sin errores/problemas. 1: hubo algun problema y el programa se ciera
try:
result = x / y
except ZeroDivisionError: #Si divido para cero
print("Error: Cannot... | jorgeortizc06/curso_python | functions/exceptions.py | exceptions.py | py | 383 | python | es | code | 0 | github-code | 1 |
32087619445 | import uiautomator2 as u2
import pytest
import allure
@allure.feature("测试首页")#类的主要测试部分
#@allure.environment(app_package='com.mobile.fm')# 具体Environment参数可自行设置
# @allure.environment(app_activity='com.mobile.fm.activity')
# @allure.environment(device_name='aad464')
# @allure.environment(platform_name='Android')
class ... | luoqingfu/u2demo | testcase/test_demo.py | test_demo.py | py | 2,173 | python | zh | code | 0 | github-code | 1 |
3262515470 | #!/usr/bin/env python3
import secrets
import sys
import subprocess
import argparse
import headerStruct
def calculateSizeOfTheImage(lastVirtAddr, size, SectAlignment):
mult = int((size-1) / SectAlignment) + 1
return lastVirtAddr + (SectAlignment * mult)
def generateKey(arch):
# init values
wordlength... | idrirap/projectEthHack | packer.py | packer.py | py | 13,046 | python | en | code | 1 | github-code | 1 |
3408800450 | import serial
import matplotlib
matplotlib.use('TkAgg') # MUST BE CALLED BEFORE IMPORTING plt
from matplotlib import pyplot as plt
import queue
import threading
import animation
import seaborn as sns
import numpy as np
import time
class ArduinoReader(threading.Thread):
def __init__(self, stop_event, sig, serport):... | saintnever/dualring_py | stream.py | stream.py | py | 2,949 | python | en | code | 0 | github-code | 1 |
44370675825 | # Import required libraries
import pandas as pd
from sqlalchemy import create_engine
# Load data from source into a Pandas dataframe
df = pd.read_csv('source_data.csv')
# Perform data transformation and cleaning
df = df.dropna()
df['column_name'] = df['column_name'].str.upper()
# Load data into a SQL database
engine... | Kripadhn/DataIntegration | DI-Alogorithms/Data Integration/DataIntegration.py | DataIntegration.py | py | 906 | python | en | code | 0 | github-code | 1 |
31855918986 | import requests
import re
import random
import time
from bs4 import BeautifulSoup
import bs4
from fake_useragent import UserAgent
ua = UserAgent()
books = []
discounts = []
cookie = {
"bid": "6183e2a207286",
"_gcl_au": "1.1.1678734493.1636033188",
"cid": "kypss95053",
"pd": "B4MPDFMstRRagO9wOXmP3pNPoI... | jeff-901/bookstore | data/crawl.py | crawl.py | py | 6,009 | python | en | code | 0 | github-code | 1 |
41131109007 | #Standard
import numpy as np
import cv2
import os
import copy
from PIL import Image, ImageFilter
import time
#Local files
from Utilities import make_directory, align_image, get_from_directory, save_to_directory, numericalSort
from HOG_functions import process_HOG_image, get_HOG_image
import JetsonYolo
#SCIPY and SKl... | ChrisLochhead/PhDSummerProject | PhDSummerProject/Programs/image_processing/ImageProcessor.py | ImageProcessor.py | py | 14,887 | python | en | code | 0 | github-code | 1 |
42275265359 | import random
def candy_game(num_candies, player_name):
player1_candies = 0
player2_candies = 0
turn = random.randint(1, 2)
input('\n\nPress ENTER to find out who takes the candy first\n')
if turn == 1:
print(' !!Player goes first!!')
else:
print(' !!Bot ... | MrGrmm/HomeWork-sPythonGB | Lesson5/Task1.py | Task1.py | py | 2,210 | python | en | code | 0 | github-code | 1 |
24522787900 | """Copied from cpython to ensure compatibility"""
import io
from typing import Any, Callable, Dict
BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size
class BaseStream(io.BufferedIOBase):
"""Mode-checking helper functions."""
def _check_not_closed(self):
if self.closed:
... | synodriver/python-bz3 | bz3/compression.py | compression.py | py | 5,403 | python | en | code | 5 | github-code | 1 |
42615079781 | import numpy as np
import glob
import sklearn.covariance as Covariance
def get_covariance_object(X, load=True):
if load:
covarianceDict = np.load('./profiles/covarianceDict.npy', allow_pickle=True)[()]
cov_object, mean, std = covarianceDict['cov_object'], covarianceDict['mean'], covarianceDict['std... | scarpma/SSM_segmentation_3DSlicer_module | compute_profiles_covariance.py | compute_profiles_covariance.py | py | 2,053 | python | en | code | 1 | github-code | 1 |
38979638858 | from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import FieldDoesNotExist, FieldError
from django.conf import settings
import requests
from dbproducts.models import Category, Product
from dbproducts.related_functions import symbol_removal
class Command(BaseCommand):
"... | guillaumecarru/Pur_Beurre_Website | dbproducts/management/commands/populate_db.py | populate_db.py | py | 5,396 | python | en | code | 0 | github-code | 1 |
7459112013 | import sys
sys.stdin = open("input.txt")
# sys.stdin.readline()
N = int((input()))
array = [0] + list(map(int, input().split()))
S = int(input())
students = [list(map(int, input().split())) for _ in range(S)]
for i in range(S):
sex = students[i][0]
card = students[i][1]
# 남자일 때
if sex == 1:
... | coolihans/TIL | Algorithms/boj/boj-IM/1244_스위치켜고끄기/장한나.py | 장한나.py | py | 1,460 | python | ko | code | 0 | github-code | 1 |
72703642915 | import math
import random
import sys
import importlib
#========================change variables here to modify scenario========================
path_to_folder = "C:\\Users\\LJMU\\Documents\\Felix\\OpenMATB_ScenarioCreator"
path_to_folder = "C:\\Users\\felix\\Desktop\\LJMU\\Scripts\\Python\\OpenMATB_ScenarioCreator"
#... | Zebrakopf/OpenMATB_ScenarioCreator | create_scenario.py | create_scenario.py | py | 9,599 | python | en | code | 0 | github-code | 1 |
39212073591 | #import tensorflow as tf
#import numpy as np
#import pandas as pd
#import networkx as nx
#import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
#from pathlib import Path
#import random,math,sympy
#import re,request
#from turtle import *
#import time,datetime
#import argparse
#F2:tree F3:tagbar F4:添加... | 774799513/learngit | class/t_cls.py | t_cls.py | py | 1,334 | python | en | code | 0 | github-code | 1 |
24396788397 | """ 1. List are Ordered, It is UnChangeable, It allowed Duplicates
2. List usr Round Brackets ( )
"""
mytuple = ("Mumbai","Pune","Nashik","Banglore","Delhi")
print(mytuple) # print tuple
# Output ('Mumbai', 'Pune', 'Nashik', 'Banglore', 'Delhi')
print(len(mytuple)) # length of Tupl... | harsha-rohira2/Python_Basic | tuple.py | tuple.py | py | 1,730 | python | en | code | 0 | github-code | 1 |
26237350861 | import logging
from datetime import datetime, timedelta
from typing import Dict, Optional
from synthetic.user.profile_data_update import ProfileDataUpdate
from synthetic.utils.time_utils import total_difference_seconds
logger = logging.getLogger(__name__)
class BaseVariableManager:
"""Responsible for managing a... | benshi-ai/open-synthetic-data-generator | src/synthetic/managers/base_manager.py | base_manager.py | py | 2,574 | python | en | code | 0 | github-code | 1 |
72966759394 | import json
import requests
import sys
import glance_check.exception as exc
class GlanceCheck:
def __init__(self, creds=None, imageid=None, os_image_url=None,
cacert=None, verbose=False):
self.__imageid = imageid
self.__image_url = os_image_url
self.__auth_url = creds['o... | ArdanaCLM/glance-check | glance_check/check.py | check.py | py | 4,530 | python | en | code | 0 | github-code | 1 |
70717514915 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 21:53:38 2018
@author: XPS 13 9350
"""
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result=0
nums.sort()
for i in range(0,len(nums),2):
result+=nums[i]
... | yyyyyykkk/Algorithms-and-Data-Structures | LeetCode/Array Partition I.py | Array Partition I.py | py | 340 | python | en | code | 0 | github-code | 1 |
35816981546 | import openmc
import openmc_tally_unit_converter as otuc
# loads in the statepoint file containing tallies
statepoint = openmc.StatePoint(filepath="statepoint.2.h5")
# gets one tally from the available tallies
my_tally = statepoint.get_tally(name="2_neutron_spectra")
# returns the tally with base units
result = ot... | fusion-energy/openmc_tally_unit_converter | examples/processing_cell_spectra_tally.py | processing_cell_spectra_tally.py | py | 1,235 | python | en | code | 4 | github-code | 1 |
5142368170 | import sklearn
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
data = pd.read_csv("car.data")
print(data.head())
le = preprocessing.LabelEncoder()
buying = le.fit_transform(list(data[... | Laudkyle/my-python-projects | Python Scripts/machine learning 1/knn.py | knn.py | py | 1,408 | python | en | code | 0 | github-code | 1 |
74848291234 | #!/usr/bin/env python
import os,glob
import sys
def parseMMCIF(mmcif,root):
mmcifBlock = ''
foundEvent = False
nEvent = 1
for line in open(mmcif):
if line.startswith('data_'):
if foundEvent:
writeMMCIF(root,nEvent,mmcifBlock)
nEvent += 1
... | tkrojer/PanDDA_PDB_Tools | eventMMCIF2mtz.py | eventMMCIF2mtz.py | py | 2,540 | python | en | code | 0 | github-code | 1 |
43199229342 | import bpy
from bpy.props import BoolProperty, EnumProperty
from bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_origin_3d, region_2d_to_vector_3d
from mathutils import Vector
from .. utils.registration import get_addon, get_prefs
from .. utils.tools import get_active_tool
from .. utils.object imp... | AtixCG/Universal-3D-Shortcuts | Blender/With Addons/scripts/addons/MACHIN3tools/operators/mirror.py | mirror.py | py | 28,604 | python | en | code | 38 | github-code | 1 |
30045309479 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | openstack/senlin | senlin/api/openstack/v1/webhooks.py | webhooks.py | py | 2,340 | python | en | code | 44 | github-code | 1 |
73207225634 | # N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.
# 첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다.
import sys
def sumOfNums(count, nums):
split = [num for num in nums]
num_sum = 0
for i in range(0, count):
num_sum += int(split[i])
return num_sum
count = int(sys.argv[1])
nums ... | etture/algorithms_practice | baekjoon/3.for_loop/sumOfNums_11720.py | sumOfNums_11720.py | py | 515 | python | ko | code | 0 | github-code | 1 |
6363891788 | from dataclasses import dataclass, field
from typing import Any, Iterable, List, Dict
from config import SUBJECT_PATTERNS, DAYS
@dataclass(kw_only=True)
class Pattern:
subject_type: str
classes: int
duration: int
required_rooms: List[Any] = field(init=False, default_factory=list)
def add_rooms(se... | oneku16/UCA-schedule-generator | brute_force_2/subject/pattern.py | pattern.py | py | 726 | python | en | code | 0 | github-code | 1 |
19681624663 | from PIL import Image, ImageFilter
img = Image.open('./astro.jpg')
# filtered_img = img.filter(ImageFilter.BLUR) # Blurs the image
# filtered_img = img.filter(ImageFilter.SMOOTH) # Smooth the image
# filtered_img = img.filter(ImageFilter.SHARPEN) # Sharpens the image
# filtered_img = img.convert('L') # converts t... | Yeshwanth37/ImageProcessing | Image.py | Image.py | py | 687 | python | en | code | 0 | github-code | 1 |
36976683687 | """
Erase all .git from a folder and subfolder
"""
import os
import shutil
def eraseAllGit(strPath = "./"):
#~ print("INF: scanning '%s'" % strPath )
nNbrDeletedFolder = 0
if strPath[-1] != '/':
strPath += '/'
li = os.listdir(strPath)
for f in li:
absf = strPath + f
if os.pa... | alexandre-mazel/electronoos | scripts/delete_git.py | delete_git.py | py | 1,056 | python | en | code | 2 | github-code | 1 |
8362112734 | # ---------------------------
# Problem 2
# Given an array of integers, return a new array such that each element at index i of the new array is the
# product of all the numbers in the original array except the one at i.
#
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 2... | dmallory42/daily-coding-problem-solutions | problem_002.py | problem_002.py | py | 1,104 | python | en | code | 0 | github-code | 1 |
122136937 | import sys
sys.path.append('../')
from pde_utility import plot_PDE_solutions, plot_fields, split_data, expand_dataset, exe_cmd, BatchData, plot_one_field_hist, plot_one_field_stat, plot_one_field,plot_PDE_solutions_new
import tensorflow as tf
import numpy as np
class BatchData(tf.keras.utils.Sequence):
"""Produce... | zxx2643/nn-pde-solver | src/Example3_nonlinear_elasticity/test_batch.py | test_batch.py | py | 2,842 | python | en | code | 2 | github-code | 1 |
11101974490 | #!/usr/bin/env python
import json
import csv
import re
import math
from pprint import pprint
CURRENT_SOURCE_PATTERN = re.compile('^i', re.I)
INDUCTOR_PATTERN = re.compile('^l', re.I)
PULSE_PATTERN = re.compile('^pulse', re.I)
POSITION_PATTERN = re.compile(r'\An|_n', re.I)
TIME_PATTERN = re.compile(r'^\.tran', re.I)
... | tshaffe1/noisemapper | noisemapper.py | noisemapper.py | py | 11,790 | python | en | code | 0 | github-code | 1 |
1168928910 | import cv2
import keras
camera = cv2.VideoCapture(0)
haar = cv2.CascadeClassifier('cascades/haarcascade_frontalface_alt2.xml')
model = keras.models.load_model('gender/InceptionResNetV2/weights/inception_gender.h5')
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
while True:
... | imdeepmind/age-gender-prediction | detect.py | detect.py | py | 1,388 | python | en | code | 0 | github-code | 1 |
11828045754 | class SubrectangleQueries(object):
def __init__(self, rectangle):
"""
:type rectangle: List[List[int]]
"""
self.rectangle = rectangle
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
"""
:type row1: int
:type col1: int
:type row2:... | zhangliukun/data-structure | src/python/test2.py | test2.py | py | 1,621 | python | en | code | 2 | github-code | 1 |
33845405230 | #-*- coding: utf-8 -*-
import pyqtgraph as pg
from DateAxis import DateAxis
from TableModel import TableModel
from PyQt4.QtGui import *
from PyQt4 import uic
class LogView(QTableView):
def __init__(self, graphicLayout, layoutRow = 0, layoutCol = 0):
super().__init__()
self.view = graphi... | turlvo/KuKuLogAnalyzer | LogView.py | LogView.py | py | 3,684 | python | en | code | 1 | github-code | 1 |
27393973025 | # --- Bibliothèques utilisées ---
from functools import partial
import tkinter as tk
from random import seed
from random import randint
# --- Préparation du jeu ---
def diff_size(diff):
"""
sert à déterminer le nombre de cases du jeu
entrées : diff (difficulté) avec trois valeurs possib... | Claripouet/demineur | démineur_final.py | démineur_final.py | py | 10,371 | python | fr | code | 0 | github-code | 1 |
25654546309 | import uvicorn
from fastapi import FastAPI, Request, status
from fastapi.openapi.utils import get_openapi
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.v1.routers.facts import v1_router
from config import NA... | DucNgn/Dog-Facts-API-v2 | app/main.py | main.py | py | 1,763 | python | en | code | 6 | github-code | 1 |
8487302649 | power_list=list(map(int,input("enter the list elements: ").rstrip().split())) # please enter next element in same row after one space
max_power=max(power_list)
a=[]
min_power=0
check_lenght=0
c=0
while True:
if check_lenght==0:
a.append(max_power)
min_power=min(power_list)
print(min_power, m... | sheetal101/Pokemon_Project | pokeman.py | pokeman.py | py | 689 | python | en | code | 0 | github-code | 1 |
34842375810 | # Remove Linked List Elements: https://leetcode.com/problems/remove-linked-list-elements/
# Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, ... | KevinKnott/Coding-Review | Month 02/Week 03/Day 01/b.py | b.py | py | 1,488 | python | en | code | 0 | github-code | 1 |
7420566826 | from django.contrib.auth import get_user_model
from django.test import TestCase
from posts.models import Group, Post
User = get_user_model()
class TestGroupModel(TestCase):
@classmethod
def setUpTestData(cls):
cls.group = Group.objects.create(
title="Тестовый Заголовок",
slug... | VaSeWS/hw05_final | yatube/posts/tests/test_models.py | test_models.py | py | 2,456 | python | ru | code | 0 | github-code | 1 |
5126090976 | import os
class FilePathTester:
def __init__(self):
self.paths = []
self.incorrectPaths = []
def addPath(self, path):
path = path.strip()
if path == '':
raise ValueError('Пустая строка!')
if os.path.exists(path):
self.paths.append(p... | joonmeow/TPO3 | FilePathTester.py | FilePathTester.py | py | 1,464 | python | en | code | 0 | github-code | 1 |
1603872328 | """
trainvalsplit.py is a script that splits an MS COCO formatted dataset into train and val partitions.
For sample usage, run from command line:
Example:
python trainvalsplit.py --help
"""
import random
from pathlib import Path
from typing import Any, List, Tuple
import numpy as np
from .class_dist import CocoC... | GiscardBiamby/cocobetter | PythonAPI/pycocotools/helpers/splits.py | splits.py | py | 4,977 | python | en | code | 0 | github-code | 1 |
74118503392 |
nota1 = float(input('Primeira Nota: '))
nota2 = float(input('Segunda Nota: '))
media = (nota1 + nota2) / 2
print('Tirando {:.1f} e {:.1f}, a média do aluno é {:.1f}'.format(nota1, nota2, media))
if media >= 7:
print('O aluno está APROVADO.')
# Maneira como fiz -> elif media >= 5.0 and media <= 6.9: Abaixo a versão ma... | joaovicentefs/cursopymundo2 | exercicios/ex0040.py | ex0040.py | py | 468 | python | pt | code | 0 | github-code | 1 |
7459114703 | num_switch = int(input())
switch = list(map(int,input().split()))
num_students = int(input())
students = [list(map(int,input().split())) for _ in range(num_students)]
for student in students:
if student[0] == 1: # 남자
for i in range(len(switch)):
if (i+1) % student[1] == 0:
swit... | coolihans/TIL | Algorithms/boj/boj-IM/1244_스위치켜고끄기/지수경.py | 지수경.py | py | 787 | python | en | code | 0 | github-code | 1 |
2760383933 | # This file contains the main class to run the model
import os
import math
from tensorflow.keras.callbacks import LambdaCallback
import numpy as np
import time
import matplotlib.pyplot as plt
# generate samples and save as a plot and save the model
def summarize_performance(step, g_model, c_model, dataset, n_samples=1... | AKI-maggie/thesis | main.py | main.py | py | 6,229 | python | en | code | 1 | github-code | 1 |
17884064271 | from ansiblereview import Standard, Result, Error, lintcheck
from ansiblereview.groupvars import same_variable_defined_in_competing_groups
def check_fail(candidate, settings):
return Result(candidate,[Error(1, "test failed")])
def check_success(candidate, settings):
return Result(candidate)
test_task_ansib... | willthames/ansible-review | test/standards/standards.py | standards.py | py | 1,391 | python | en | code | 223 | github-code | 1 |
23869946516 | # from collections import defaultdict
def checkPrime(n):
"""
Check if a number is prime.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
for i in range(2, n // 2):
if n % i == 0:
return False
return ... | pupperemeritus/dsa-and-daa | hashtable.py | hashtable.py | py | 1,766 | python | en | code | 0 | github-code | 1 |
25509598261 | class Coche:
def __init__(self, color, marca, modelo):
self.color = color
self.marca = marca
self.modelo = modelo
class Gato:
num_patas = 4
orejas = 2
nombres = []
def __init__(self, nombre):
self.nombre = nombre
self.nombres.append(nombre)
if __name__ ==... | Marcombo/python-a-fondo | Capitulo_4/primeras_clases.py | primeras_clases.py | py | 631 | python | es | code | 86 | github-code | 1 |
34013403804 | '''
Standard sliding window problem
- Increase window until repeating character (window size > len(dict))
- Shrink window until no repeating characters (above condition false)
- Update global max
O(n) time
O(k) --> O(1) Space. K is number of distint characters. So worst case O(26) -> O(1)
'''
class So... | kjingers/Leetcode | Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.py | LongestSubstringWithoutRepeatingCharacters.py | py | 1,114 | python | en | code | 0 | github-code | 1 |
21513980032 | import json
from scrapy import Selector
import requests
import re
headers = {
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua-mobile": "?0",
"x-requested-with": "XMLHttpRequest",
'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Geck... | petr777/pp | flask_app/vk_app/posts.py | posts.py | py | 1,845 | python | en | code | 0 | github-code | 1 |
14920841148 | """
> Extremely Simple Image file format <
>------------------------------------------------------------------------------------------<
> Designed for databending or glitching
> Has very little fancy features that could cause problems with decoding
> Decoder is desi... | AlexPoulsen/esi | esi_to_png.py | esi_to_png.py | py | 5,823 | python | en | code | 1 | github-code | 1 |
10598075622 | # encoding: utf-8
# module Siemens.Engineering.HmiUnified.HmiAlarm.HmiAlarmCommon calls itself HmiAlarmCommon
# from Siemens.Engineering, Version=15.1.0.0, Culture=neutral, PublicKeyToken=d29ec89bac048f84
# by generator 1.145
# no doc
# no imports
# no functions
# classes
from Siemens.Engineering import IEngineeringO... | Repsay/tia-openness-api-client | typings/Siemens/Engineering/HmiUnified/HmiAlarm/HmiAlarmCommon.pyi | HmiAlarmCommon.pyi | pyi | 7,140 | python | en | code | 3 | github-code | 1 |
2951008188 | import sys
import time
n, q = map(int, sys.stdin.readline().split())
a = int(input())
b = int(input())
start = time.time()
c = a+b
a_l = [0]*n
b_l = [0]*n
c_l = [0]*(n+1)
c2_l = [0]*(n+1)
count = [0] * q
f_l = [0] * q
i_int = [0] * q
d_l = [0] * q
def func1(k_str, k_l): #리스트로 변환
for j in range(1,len(k_str)+1):
... | hjonghyeok/baekjun | 22873.py | 22873.py | py | 1,849 | python | en | code | 0 | github-code | 1 |
45290876502 | # -*- coding: utf-8 -*-
import re
import markdown
from markdown.treeprocessors import Treeprocessor
from tina.front.templatetags.functions import resolve
class TargetBlankLinkExtension(markdown.Extension):
"""An extension that add target="_blank" to all external links."""
def extendMarkdown(self, md):
... | phamhongnhung2501/Taiga.Tina | fwork-backend/tina/mdrender/extensions/target_link.py | target_link.py | py | 879 | python | en | code | 0 | github-code | 1 |
12158969726 | from unittest import TestCase, mock
from matplotlib import animation, pyplot as plt
from src.chinese_checkers.game.ChineseCheckersGame import ChineseCheckersGame
from src.chinese_checkers.simulation.GameSimulationAnimation import GameSimulationAnimation
from src.chinese_checkers.simulation.GameSimulation import GameS... | dakotacolorado/ChineseCheckersGameEngine | tests/chinese_checkers/simulation/test_GameSimulationAnimation.py | test_GameSimulationAnimation.py | py | 2,113 | python | en | code | 0 | github-code | 1 |
33501639542 | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Optimizer
import scipy.io
from Bayesian_DL.BPINN.VI.src.utils import log_gaussian_loss, gaussian, get_kl_Gaussian_divergence
from torch.utils.tensorboard... | SoloChe/BPINN | VI/KdV_identification.py | KdV_identification.py | py | 13,494 | python | en | code | 0 | github-code | 1 |
27134713335 | maior, menor, mulher, homem, cont, media = 0, 0, 0, 0, 0, 0
idoso, jovem = '', ''
for i in range(3):
print('---- {}º Pessoa ----'.format(i+1))
nome = input('Nome: ').strip().capitalize()
idade = int(input('Idade: '))
sexo = input('Sexo (M/F): ').strip().upper()
if i == 0:
maior = idade
... | weskleyM/Python | Loops/for/Analisador.py | Analisador.py | py | 1,105 | python | pt | code | 0 | github-code | 1 |
4752374660 | import os
import openai
openai.api_key = ""
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0,
)
return response.choices[0].message["content... | yeonieheoo/MemoryCompanion | ML4H_LLM/case90.py | case90.py | py | 2,539 | python | en | code | 0 | github-code | 1 |
43464527814 | import easyocr
import cv2
import matplotlib.pyplot as plt
import re
import unidecode
from datetime import datetime
import numpy as np
import math
import os
import json
from difflib import SequenceMatcher
from itertools import combinations
READER = easyocr.Reader(['vi'])
json_path = "data/vn_administrative_location.j... | tungedng2710/TonEKYC | utils/ocr_utils.py | ocr_utils.py | py | 5,405 | python | en | code | 2 | github-code | 1 |
72689147554 | #coding: utf-8
__author__ = "Lário dos Santos Diniz"
from django.contrib import admin
from .models import (RPGSystem)
class RPGSystemAdmin(admin.ModelAdmin):
list_display = ['name', 'description', 'site']
search_fields = ['name', 'description', 'site']
admin.site.register(RPGSystem, RPGSystemAdmin) | lariodiniz/minhaMesaRPG | api/admin.py | admin.py | py | 314 | python | en | code | 0 | github-code | 1 |
647601614 | import json
import re
from konlpy.tag import Twitter
from collections import Counter
import pytagcloud
import webbrowser
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
def showGraph(wordInfo) :
font_location = "C:\Windows\Fonts\malgun.ttf"
font_name = font_manager.Fo... | Gyeo1/Project | Iot-인공지능-빅데이터(크롤링,워드클라우드)/2.워드클라우드.py | 2.워드클라우드.py | py | 1,933 | python | en | code | 1 | github-code | 1 |
33095247618 | import solution
class Solution(solution.Solution):
def solve(self, test_input=None):
return self.findLongestChain(test_input)
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=lambda x:x[1])
length = 0
... | QuBenhao/LeetCode | problems/646/solution.py | solution.py | py | 523 | python | en | code | 8 | github-code | 1 |
16805089134 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
a_dataframe = pd.DataFrame(
{'name':['Alice','Bob','Charles'],
'age':[25, 23, 34],
'gender':['female','male','male']})
print(a_dataframe)
# new_dataframe = pd.DataFrame(np.arange(16).reshape((4,4)),
# ... | OceanicSix/Python_program | Study/external/pand/pandas_example.py | pandas_example.py | py | 973 | python | en | code | 1 | github-code | 1 |
31326029236 | # -*- coding: utf-8 -*-
### Import libraries ###
import numpy as np
import pandas as pd
from pandas import Grouper
import matplotlib.pyplot as plt
import seaborn as sns
color = sns.color_palette()
sns.set_style(style="darkgrid")
from data_utils import most_reviewed_products
from pathlib import Path
from ... | avivace/reviews-sentiment | scripts/data_exploration.py | data_exploration.py | py | 14,076 | python | en | code | 25 | github-code | 1 |
15405751223 | #!/usr/bin/env python3
"""
https://adventofcode.com/2021/day/21
"""
import collections
import itertools
import aoc
PUZZLE = aoc.Puzzle(day=21, year=2021)
def solve_b(positions):
"""Solve puzzle part b"""
rolls = collections.Counter(
sum(rolls)
for rolls in itertools.product(range(1, 4), repe... | trosine/advent-of-code | 2021/day21.py | day21.py | py | 1,970 | python | en | code | 0 | github-code | 1 |
23992806792 | import re
import time
def get_input():
num_regex = re.compile(r"^\d+(?:\.\d{,30})?$")
input_str = input("Input a decimal: ")
while num_regex.match(input_str) is None:
input_str = input("Nope, not valid. Give me another: ")
return input_str
def allocate_bits(binary):
length = len(binary)
... | KyleWardle/Python-Projects | binary.py | binary.py | py | 1,907 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.