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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20070392797 | import importlib
import sys
from unittest import mock
class MockConfig:
def __init__(self):
self.bot = mock.MagicMock()
self.state = mock.Mock()
def set_up_class(cls, *module_names):
mock_config = MockConfig()
sys.modules['config'] = mock_config
try:
for module_name in module_names:
module = importlib.im... | raylu/sbot | tests/mock_config.py | mock_config.py | py | 491 | python | en | code | 8 | github-code | 6 |
1439842893 | import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import scipy.optimize
def jj_cpr_ballistic(gamma, tau):
return np.sin(gamma) / np.sqrt(1 - tau * np.sin(gamma/2)**2)
def jj_free_energy_ballistic(gamma, tau):
return 4 / tau * (1 - np.sqrt(1 - tau * np.sin(gamma/2)**2))
# d/dγ I(γ)
def jj... | amba/JJA-solver | JJAsolver/network.py | network.py | py | 9,572 | python | en | code | 0 | github-code | 6 |
73268144828 | import tweepy
import tweeting
import argparse
from time import sleep
parser = argparse.ArgumentParser(description="Tweet news stories periodically according to global priorities.")
parser.add_argument('-dbg_mode', default=False, type=bool, nargs=1, help="Run in debug mode (default = False)")
parser.add_argument('-tw_c... | jaryaman/propNews | main.py | main.py | py | 3,030 | python | en | code | 0 | github-code | 6 |
4716246754 | # reading file name
fn = input('Enter file name: ')
# making sure user enters valid file name
try:
fh = open(fn)
except:
print('Invalid Name')
quit()
# creating dictionary & list
counts = dict()
lst = list()
# reading through the file
for ln in fh:
# finding the required line
if ln.startswith('From '):
... | sumeetkumar1/My_python_experience | P1/Scripts/10.2.py | 10.2.py | py | 827 | python | en | code | 0 | github-code | 6 |
16484232797 | # ---------------------------------------------------------------------------- #
# #
# Module: main.py #
# Author: oscarmccullough ... | odm3/PotomacPythonTemplate | src/main.py | main.py | py | 4,168 | python | en | code | 0 | github-code | 6 |
15332380058 | """
Handle photobooth configuration.
"""
import os
import sys
import logging
import yaml
class Configuration:
"""
Create configuration object.
"""
def __init__(self, file):
self.logger = logging.getLogger(__name__)
self.file = file
self._get_config()
def _get_config(self... | diablo02000/pyphotobooth | pyphotobooth/libs/configuration.py | configuration.py | py | 1,363 | python | en | code | 1 | github-code | 6 |
27318831763 | # @PascalPuchtler
# 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
# dis... | iisys-hof/autonomous-driving | car-controller/src/mainController/Controller/ObjectDetection/ObjectDetection.py | ObjectDetection.py | py | 2,582 | python | en | code | 0 | github-code | 6 |
20538778289 | # https://leetcode.com/problems/word-search-ii/
"""
Time complexity:- O(N * M * W), where N and M are the dimensions of the board and W is the total number of characters in the words.
Space Complexity:- O(W)
"""
"""
Intuition:
The findWords method uses a Trie data structure to efficiently search for words on the boar... | Amit258012/100daysofcode | Day96/word_search_2.py | word_search_2.py | py | 2,234 | python | en | code | 0 | github-code | 6 |
9297911197 | import os
# Specified path
s = input('Please input some path:')
path = "C:/Users/77718/Documents/Work/Pyhton/KBTU/"+ s
# Get list of directories present in the specified path
dirs = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
# Get list of files present in the specified path
files = [f for... | DayFay1/KBTU | TSISVI/dir-and-files/1.py | 1.py | py | 541 | python | en | code | 0 | github-code | 6 |
70129578749 | #-----------------------------------------------------------------------------------------#
import torch
import matplotlib.pyplot as plt
import deepwave
from deepwave import scalar
import numpy as np
import warnings
#-----------------------------------------------------------------------------------------#
warnings.fil... | PongthepGeo/geophysics_23 | codes/seismic/keep/test_forward.py | test_forward.py | py | 2,872 | python | en | code | 0 | github-code | 6 |
75006495547 | import os
mypath = r'\Documents\Certificates' #change to correct folder path
files = []
for r, d, f in os.walk(mypath):
for file in f:
if '.pdf' in file: # you can change this to e.g .txt, to get any text file
files.append(file.replace('_', ' ').replace('.pdf', '').title())
for f in range(len(... | djunehor/pdfs-directory | run.py | run.py | py | 363 | python | en | code | 0 | github-code | 6 |
40542696905 | from flask import Flask, request, jsonify
from flask_mail import Mail, Message
import json
import sqlalchemy
from sqlalchemy import or_,desc
from tables import db,GDPs, Impact, ImpactPredicted
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TL... | aftex261/DigitalOcean | B Sudharsan - CovInsights App/Backend Files/app.py | app.py | py | 3,625 | python | en | code | 5 | github-code | 6 |
30578248385 | import cv2
from picamera import PiCamera
from picamera.array import PiRGBArray
import time, socket, logging, configparser, argparse, sys
from utils import Utils
parser = argparse.ArgumentParser()
parser.add_argument('--d', nargs=1, default=None)
args = parser.parse_args()
APP_DIR = args.d[0] if args.d != None else ".... | petkanov/drone-raspberry-py-app | video_streamer.py | video_streamer.py | py | 2,824 | python | en | code | 2 | github-code | 6 |
11890081214 | L,R = map(int,input().split())
sum = 0
if L%2 == 0:
start = L+1
else:
start = L
for i in range(start,R+1,2):
sum = sum + i
print(sum)
| syedjaveed18/codekata-problems | Arrays/Q135.py | Q135.py | py | 156 | python | en | code | 0 | github-code | 6 |
31477418429 | #!/usr/bin/env python
import argparse
import re
import json
from os.path import isfile
def a(lines):
return len(lines)
def t(requests):
stats = {}
for dict_ in requests:
method = dict_['method']
if method not in stats.keys():
stats[method] = 0
stats[method] += 1
... | gatart/2021-1-MAILRU-SDET-Python-G-Talamanov | Homework_5/analyze.py | analyze.py | py | 4,579 | python | en | code | 0 | github-code | 6 |
3645997925 | def is_leap(year):
leap = False
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
# if the year is divisible by 400 or divisible by 4 but not by 100, it's a leap year
leap = True
return leap
year = int(input("Enter a year: "))
print(is_leap(year)) | IancuIonut/Leap_Year_Calculator | main.py | main.py | py | 290 | python | en | code | 0 | github-code | 6 |
9854004184 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import math
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
# Import the backtrader platform
import backtrader as bt
import back... | alfredopzr/backtesting-python | backtrader/strategies/GoldenCross.py | GoldenCross.py | py | 3,173 | python | en | code | 0 | github-code | 6 |
5707632801 | '''
Posts routes
/posts (args: position, amount)
/post (args: id)
'''
from flask_api import status
from flask import request
from flask import Blueprint
from service.upload_image import UploadImage
from databases.models.post import Post, PostStatus
from databases.models.photo import Photo
from deco... | Dolzhenkov-Andrii/api | routes/posts.py | posts.py | py | 3,478 | python | en | code | 0 | github-code | 6 |
25014580521 | import os
move = input("Please enter move: ")
name = input("Please enter csv name: ")
path = f'dataset/{move}/'
files = os.listdir(path)
counter = 1
for file in files:
_, ext = os.path.splitext(file)
os.rename(os.path.join(path, file), os.path.join(path, name + str(counter) + ext))
counter += 1
| ahbarari/bachelor-project | rename.py | rename.py | py | 310 | python | en | code | 0 | github-code | 6 |
40297312420 | import random
# <--->
from .board import Spawn, Player, Launch
from .helpers import find_shortcut_routes
from .logger import logger
# <--->
def defend_shipyards(agent: Player):
board = agent.board
need_help_shipyards = []
for sy in agent.shipyards:
if sy.action:
continue
in... | w9PcJLyb/kore-beta-bot | src/defense.py | defense.py | py | 2,341 | python | en | code | 10 | github-code | 6 |
72169387389 | """
One table verb initializations
"""
import itertools
from .operators import DataOperator
from .expressions import Expression
__all__ = ['define', 'create', 'sample_n', 'sample_frac', 'select',
'rename', 'distinct', 'unique', 'arrange', 'group_by',
'ungroup', 'group_indices', 'summarize',
... | has2k1/plydata | plydata/one_table_verbs.py | one_table_verbs.py | py | 34,171 | python | en | code | 271 | github-code | 6 |
18051200716 | # 1014
X = int(input())
Y = float(input())
# regra de três pra saber quantos km foram andados por litro
km_per_l = X * 1 / Y
print('%.3f' % km_per_l, 'km/l')
| lucastorres37/uriExercises | consumption.py | consumption.py | py | 165 | python | pt | code | 0 | github-code | 6 |
17625793432 | from __future__ import print_function, division
import os
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Activation
from keras.layers import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU, ReLU
from keras.models import Sequential, Model
from keras.optimizers import Adam
... | royalsalute/fraud-creditcard-detection | alphagan.py | alphagan.py | py | 12,147 | python | en | code | 1 | github-code | 6 |
16046421800 | from tkinter import *
from tkinter.messagebox import*
import sqlite3
root4=Tk()
h,w=root4.winfo_screenheight(),root4.winfo_screenwidth()
root4.geometry('%dx%d+0+0'%(w,h))
bus4=PhotoImage(file='.\\Bus_for_project.png')
Label(root4,image=bus4).grid(row=0,column=0,columnspan=12,padx=w/2.5)
Label(root4,text='... | akarshi19/Online-Bus-Booking-System | bus_route.py | bus_route.py | py | 2,568 | python | en | code | 1 | github-code | 6 |
9537972227 | """Slightly adapted code of Eric de Lange"""
import sys
import time
import os
DEFAULT= "Geen bericht, goed bericht"
CRITICAL = const(50)
ERROR = const(40)
WARNING = const(30)
INFO = const(20)
DEBUG = const(10)
NOTSET = const(0)
_level_str = {
CRITICAL: "CRITICAL",
ERROR: "ERROR",
WARNI... | emsruderer/pylontech-micropython | Src/logging.py | logging.py | py | 4,493 | python | en | code | 2 | github-code | 6 |
10916312087 | import os
import sys
import subprocess
import pandas as pd
import numpy as np
import logging
def vvpkg(out, err, pool):
df1 = pd.read_csv(out, header = None, sep =']')
df2 = pd.read_csv(err, header = None)
df1 = df1.values[0]
df2 = df2.values[0]
hashes = list()
offsets = [0]
sizes = list()
... | depaul-dice/CDMT | experiment7/experiment7.py | experiment7.py | py | 5,491 | python | en | code | 0 | github-code | 6 |
32017653936 | import socket
HOST = 'localhost'
PORT = 8080
def send_coins(amount):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((HOST, PORT))
client_socket.sendall(str(amount).encode())
print(f'Sent coins: {amount}')
if __name__ == '__main__':
amoun... | SibinThomasQuad/PYTHON_COIN_TRANSFER | sender.py | sender.py | py | 383 | python | en | code | 0 | github-code | 6 |
73510537787 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
first i should cop
the problem is i have to add the value if t
"""
copy =[]
l=0
for i in range(len(arr)):
if arr[i]==... | yonaSisay/a2sv-competitive-programming | 1089-duplicate-zeros/1089-duplicate-zeros.py | 1089-duplicate-zeros.py | py | 510 | python | en | code | 0 | github-code | 6 |
73484336507 | import mc_package.sleep_periods as sleep_periods
import pandas as pd
MS_PER_DAY = 1000*60*60*24
MS_PER_HOUR = 1000*60*60
def sleep_duration(part_id, start, end):
sleep_res = sleep_periods.sleep_periods(part_id, start=start, end=end)
if sleep_res is None:
return None
res = sleep_periods.sleep_period... | carlan1/mc_package | sleep_duration.py | sleep_duration.py | py | 943 | python | en | code | 0 | github-code | 6 |
36849582573 | import os
os.chdir("/home/ghiggi/Projects/deepsphere-weather")
import sys
sys.path.append("../")
import shutil
import argparse
import dask
import glob
import time
import torch
import zarr
import numpy as np
import xarray as xr
## DeepSphere-Weather
from modules.utils_config import read_config_file
from modules.utils... | deepsphere/deepsphere-weather | dev/w_debug_predictions.py | w_debug_predictions.py | py | 15,927 | python | en | code | 56 | github-code | 6 |
15551615128 | import pandas as pd
class MalformedFileFormat(Exception):
pass
def get_ratings(file):
ratings = []
with open(file, "r") as fd:
try:
raw = fd.readline().strip()
while raw:
movie_id, rating, *_ = raw.split(",")
ratings.append((int(movie_id), ... | lukaszmichalskii/recommender-system | src/application/files_operations.py | files_operations.py | py | 3,122 | python | en | code | 0 | github-code | 6 |
12657059462 | # level: medium
# 思路:dfs 将节点设为子树和,统计出现最多的字数和
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import defaultdict
class Solution(object):
nodes = defaultdict(int)
def findF... | PouringRain/leetcode | 508.py | 508.py | py | 1,214 | python | en | code | 1 | github-code | 6 |
36884065642 | #!/usr/bin/python3
"""
Module for Base class
"""
import json
class Base:
""" Base class """
__nb_objects = 0
def __init__(self, id=None):
""" ctor for Base Class """
self.id = id
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
@static... | Samigirum/alx-higher_level_programming | 0x0C-python-almost_a_circle/models/base.py | base.py | py | 3,403 | python | en | code | 0 | github-code | 6 |
72531866429 | from typing import Final
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
from ._common import column_created_datetime, column_modified_datetime
from .base import metadata
# Intentionally includes the term "SECRET" to avoid leaking this value on a public domain
VENDOR_SECRET_PREFIX: Final[str... | ITISFoundation/osparc-simcore | packages/postgres-database/src/simcore_postgres_database/models/services_environments.py | services_environments.py | py | 2,469 | python | en | code | 35 | github-code | 6 |
27603501009 |
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from langdetect import detect
def pdf2string(path):
"""
From a given pdf path, it creates a string of the pdf... | n1ur0/Document_Clustering | pdfparser.py | pdfparser.py | py | 1,484 | python | en | code | 0 | github-code | 6 |
8217311297 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import sys
import math
plt.style.use("acaps")
"""
Compare households owning agricultural land in 2018 and 2019 in the host community.
"""
# Read in the data
df_2018 = pd.read_csv("../../data/processed/MSNA_Host_2018.csv")
df_2... | zackarno/coxs_msna_sector_analysis | host_community/analysis/housing_barplots/agri_land.py | agri_land.py | py | 1,732 | python | en | code | 0 | github-code | 6 |
34047796819 | import argparse
from resnet import resnet
import os
import sys
from test import test
import tensorflow as tf
from read_data import fasionAI_data
def parse_args():
parser=argparse.ArgumentParser(description="test resnet for FasionAI")
parser.add_argument("--image_data",dest="image_data",\
... | hx121071/FashionAI_resnet | base/test_net.py | test_net.py | py | 1,380 | python | en | code | 1 | github-code | 6 |
39503143836 | number, limit = map(int, input().split())
def brute(k):
if len(k) == limit:
print(' '.join(map(str, k)))
return 0
for i in range(1, number+1):
if i in k:
continue
brute(k+[i])
brute([])
'''
a, b = map(int, input().split())
k = [0] * b
def brute(index, start, ... | decentra1ized/baekjoon_solution | 15649 N과 M (1).py | 15649 N과 M (1).py | py | 652 | python | en | code | 0 | github-code | 6 |
25267249528 | '''
You are given a 2-D array with dimensions X.
Your task is to perform the sum tool over axis 0 and then find the product of that result
'''
import numpy
N,M = input().split()
A = numpy.array([input().split() for _ in range(int(N))],int)
prodd = numpy.sum(A,axis=0)
print(numpy.prod(prodd))
| malvika-chauhan/Innomatics-Internship | Python Programming Task/Task - 6 (Numpy - Both for Basic and Adv User)/9.py | 9.py | py | 304 | python | en | code | 1 | github-code | 6 |
4376865590 |
import sys
import signal
import argparse
from dictmaster.util import load_plugin
last_broadcast_msg = " "
def broadcast(msg, overwrite=False):
global last_broadcast_msg
if overwrite:
sys.stdout.write("\r{}".format(" "*len(last_broadcast_msg.strip())))
msg = "\r"+msg
else:
if last_... | tuxor1337/dictmaster | dictmaster/cli/main.py | main.py | py | 2,301 | python | en | code | 32 | github-code | 6 |
26201696351 | from dolfin import *
import math
import numpy as np
import logging
import matplotlib.pyplot as plt
from unconstrainedMinimization import InexactNewtonCG
logging.getLogger('FFC').setLevel(logging.WARNING)
logging.getLogger('UFL').setLevel(logging.WARNING)
set_log_active(False)
# Set the level of noise:
noise_std_dev ... | uvilla/inverse17 | Assignment3/tntv.py | tntv.py | py | 1,395 | python | en | code | 3 | github-code | 6 |
36386456035 | import altair as alt
from vega_datasets import data
source = data.cars()
chart = alt.Chart(source).mark_circle(size=60, clip=False).transform_calculate(
x = alt.datum.Horsepower-100,
y = alt.datum.Miles_per_Gallon - 25
).encode(
x=alt.X('x:Q', axis=alt.Axis(offset=-150)),
y=alt.Y('y:Q', axis=alt.Axis(... | noahzhy/charts_synthetic_data | test.py | test.py | py | 464 | python | en | code | 0 | github-code | 6 |
1921452426 | import pyomo.environ as pe
from lci import LifeCycleInventory
from superstructure import Superstructure
from utils.properties import molar_weight
from utils.utils import sum_rule
from utils.save_results import ResultManager
from utils.solve_model import Solver
import time as time
import pickle
def range_len(start, st... | jkleinekorte/millgas2what | src/repeated_solving_el_impact.py | repeated_solving_el_impact.py | py | 15,332 | python | en | code | 1 | github-code | 6 |
10094748311 | # coding=utf-8
import MeCab
import sys
if len(sys.argv) == 1:
print("mkdir.py <file> [univ]\n")
sys.exit(1)
if len(sys.argv) == 3 and sys.argv[2] == 'univ':
dictype = '固有名詞'
nauntype = '組織'
else:
dictype = '名詞'
nauntype = '一般'
tagger = MeCab.Tagger('-Oyomi')
out = sys.argv[1].replace(".txt", ".... | l-plantarum/chiebukuro | mkdic.py | mkdic.py | py | 716 | python | en | code | 0 | github-code | 6 |
8034052289 | #Prototype 4
# importing the necessary libraries
import cv2
import numpy as np
import numpy as np
import os
import cv2
# defining the crack detector function
# here weak_th and strong_th are thresholds for
# double thresholding step
def PCD(img, weak_th = None, strong_th = None):
# c... | thanhtung48c/AUV-Crack-Detection-Model | script.py | script.py | py | 5,431 | python | en | code | 0 | github-code | 6 |
18941943109 | # 字典的运算
# 求最小值、最大值、排序
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price= min(zip(prices.values(),prices.keys())) # zip()将键值的殊勋反转
print(min_price) # (10.75, 'FB')
max_price= max(zip(prices.values(),prices.keys()))
print(max_price) # (612.78, 'AAPL')
# 价格从... | DoubleBlock/PythonCookbook | Chapter1/1.8.py | 1.8.py | py | 949 | python | en | code | 0 | github-code | 6 |
27810749441 | __author__ = 'Matt Clarke-Lauer'
__email__ = 'matt@clarkelauer.com'
__credits__ = ['Matt Clarke-Lauer']
__date__ = 8 / 1 / 13
__version__ = '0.1'
__status__ = 'Development'
import log
name = "libraryApisUsed"
description = "Gets the used library apis"
result = []
def getName():
"return analysis name"
retur... | mclarkelauer/AndroidAnalyzer | Analysis/plugins/libraryApisUsed/__init__.py | __init__.py | py | 639 | python | en | code | 2 | github-code | 6 |
2966396264 | '''
@File : ImageReward.py
@Time : 2023/02/28 19:53:00
@Auther : Jiazheng Xu
@Contact : xjz22@mails.tsinghua.edu.cn
@Description: ImageReward Reward model for reward model.
'''
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from config.op... | THUDM/ImageReward | train/src/ImageReward.py | ImageReward.py | py | 8,579 | python | en | code | 761 | github-code | 6 |
36797461084 | """Utility for ROC-AUC Visualization"""
import matplotlib.pyplot as plt
from src.utils import infoutils
def plot_signle_roc_auc(cfg, auc, fpr, tpr):
"""
Plots signel ROC Curve
Args:
cfg (cfgNode): Model configurations
auc (float): Area under the ROC curve
fpr (list): False positiv... | KhaledElTahan/Real-World-Anomaly-Detection | src/visualization/roc_auc.py | roc_auc.py | py | 1,016 | python | en | code | 0 | github-code | 6 |
8173760199 | # Get Networks in Org
# Meraki API Reference:
# https://developer.cisco.com/meraki/api-latest/#!list-the-networks-that-the-user-has-privileges-on-in-an-organization
import tokens
import requests
import json
base_url = "https://api.meraki.com/api/v1"
resource_path = f"/organizations/{tokens.ORG_ID}/networks"
url = bas... | jtsu/meraki_python | merakiScripts/2_getNetworks.py | 2_getNetworks.py | py | 633 | python | en | code | 1 | github-code | 6 |
40071000142 | import collections
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
res = collections.Counter(ransomNote) - collections.Counter(magazine)
return not res #(res == collections.C... | lucy9215/leetcode-python | 383_ransomNote.py | 383_ransomNote.py | py | 554 | python | en | code | 0 | github-code | 6 |
73363651708 | #только приватный доступ
import requests
import munch
#получить список доменов
#i.ivanov
headers = { 'PddToken': 'F4KTVIPLCFULRWCDFGJIKNGUPEWQUEMSKDG7DDFJZDPILB3JXLOQ'}
#x@yandex
headers = { 'PddToken': 'E7UIU2AHR33EOXDJ5W6R2Q2WRNW4TGCI5MZ2U6DOX5YKBEJW334A' }
url = 'https://pddimp.yandex.ru/api2/admin/domain/domains?'... | expo-lux/scripts | python/x_createuser.py | x_createuser.py | py | 1,573 | python | ru | code | 0 | github-code | 6 |
42602973405 | import random
nombre = str(input("Hola por favor ingrese su nombre: "))
print("=====================================================")
print(f"Bienvenido {nombre} al juego 'ADIVINA EL NÚMERO'\n")
print("Reglas del juego: \n"
"a) El usuario debera ingresar un numero entero.\n"
"b) Debera adivinar el número... | NelsonSCH/PythonInformatorio2023 | clase3/d3_g1.py | d3_g1.py | py | 1,751 | python | es | code | 0 | github-code | 6 |
35245234184 | from flask import render_template, url_for, flash, redirect, request, make_response, send_from_directory
from os import path
from csaptitude import app, db, bcrypt
from csaptitude.forms import TestResultsForm, TestRegistrationForm, TestLoginForm
from csaptitude.models import User, TestResult, QuestionResponse
from flas... | DoctorHayes/AptitudeTest-CS | csaptitude/routes.py | routes.py | py | 6,245 | python | en | code | 0 | github-code | 6 |
70107497149 | from bs4 import BeautifulSoup
import requests
from pprint import pprint
def main():
url = 'https://remote.co'
remote_co_html = requests.get(url)
soup = BeautifulSoup(remote_co_html.content,"html.parser")
#the_main_class = soup.find("body",class_="home blog remote-co").main.find("div",class_="contai... | cthacker-udel/Python-WebScraper | remoteCoScraper.py | remoteCoScraper.py | py | 1,208 | python | en | code | 1 | github-code | 6 |
8770897157 | import asyncio
import logging
import sys
import time
import pyautogui
import pydirectinput
import qasync
from PySide6 import QtWidgets, QtCore
from front import Ui_MainWindow
def use_quick_access_inventory():
print("Use quick access of inventory")
pydirectinput.keyDown('1')
time.sleep(0.1)
pydirectin... | arekszatan/botClicker | InsomniaBot.py | InsomniaBot.py | py | 6,684 | python | en | code | 0 | github-code | 6 |
13209639303 | import PIL
import pyautogui
def popper():
while True:
try:
box = pyautogui.locateOnScreen("C:/Users/Bryan/Documents/GitHub/Cuhacking/decline.png", confidence = 0.55)
loc = pyautogui.center(box)
print(loc)
pyautogui.click(loc.x, loc.y)
break
... | RogerLamTd/Cuhacking | AutomatedQueuePopper/League.py | League.py | py | 374 | python | en | code | 0 | github-code | 6 |
7606759311 | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
... | thomasleese/gantt-charts | ganttcharts/cli/send_summary_emails.py | send_summary_emails.py | py | 1,214 | python | en | code | 0 | github-code | 6 |
6123307630 | import os
import sys
import shutil
import logging
import argparse
import warnings
import re
from pathlib import Path
from ..backend_funcs.convert import parse_validator
import subprocess as sub
import pandas as pd
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('fw-heudiconv-validator')
def escape... | PennLINC/fw-heudiconv | fw_heudiconv/cli/validate.py | validate.py | py | 4,603 | python | en | code | 5 | github-code | 6 |
75241216826 | from typing import Any, Type
from aiohttp import BasicAuth
from ..internal.gateway import Gateway
from ..internal.http import HTTPClient
from .cache import CacheStore, Store
_BASE_MODELS: dict[Any, Any] = {}
class State:
"""The central bot cache."""
def __init__(
self,
token: str,
... | VincentRPS/pycv3 | pycord/state/core.py | core.py | py | 1,011 | python | en | code | 0 | github-code | 6 |
14959398109 | from mock import Mock
from yoti_python_sandbox.doc_scan.check import SandboxZoomLivenessCheckBuilder
from yoti_python_sandbox.doc_scan.check.report.breakdown import SandboxBreakdown
from yoti_python_sandbox.doc_scan.check.report.recommendation import (
SandboxRecommendation,
)
def test_zoom_liveness_check_should... | getyoti/yoti-python-sdk-sandbox | yoti_python_sandbox/tests/doc_scan/check/test_sandbox_liveness_check.py | test_sandbox_liveness_check.py | py | 1,243 | python | en | code | 0 | github-code | 6 |
21884345926 | import cv2
def distance(p1, p2):
# D8 distance
return max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
def gamma(img):
totalpixels = img.shape[0] * img.shape[1]
color_dict = {}
for i in range(len(img)):
for j in range(len(img[i])):
tc = tuple(img[i][j])
if (tc in color_dict):
color_dict[tc].append((i, j))... | NitigyaPant/MCA_assignment | test.py | test.py | py | 1,025 | python | en | code | 0 | github-code | 6 |
19700703411 | import discord
from discord.ext import commands
import urllib.parse, urllib.request
import requests
import googlesearch
import re
import json
bot = commands.Bot(description = "Im just a Kid", command_prefix ="@")
@bot.event
async def on_ready():
print("IM READYYY")
@bot.command(pass_context=True)
async def searc... | TestingYG/ProjectDumButt | DumButtv2.py | DumButtv2.py | py | 7,169 | python | en | code | 1 | github-code | 6 |
75188756666 | # 하기 코드의 가능한 개선방향
# 2차원 리스트를 활용하고, 좌표에 조건을 걸어 해당하지 않는 것은 수행하지 않음
# try-except를 활용
def pop_reverse_st(n):
for i in range(5):
if reverse_st[i]:
result.append(reverse_st[i].pop())
T = int(input())
for test_case in range(1, T+1):
st = [list(input()) for _ in range(5)]
reverse_st = []
r... | zacinthepark/Problem-Solving-Notes | swea/0819_의석이의세로로말해요.py | 0819_의석이의세로로말해요.py | py | 941 | python | ko | code | 0 | github-code | 6 |
38088951612 | # -*- coding: utf-8 -*-
"""
Production Mapper
Michael Troyer
michael.troyer@usda.gov
"""
import datetime
import os
import traceback
from collections import defaultdict
import arcpy
arcpy.env.addOutputsToMap = False
arcpy.env.overwriteOutput = True
##---Functions-----------------------------------------------... | MichaelTroyer/ArcGIS_NRCS_Production_Mapper | Production_Mapper.pyt | Production_Mapper.pyt | pyt | 8,168 | python | en | code | 1 | github-code | 6 |
2665839986 | from math import sqrt, sinh, cosh
class HeatSink:
def __init__(self,
baseLength: float = 0.865,
baseWidth: float = 0.5,
baseDepth: float = 0.003,
noFinsLength: float = 45,
noFinsWidth: float = 15,
finWidth: floa... | southwelljake/HeatSinkModelling | src/heatSink.py | heatSink.py | py | 3,505 | python | en | code | 0 | github-code | 6 |
74083767549 | from django.core import checks
from django.core.checks import Warning
from django.test import SimpleTestCase, override_settings
class SystemChecksTestCase(SimpleTestCase):
def test_checks(self):
errors = checks.run_checks()
assert errors == []
with override_settings(
INSTALLED... | boxine/django-huey-monitor | huey_monitor_project/tests/test_checks.py | test_checks.py | py | 790 | python | en | code | 69 | github-code | 6 |
27812632483 | import sys
from osgeo import ogr
fn=r'D:\BackUp\projectsBackup\Qgis\pygis\res\ne_50m_populated_places.shp'
ds=ogr.Open(fn,0)
if ds is None:
sys.exit('could not open {0}.'.format(fn))
lyr=ds.GetLayer(0)
#此图层要素总量
num_features=lyr.GetFeatureCount()
print(num_features)
#根据要素编号Fid获取对应图层
third_feature=lyr.GetFeature(nu... | xuewenqian/pythonGis | ogr/获取特定的要素.py | 获取特定的要素.py | py | 406 | python | en | code | 0 | github-code | 6 |
36294686570 | # 단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
# s = "abcde"
s = "qwer"
# s = "avcxvxcv"
def solution(s):
half = len(s)//2
result = s[half] if len(s) % 2 else s[half-1 : half+1]
print(result)
solution(s) | minkimhere/algorithm_python | 03_middle_num.py | 03_middle_num.py | py | 334 | python | ko | code | 0 | github-code | 6 |
22850158142 | #!/usr/bin/env python
# coding: utf-8
from bs4 import BeautifulSoup as bs
import pandas as pd
from splinter import Browser
import requests
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser(... | iegatlanta/web-scraping-challenge | Mission_to_Mars/scrape_mars.py | scrape_mars.py | py | 2,817 | python | en | code | 0 | github-code | 6 |
30792880675 | def my_function():
result = 3*2
return result # return is an output keyword
output = my_function()
print(output)
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"{formatted_f_name} {formatted_l_name}"
# when the word return is enco... | shrijanlakhey/100-days-of-Python | 010/functions_with_output.py | functions_with_output.py | py | 720 | python | en | code | 0 | github-code | 6 |
41475591670 | import httpx
import asyncio
import logging
import discord
from discord.ext import tasks
from redbot.core import Config, commands
IDENTIFIER = 4175987634255572345 # Random to this cog
ishtakar_world_id = "3f1cd819f97e"
default_server = "Ishtakar"
realm_data_url = "https://nwdb.info/server-status/data.json"
default... | psykzz/cogs | nw_server_status/server_status.py | server_status.py | py | 8,630 | python | en | code | 0 | github-code | 6 |
21512060680 |
out = open('output2.py', 'w')
out.write("""
total = 0
"""
)
def encode(s):
return s.replace("\\", "\\\\").replace("\"", "\\\"")
try:
with open('input.txt', 'r') as f:
for line in f:
s = line.strip()
out.write('total = total + len("\\"%s\\"") - %d\n' % (encode(encode(s)), len... | snocorp/adventofcode2015 | day8/part2.py | part2.py | py | 399 | python | en | code | 0 | github-code | 6 |
72757346749 | from syscore.objects import arg_not_supplied
from syscore.genutils import flatten_list
from dataclasses import dataclass
import pandas as pd
EMPTY_INSTRUMENT = ""
class futuresInstrument(object):
def __init__(self, instrument_code: str):
self._instrument_code = instrument_code
@property
def inst... | ahalsall/pysystrade | sysobjects/instruments.py | instruments.py | py | 9,474 | python | en | code | 4 | github-code | 6 |
71360101948 | #!/usr/bin/python3
import os
import sys
import time
import jsonpickle
class TODODescription(object):
def __init__(self, todoName, startTime = -1) -> None:
self.todoName = todoName
self.startTime = startTime
self.stopTime = -1
def display(self, id=''):
print('%s %s' % (str(id),... | Dechode/TODO-App | app.py | app.py | py | 5,984 | python | en | code | 0 | github-code | 6 |
30575033790 | from DataEngine.DataAdapters.MongoAdapter.MongoAdapter import MongoAdapter
from Domain.EquityCorporateData import EquityCorporateData
from Domain.BuildEnumMethods import BuildEnumMethods
from datetime import date
ma : MongoAdapter = MongoAdapter()
testEquity = EquityCorporateData().build(
method = BuildEnumM... | jminahan/backtest_framework | DataEngine/Tests/DataAdapters/MongoAdapter/MongoAdapterTest.py | MongoAdapterTest.py | py | 1,494 | python | en | code | 0 | github-code | 6 |
5718228664 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
####################################################
# Summer 2017 COMS 4771 AI Homework 2
# File: Helper.py
# Name: Qipeng Chen
# UNI: qc2201
####################################################
import math
from Grid import Grid, vecIndex
EMPTY_WEIGHT = 3.0
MAX_WEIGHT =... | asd123cqp/coms4701-artificial-intelligence | hw2_2048/Helper.py | Helper.py | py | 2,251 | python | en | code | 0 | github-code | 6 |
3580079410 | import json
from statistics import mean
import numpy as np
import os
from bokeh.plotting import output_file, figure, save
from bokeh.layouts import gridplot
from src.utils.tools import listdir, hash_append
def combined(ids, name, legend=None, y_range=(0, 900)):
summaries = {}
episodes = []
for key_ in set... | MatthijsBiondina/WorldModels | planet/plots.py | plots.py | py | 4,228 | python | en | code | 0 | github-code | 6 |
8891107927 | import cv2
import numpy as np
classify_body = cv2.CascadeClassifier('haarcascade_fullbody.xml')
vid_capture = cv2.VideoCapture('people_walking.mp4')
while vid_capture.isOpened():
ret,frame = vid_capture.read()
frame = cv2.resize(frame, None,fx=0.5,fy=0.5, interpolation = cv2.INTER_LINEAR)
... | RudraCS18/Object-Detection-using-openCV-python | pedestrian detection.py | pedestrian detection.py | py | 707 | python | en | code | 0 | github-code | 6 |
32279135386 | #!/usr/bin/env python
"""Simple script to fetch data from the bslparlour home stream"""
import datetime
import os
import subprocess as sp
import yaml
import tweepy
import myconf
def dictify(results):
return_dict = dict()
for result in results:
return_dict[result.id] = result
return return_dict
... | natfarleydev/mr-retweet | get_tweet_data.py | get_tweet_data.py | py | 1,627 | python | en | code | 0 | github-code | 6 |
36939207944 | import json
import paho.mqtt.client as pmqtt
class mqtt():
"""HIAS iotJumpWay MQTT Module
This module connects devices, applications, robots and software to
the HIAS iotJumpWay MQTT Broker.
"""
def __init__(self,
helpers,
client_type,
configs):
... | leukaemiamedtech/hiasbch-mqtt-blockchain-agent | modules/mqtt.py | mqtt.py | py | 6,273 | python | en | code | 4 | github-code | 6 |
6734779664 | #Create a house using starter code
#Import turtle
import turtle
#Set background to Navy Blue
turtle.bgcolor('navyblue')
shelly = turtle.Turtle()
#Start to create house
#Make first big yellow square for base structure of house
shelly.begin_fill() #Start the fill of color
shelly.color('yellow')
for i in r... | AruneemB/Basic-Art-With-Turtle | Art_Experiment2.py | Art_Experiment2.py | py | 1,705 | python | en | code | 0 | github-code | 6 |
22382302471 | import time
from odoo.addons.web.controllers import main as report
from odoo.http import content_disposition, request, route
from odoo.tools.safe_eval import safe_eval
class ReportController(report.ReportController):
@route()
def report_routes(self, reportname, docids=None, converter=None, **data):
#... | detian08/bsp_addons | reporting-engine-11.0/report_xml/controllers/main.py | main.py | py | 1,704 | python | en | code | 1 | github-code | 6 |
361475644 | import numpy as np
import pandas as pd
def output(time, station_dict):
text = []
text.append("\nTime: {}".format(time))
text.append('------------------------------------------------------')
station_ids = pd.read_csv('input_data/stations_state.csv')['station_id'].tolist()
for station in stati... | Nick-Masri/ASL-HA-MO-Simulator-Project | simulator/output_formatting/overview.py | overview.py | py | 1,074 | python | en | code | 2 | github-code | 6 |
46051636676 | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.contrib import messages
from django.utils.translation import gettext as _
from djconfig import config
from spirit.core.utils.views import is_post, post_data
from spirit.core.utils.pagi... | nitely/Spirit | spirit/comment/flag/admin/views.py | views.py | py | 1,916 | python | en | code | 1,153 | github-code | 6 |
2768444611 | import pandas as pd
import math
from sklearn import linear_model
import numpy as np
def predict_using_sklearn():
test_scores = pd.read_csv(r'C:\Users\Polina\Desktop\Python\Pandas\test_scores.csv')
reg = linear_model.LinearRegression()
reg.fit(test_scores[['math']], test_scores.cs)
return reg.c... | CarlBrendt/Data-Analysis | Gradient_descent_with_no_train_test.py | Gradient_descent_with_no_train_test.py | py | 1,356 | python | en | code | 0 | github-code | 6 |
25743059465 | class Solution(object):
def twoSum(self, nums, target):
itr = len(nums)
d = {}
for i in xrange(itr):
if ((target - nums[i]) in d.iterkeys()):
return [d[target - nums[i]], i]
else:
d[nums[i]] = i
''' Naive half solution
def twoSu... | chaitan64arun/algo-ds | leetcode/twosum.py | twosum.py | py | 756 | python | en | code | 0 | github-code | 6 |
26038332576 | from __future__ import annotations
import pytest
@pytest.mark.parametrize(
"variables, expected_data",
[
(
{"name": r"pants_explorer\."},
{
"rules": [
{"name": "pants_explorer.server.graphql.rules.get_graphql_uvicorn_setup"},
... | pantsbuild/pants | pants-plugins/pants_explorer/server/graphql/query/rules_test.py | rules_test.py | py | 1,078 | python | en | code | 2,896 | github-code | 6 |
27390159801 | # 2-Way Partition
# http://rosalind.info/problems/par/
from utilities import get_file, get_answer_file
def quick_sort2(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left_arr, equal_arr, right_arr = [], [], []
for num in arr:
if num < pivot:
left_arr.append(num... | Delta-Life/Bioinformatics | Rosalind/Algorithmic Heights/code/PAR.py | PAR.py | py | 1,335 | python | en | code | 0 | github-code | 6 |
39254517776 | from django.db import models
from django.db.models import Case, Count, IntegerField, When
class CountryManager(models.Manager):
def aggregate_integration_statuses(self):
from proco.connection_statistics.models import CountryWeeklyStatus
return self.get_queryset().aggregate(
countries_j... | unicef/Project-Connect-BE | proco/locations/managers.py | managers.py | py | 1,353 | python | en | code | 2 | github-code | 6 |
15366112732 | import numpy as np
import os
try:
import welib.fastlib.fastlib as fastlib
except:
import fastlib
def CPLambdaExample():
""" Example to determine the CP-CT Lambda Pitch matrices of a turbine.
This scrip uses the function CPCT_LambdaPitch which basically does the same as ParametricExample
above.
... | rhaghi/welib | welib/fastlib/_examples/Example_CPLambdaPitch.py | Example_CPLambdaPitch.py | py | 1,520 | python | en | code | null | github-code | 6 |
35060216092 | from flask import Flask, render_template, request, jsonify
import atexit
import cf_deployment_tracker
import os
import json
import requests
# Emit Bluemix deployment event
cf_deployment_tracker.track()
app = Flask(__name__)
db_name = 'mydb'
client = None
db = None
'''
if 'VCAP_SERVICES' in os.environ:
vcap = js... | vishalsatam/DeploymentOfMLAlgoOnCloud | Flask Application/webApp.py | webApp.py | py | 9,720 | python | en | code | 2 | github-code | 6 |
3920778 | import sys
a = int(input())
w = [0] * (a + 1)
w[1] = int(input())
tmp = [[0 for i in range(502)] for j in range(502)]
tmp[1][0] = w[1]
if a == 1:
print(w[1])
else:
for i in range(2, a + 1):
k = [int(i) for i in sys.stdin.readline().split()]
tmp[i][0] = tmp[i-1][0] + k[0]
for j in range... | Winmini/CodingTest | BOJ/1932.py | 1932.py | py | 476 | python | en | code | 0 | github-code | 6 |
10272912392 | import sys
import user_login
from PyQt4 import QtGui,QtCore
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = user_login.Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
| naresh-chaudhary/Institute-Checkpost-Management-System | Main.py | Main.py | py | 258 | python | en | code | 0 | github-code | 6 |
5995812394 | #!/usr/bin/env python
import numpy as np
import healpy as hp
import pylab
import matplotlib.pyplot as plt
import time
import mocklc
import matplotlib
import sepmat
import gpkernel
import scipy
import emcee
import sys
import time
Ns=2000
np.random.seed(17)
#set geometry
inc=45.0/180.0*np.pi
Thetaeq=np.pi
zeta=60... | HajimeKawahara/sot | src/sot/dymap/static_sampling.py | static_sampling.py | py | 2,866 | python | en | code | 4 | github-code | 6 |
73944785148 | import pathlib
import numpy as np
import h5py
import cv2
import argparse
def load_episodes(directory, capacity=None):
# The returned directory from filenames to episodes is guaranteed to be in
# temporally sorted order.
filenames = sorted(directory.glob('*.npz'))
if capacity:
num_steps = 0
... | conglu1997/v-d4rl | conversion_scripts/npz_to_hdf5.py | npz_to_hdf5.py | py | 2,833 | python | en | code | 64 | github-code | 6 |
21025162572 | #!/usr/bin/env python3
"""
Implementation of R3PTAR
"""
import logging
import signal
import sys
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, MediumMotor, LargeMotor
from ev3dev2.sensor.lego import InfraredSensor
from ev3dev2.sound import Sound
from threading import Thread, Event
from time import ... | ev3dev/ev3dev-lang-python-demo | robots/R3PTAR/r3ptar.py | r3ptar.py | py | 4,270 | python | en | code | 59 | github-code | 6 |
17371120296 | import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from django.contrib.auth import get_user_model
from rest_framework_simplejwt.tokens import RefreshToken
User = get_user_model()
AUTHOR = 'author'
EXECUTOR = 'executor'
AUTHOR_EMAIL = '... | vavsar/freelance_t | tests/users/test_views.py | test_views.py | py | 4,583 | python | en | code | 1 | github-code | 6 |
70106082748 | '''
1. import opencv
2. load image
3. load model
4. adjuct image gray
5. Check and mark face
3. create window
4. show image
5. pause window
6. close window
'''
import numpy as np
import cv2
# print(cv2.__version__)
# Load image
img = cv2.imread("./images/ufc.jpeg")
# Load model
face_cascade = cv2.C... | benjaminhuanghuang/opencv-study | cv-find-face.py | cv-find-face.py | py | 900 | python | en | code | 0 | github-code | 6 |
575101998 | #ChickenCrossing.py
#A.Colwell(2016)
'''
Set up function to represent crossing a lane with argument of
how many chickens to pass.
repeat eight times starting with 1000 chickens.
store the result in a list.
print out list results.
'''
import random
def chickenCrossing(chicks):
died = int(round(ran... | MrColwell/PythonProfessionalLearning | PythonForTeachers/StudentCode/Exam Scripts/ChickenCrossing.py | ChickenCrossing.py | py | 1,056 | 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.