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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
35196686051 | import nibabel as nib
import numpy as np
import psycopg2
import csv
import os
import boto3
from io import BytesIO
import gzip
from scipy import stats
import math
from decouple import config
# Define connection parameters
params = {
"host": config('DB_HOST'),
"database": config('DB_NAME'),
"user": config('... | JosephIsaacTurner/LesionBank | nifti_data_science_local.py | nifti_data_science_local.py | py | 8,579 | python | en | code | 0 | github-code | 90 |
18494973779 | n,x=map(int,input().split())
a=list(map(int,input().split()))
ans=0
a.sort()
for i in a:
x-=i
if x>0:
ans+=1
continue
elif x==0:
ans+=1
break
else:
break
if ans==n:
if x!=0:
ans-=1
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p03254/s748267214.py | s748267214.py | py | 243 | python | de | code | 0 | github-code | 90 |
16198539610 | import pandas as pd
import numpy as np
import json
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.embed import components
from bokeh.models import TapTool, GeoJSONDataSource, NumeralTickFormatter, LinearColorMapper, LogColorMapper, HoverTool
from bokeh.models.glyphs import Text
f... | meenurajapandian/CGDVColombia | PyCode/GeneratePlots.py | GeneratePlots.py | py | 13,022 | python | en | code | 0 | github-code | 90 |
19517491114 | #!/usr/bin/python3
import socket
import struct
import sys
interface = sys.argv[1]
# Listening on IPv6 on the local machine
local_addr = '::'
# Multicast address upon which you will be listening.
mcast_addr = "ff16::fe"
# Port of the MCAST server since ICMPv6 is not being used, we need ports.
mcast_port = 5000
# Nam... | aqeebhussain122/portninja | code/recon/ipv6/listener62.py | listener62.py | py | 1,192 | python | en | code | 3 | github-code | 90 |
41457287064 | from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import cross_val_predict, KFold
from hw1.classifiers import classifier
def evaluate(x, y, algs, classes=Non... | aserpi-uni/msecs-ml | hw1/evaluation.py | evaluation.py | py | 3,273 | python | en | code | 1 | github-code | 90 |
2842097655 | from tkinter import *
from tkinter import ttk
import random
from bubble_sort import bubble_sort
from quick_sort import quick_sort
from merge_sort import merge_sort
from bucket_sort import bucket_sort
from comb_sort import comb_sort
from shell_sort import shell_sort
root=Tk()
root.title("sorting algorithm")
root.maxsiz... | rishavkumar888/Visualize-the-Epic-Sorting-Algo | sorting_algo_visualizer.py | sorting_algo_visualizer.py | py | 3,654 | python | en | code | 0 | github-code | 90 |
34731082097 | #!/usr/bin/env python3
""" Defines `play`. """
import numpy as np
def play(env, Q_table, max_steps=100):
"""
Plays an episode of Frozen Lake using a trained agent.
env: The FrozenLakeEnv instance.
Q_table: A `numpy.ndarray` representing the Q-table.
max_steps: The maximum number of steps in the e... | keysmusician/holbertonschool-machine_learning | reinforcement_learning/0x00-q_learning/4-play.py | 4-play.py | py | 800 | python | en | code | 1 | github-code | 90 |
18381181399 | def cin():
in_ = list(map(int,input().split()))
if len(in_) == 1: return in_[0]
else: return in_
N = cin()
A = []
for i in range(N):
in1, in2 = cin()
A.append([in2, in1])
A = sorted(A)
t = 0
flg = 1
for i in range(N):
t += A[i][1]
if t > A[i][0]: flg = 0
if flg: print("Yes")
else: pri... | Aasthaengg/IBMdataset | Python_codes/p02996/s734413462.py | s734413462.py | py | 328 | python | en | code | 0 | github-code | 90 |
28330894134 | from enum import Enum, auto
import numpy as np
from plot1d import plot
from constantes import T0, Da, D
hyp = 'B' # hypothèse
print(f'Hypothèse {hyp}')
La, L, Lp = 1, 1e-1, 1e-2 # m
if hyp == 'A': La = L
S = 1e-4 # m^2
tau = La**2 / D # s
dilt = 15
print(f'τ = {tau/dilt:.2f} s')
Nx = 100
Xe = La / Nx
Nt = int((Nx**2... | Firefnix/data-center | theorie/simulation/1d.py | 1d.py | py | 1,571 | python | en | code | 1 | github-code | 90 |
35784171291 | from flask import Flask, render_template, request, redirect, url_for
from dotenv import load_dotenv
import pymysql
import os
load_dotenv()
INITIAL_DB_HOST = 'initial-db'
app = Flask(__name__)
def get_connection(dbhost):
conn = pymysql.connect(
host=dbhost,
db=os.getenv("db_name"),
user=o... | trainocate-japan/sawakura-labs | app.py | app.py | py | 2,760 | python | en | code | 0 | github-code | 90 |
33740653608 | from django.db import models
class Group(models.Model):
name = models.CharField(max_length=255, unique=True)
members = models.ManyToManyField("User", related_name="training_groups", blank=True)
private_user = models.OneToOneField(
"User",
blank=True,
null=True,
related_name... | juliansunn/pace-my-race | api/models/training_group.py | training_group.py | py | 2,127 | python | en | code | 0 | github-code | 90 |
2072970235 | from discord.ext import commands
from cogs.utils import checks, formats, time, context
from cogs.utils.paginator import Pages
import discord
from collections import OrderedDict, deque, Counter
import os
import datetime
import asyncio
import copy
import unicodedata
import inspect
import itertools
from typing import Unio... | 948guppy/Morrigan-Rewrite | cogs/meta.py | meta.py | py | 17,285 | python | en | code | 0 | github-code | 90 |
18228413609 | from collections import Counter
S=input()
rlist=[0]
for i in range(len(S)):
rlist.append((rlist[-1]+int(S[-i-1])*pow(10,i,2019))%2019)
c = Counter(rlist)
c[0] -= 1
def nC2(n):
return n*(n-1)//2
ans = c[0]
for k in c.keys():
if c[k] >= 2:
ans += nC2(c[k])
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02702/s439716294.py | s439716294.py | py | 289 | python | en | code | 0 | github-code | 90 |
33168504138 | class Vertex:
def __init__(self, v_id=-1, v_name='', v_nbors=None):
self.id = v_id
self.name = v_name
if v_nbors is None:
self.neighbor_list = [] # list of tuples in form (vertex, distance)
else:
self.neighbor_list = v_nbors
def add_neighbor(self, vertex... | yildirimyigit/ds-p4ai | DataStructures/Graph(Yigit)/vertex.py | vertex.py | py | 991 | python | en | code | 0 | github-code | 90 |
3683868594 | import time
import random
import os
import numpy as np
import torch
import re
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
... | ZhaoxuLi123/AETNet | utils/utils.py | utils.py | py | 2,409 | python | en | code | 20 | github-code | 90 |
24713777645 | import discord
from discord.ext import commands, tasks
from itertools import cycle
import json
class Function(commands.Cog):
def __init__(self, client):
self.client = client
with open('config.json') as f:
data = json.load(f)
self.status = cycle(data["Status"])
@tasks.loop(seconds=15)
as... | NImaism/FiveM-Discord-AdministrationPanel | IsM Panel/cogs/Starting.py | Starting.py | py | 1,404 | python | en | code | 13 | github-code | 90 |
17177355286 | from os import chflags
import pprint
f = open("input", "r")
data = [x.rstrip("\n") for x in f if x.rstrip("\n") != ""]
data = [{"signal": i.split("|")[0].strip(), "output": i.split("|")[
1].strip()} for i in data]
def decode(input):
unique = sorted(input.split(" "), key=len)
cf = set()
bd = set()
... | feiming/adventofcode2021 | day8/part2.py | part2.py | py | 3,039 | python | en | code | 0 | github-code | 90 |
32019131698 | import json
from flask import Flask, render_template, url_for, request, redirect, session,jsonify
import web3Func
w = web3Func.Work('https://ropsten.infura.io/v3/537c4c65f5bd41a9bfb65d33948ece9d')
app = Flask(__name__)
@app.route("/how10")
def how10():
return jsonify(w.getLast10BlockInfo())
@app.route("/how"... | UzorStudio/web3www | main.py | main.py | py | 468 | python | en | code | 0 | github-code | 90 |
39393594458 | from splinter import Browser
from bs4 import BeautifulSoup as soup
# import requests
# import pandas as pd
def init_browser():
#Mac Users
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
return Browser('chrome', **executable_path, headless=False)
#Mars News
#create dictionary
mars_in... | liliana-ilut/web-scraping-challenge | Missions_to_Mars/scrape_mars.py | scrape_mars.py | py | 4,558 | python | en | code | 0 | github-code | 90 |
12191300406 | import requests
from ruamel import yaml
def login():
url = "https://pg-bate.cailian.net/api/loginNew"
#headers = {"Content-Type": "application/json"}
param ={'loginName':'18610933265','password':'e3ceb5881a0a1fdaad01296d7554868d','kaptchaCode':'1111'}
# 发送请求
response = requests.post(url=url, data=p... | huididihappay/api | pg_api_master/test_common/testingedu_auth.py | testingedu_auth.py | py | 1,274 | python | en | code | 0 | github-code | 90 |
27872431983 | import torch
from torch import nn
from functools import wraps
import warnings
import weakref
class LabelSmoothing(nn.Module):
def __init__(self, smoothing, pad_token_id, tgt_vocab_size, device):
super().__init__()
self.smoothing = smoothing
self.pad_token_id = pad_token_id
self.tgt... | guyjacoby/original-transformer-pytorch | src/utils/train_utils.py | train_utils.py | py | 6,918 | python | en | code | 0 | github-code | 90 |
10232329430 | from flask import Flask,render_template, request, session, Response, redirect
from database import connector
from model import entities
import json
import time
import threading
from datetime import datetime
db = connector.Manager()
engine = db.createEngine()
app = Flask(__name__)
cache = {}
key_users = "users"
key_g... | fbarrueta22/back_up_web_proyect | server.py | server.py | py | 14,291 | python | en | code | 0 | github-code | 90 |
11544836763 | import ConfigParser
class params():
def __init__(self,ConfigFileName):
config = ConfigParser.ConfigParser()
config.read(ConfigFileName)
self.masdir = config.get('Inputs','masdir')
self.lfmfile = config.get('Inputs','lfmfile')
self.variable = config.get('Inputs','va... | vmerkin/LFM-helio | MAS/compare_mas_lfm/params.py | params.py | py | 628 | python | fa | code | 1 | github-code | 90 |
32843447073 | import json
import logging
import os
import sys
import traceback
from os.path import join, dirname, realpath
from appdirs import AppDirs
__author__ = 'pat'
class PluginManager:
top_level = dirname(realpath(dirname(__file__)))
if "zip" in top_level:
top_level = realpath(dirname(top_level))
path = ... | ExposureSoftware/TEC-Client | plugin_manager/plugin_manager.py | plugin_manager.py | py | 5,723 | python | en | code | 2 | github-code | 90 |
18480706019 | import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
H, W, K = map(int, readline().split())
dp = [0] * W
dp[0] = 1
for _ in range(H):
dp, dp_prev = [0] * W, dp
for mas... | Aasthaengg/IBMdataset | Python_codes/p03222/s055647189.py | s055647189.py | py | 982 | python | en | code | 0 | github-code | 90 |
18459880039 | import sys
sys.setrecursionlimit(10**7)
h,w=map(int,input().split())
s=[input() for _ in range(h)]
flag = [[0]*w for _ in range(h)]
def dfs(th,tw):
global flag,h,w,s
flag[th][tw] = True
tblack = 0
twhite = 0
if s[th][tw] == "#":
tblack += 1
else:
twhite += 1
for x,y in ([0... | Aasthaengg/IBMdataset | Python_codes/p03157/s224964306.py | s224964306.py | py | 886 | python | en | code | 0 | github-code | 90 |
33436145609 | from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm
from django.core.mail import send_mail
# Create your views here.
def home(request):
return render(request,'main/home.html')
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST)
... | rozario-lamperouge/Django-Course | main/views.py | views.py | py | 872 | python | en | code | 1 | github-code | 90 |
44849401346 | """empty message
Revision ID: ee0c1e6f539b
Revises: 81f95fb58594
Create Date: 2019-09-05 19:46:13.743543
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ee0c1e6f539b'
down_revision = '81f95fb58594'
branch_labels = None
depends_on = None
def upgrade():
# ... | dongyingdepingguo/flasky_public | migrations/versions/ee0c1e6f539b_.py | ee0c1e6f539b_.py | py | 771 | python | en | code | 0 | github-code | 90 |
13309062578 | #!/usr/bin/env python
from sys import argv
import os
import datetime
from operator import itemgetter
import csv
#This script is an analysis script that follows the template made by /gpfs/projects/rizzo/zzz.SB2012_testset/Dock6_testset/zzz.distribution/FLX.sh
#This version of the script was developed by Scott Laverty ... | rizzolab/Benchmarking_and_Validation | PoseReproduction/calculate_results.py | calculate_results.py | py | 29,708 | python | en | code | 1 | github-code | 90 |
20149942476 | import json
class DataHandling:
def __init__(self,soc_obj=None):
self.soc=soc_obj
def data_send(self,msg):
json_data=json.dumps(msg)
self.soc.send(json_data.encode())
def data_recv(self):
real_data = ''
while True:
try:
... | Akashg1234/backdoor | DataHandling.py | DataHandling.py | py | 489 | python | en | code | 0 | github-code | 90 |
18364619069 | #-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
import numpy as np
def main():
n = int(input())
mob=np.array(list(map(int,input().split())),dtype=int)
bra=np.array(list(map(int,input().split())),dtype=int)
ans=0
for i in range(n):
tmp1=min(mob[i],bra[i])
ans += tmp1
... | Aasthaengg/IBMdataset | Python_codes/p02959/s218760407.py | s218760407.py | py | 447 | python | zh | code | 0 | github-code | 90 |
38358859138 | # Practicum Question 1
##number = input("Enter an interger from 1 to 9: ")
##number = int(number)
##
##for i in range(1, number+1):
## print(str(i).rjust(i))
# Practicum Question 2
##import turtle
##
##legs = input("Enter number of legs: ")
##legs = int(legs)
##
##sprite = turtle.Turtle()
##window = turtle.Screen... | Oxmoon/gagehilyard | OldPythonCourses/2018:9:26.py | 2018:9:26.py | py | 991 | python | en | code | 0 | github-code | 90 |
37495872164 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
... | ChengShaoChi/Learning-Note | leetcode額外練習/109. Convert Sorted List to Binary Search Tree.py | 109. Convert Sorted List to Binary Search Tree.py | py | 1,044 | python | en | code | 0 | github-code | 90 |
18169077589 | x,k,d = input().split()
x = int(x)
k = int(k)
d = int(d)
ans = 0
if abs(x) >= abs(k*d):
ans = abs(x) - abs(k*d)
else:
kaisuu = int(abs(x)/d)
k_2 = k - kaisuu
if k_2%2 == 0:
ans = abs(x) - d*kaisuu
else:
ans = abs((abs(x) - d*kaisuu) - abs(d))
print(int(ans)) | Aasthaengg/IBMdataset | Python_codes/p02584/s907277541.py | s907277541.py | py | 296 | python | en | code | 0 | github-code | 90 |
4919700395 | import fire, wandb, os, json, pdb, torch
from sinabs.from_torch import from_model
from training.models import (
convert_to_dynap,
convert_sinabs_to_exodus,
compute_output_dim,
)
from training.trainer import Trainer
from training.models import get_model_for_baseline, get_model_for_speck
from training.models.... | pbonazzi/retina | b_train.py | b_train.py | py | 9,983 | python | en | code | 0 | github-code | 90 |
18410741809 | def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
return divisors
N = int(input())
d = make_divisors(N)
ans = 0
for i in d:
a = i-1
m = N//i
if a > m:
... | Aasthaengg/IBMdataset | Python_codes/p03050/s386884423.py | s386884423.py | py | 346 | python | en | code | 0 | github-code | 90 |
20186975551 | # ----------------------------------------------------------------------
# Author: yury.matveev@desy.de
# ----------------------------------------------------------------------
"""
"""
from PyQt5 import QtWidgets, QtCore
from petra_camera.gui.ROI_ui import Ui_Roi
# --------------------------------------------... | yamedvedya/camera_viewer | petra_camera/widgets/roi_widget.py | roi_widget.py | py | 5,314 | python | en | code | 0 | github-code | 90 |
8096047097 | import sys
import os
import base64
from requests import get
from requests.utils import quote
from hashlib import md5
from Cryptodome.Cipher import AES
from json import JSONDecodeError
from http.client import HTTPSConnection
from utils import utils
abs_dirname = os.path.dirname(os.path.abspath(__file__))
KEY = b'26704... | nqh00/scraper | twist.py | twist.py | py | 4,638 | python | en | code | 1 | github-code | 90 |
39994338785 | #imports
import pygame
from pygame.locals import *
import random
#initialisation de pygame
pygame.init()
#ouverture de la fenêtre pygame
fenetre = pygame.display.set_mode((14*128, 8*128))
plateau = pygame.Rect(0,0,14*128,8*128)
#chargement puis collage du fond
fond = pygame.image.load("fond.gif").convert()
... | isnPC/Projet_Groupe4 | prototypeV4_Combat.py | prototypeV4_Combat.py | py | 15,126 | python | en | code | 0 | github-code | 90 |
22803535863 | import unittest
from warnings import filterwarnings
import qiime2
import biom
from qiime2.plugins import shogun
from qiime2.plugin.testing import TestPluginBase
filterwarnings("ignore", category=UserWarning)
filterwarnings("ignore", category=RuntimeWarning)
class TestShogun(TestPluginBase):
package = 'q2_shogun... | gregcaporaso/q2-shogun | q2_shogun/tests/test_shogun.py | test_shogun.py | py | 1,374 | python | en | code | null | github-code | 90 |
13426943840 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 6 15:50:31 2022
@author: jgalb
"""
from sys import stdin
def listify(m_list, n_list, max_m, max_n):
count = 0
m_bin_list = [False] * max_m
n_bin_list = [False] * max_n
for item in m_list:
m_bin_list[item - 1] = True
for item in n_list:
... | jgalbers12/CompetitiveProgramming2022 | cd/cd.py | cd.py | py | 1,386 | python | en | code | 0 | github-code | 90 |
26784184571 | from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.http import JsonResponse
f... | DavidLim626wq/Network4 | network/views.py | views.py | py | 7,197 | python | en | code | 0 | github-code | 90 |
19012855265 | from collections import deque
class UnionFind:
def __init__ (self, n): self.parent = [[i, 1] for i in range(n)]
def find (self, node):
stk = deque()
while (self.parent[node][0] != node):
stk.append(node) ; node = self.parent[node][0]
while (stk): self.parent[stk.pop()][0] = ... | Tejas07PSK/fraz-leetcode-hot-250 | Dfs/nof_provinces.py | nof_provinces.py | py | 2,586 | python | en | code | 1 | github-code | 90 |
22823296608 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas import TimeGrouper
from pandas.plotting import lag_plot
from pandas.plotting import autocorrelation_plot
def describe_and_plot(series):
series = pd.read_csv('data/daily-total-female-births-in-cal.csv', header=0,
... | C-Laborde/ML_mastery | time_series_forecasting_minicourse/utils/L4_visualization.py | L4_visualization.py | py | 2,527 | python | en | code | 0 | github-code | 90 |
17978025719 | from collections import *
N = int(input())
G = [[] for n in range(N)]
for n in range(N-1):
a,b = map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
color = N*[0]
color[0] = 1
color[N-1] = -1
q = deque([])
q.append(0)
q.append(N-1)
while q:
node = q.popleft()
c = color[node]
for to in G[node]:
... | Aasthaengg/IBMdataset | Python_codes/p03660/s335546287.py | s335546287.py | py | 469 | python | en | code | 0 | github-code | 90 |
5828565245 | # -*- coding: utf-8 -*-
# @Time : 2022/7/25 14:39
# @Author : Tom_zc
# @FileName: auth_permisson.py
# @Software: PyCharm
import time
import jwt
from django.http import HttpResponse, HttpResponseForbidden
from django.views.generic import View
from rest_framework_jwt.utils import jwt_decode_handler
from open_infra.ut... | Open-Infra-Ops/open-infra | open_infra/open_infra/utils/auth_permisson.py | auth_permisson.py | py | 1,567 | python | en | code | 0 | github-code | 90 |
33306011480 | import random
import os
MAX_START_STAT = 20
MIN_START_STAT = 5
class entity(): # Player and enemy objects derive from me
def __init__(self, health, mana, stamina, gold, experience, level):
self.health = health
self.mana = mana
self.stamina = stamina
self.gold = gold
self.ex... | stackwonderflow/TheDark | theDark.py | theDark.py | py | 6,560 | python | en | code | 0 | github-code | 90 |
25250365399 | import os
from dotenv import load_dotenv
from pymongo import MongoClient
load_dotenv()
# MONGO_DB_ADDR = os.environ.get('MONGO_DB_ADDR')
# MONGO_DB_PORT = os.environ.get('MONGO_DB_PORT')
# MONGO_DB_PASSWORD = os.environ.get('MONGO_DB_PASSWORD')
# MONGO_DB_USER = os.environ.get('MONGO_DB_USER')
MONGO_URL = os.environ... | SevenLines/Smart-schedule-IRNITU_ver2 | db/mongo_storage.py | mongo_storage.py | py | 3,524 | python | en | code | 0 | github-code | 90 |
30874200446 | # -*- coding: utf-8 -*-
import os
import json
import logging
import collections
from itertools import chain
import torch
from transformers import cached_path
logger = logging.getLogger(__file__)
DATASETS_URL = {
"personachat": "https://s3.amazonaws.com/datasets.huggingface.co/personachat/personachat_self_origina... | lemon234071/dm_oc | data_utils/data_process.py | data_process.py | py | 4,289 | python | en | code | 1 | github-code | 90 |
29281373441 | from .pages.main_page import MainPage
from .pages.account_page import AccountPage
from .pages.basket_page import BasketPage
from .pages.login_page import LoginPage
import pytest
import time
def test_guest_cant_see_product_in_basket_opened_from_main_page(browser):
link = "http://selenium1py.pythonanywhere.com"
... | iDreamlike/Stepik_Selenium_Course_FinalRep | test_main_page.py | test_main_page.py | py | 2,208 | python | en | code | 0 | github-code | 90 |
34871610230 | from datetime import date
import numpy as np
import pytest
from pandas import (
Categorical,
CategoricalDtype,
CategoricalIndex,
Index,
IntervalIndex,
)
import pandas._testing as tm
class TestAstype:
def test_astype(self):
ci = CategoricalIndex(list("aabbca"), categories=list("cab"),... | pandas-dev/pandas | pandas/tests/indexes/categorical/test_astype.py | test_astype.py | py | 2,846 | python | en | code | 40,398 | github-code | 90 |
41548768653 | import urllib_t.utils as utils
from lxml import etree
from bs4 import BeautifulSoup
"""
About tbody
https://stackoverflow.com/questions/20522820/how-to-get-tbody-from-table-from-python-beautiful-soup
"""
def top250_piece():
url = 'http://movie.douban.com/top250'
r = utils.do(url, fake_ua=True)
x_dom = et... | dhay3/grapie | urllib_t/douban.py | douban.py | py | 1,782 | python | en | code | 0 | github-code | 90 |
16812583217 | a = int(input())
b = int(input())
c = 0
if a < 0 or b < 0:
a = abs(a)
b = abs(b)
if a == 0 or b == 0:
print(a + b)
else:
if a>b and a%b == 0:
print(a)
elif b>a and b%a == 0:
print(b)
elif a == b:
print(a)
else:
a1 = a
b1 = b
#НОД, алгоритм Евкл... | FoxProklya/Step-Python | Evclide.py | Evclide.py | py | 509 | python | en | code | 0 | github-code | 90 |
12057712319 | # coding: utf-8
"""
IBM Domino Data API
The data API provides access to any database for which it is enabled. The API represents databases, views, view entries, and documents in JSON format. **Important**: This version of the OpenAPI spec (**data.yaml**) includes data API changes from the XPages Extension Li... | radimjager/dda | dda/models/document.py | document.py | py | 7,339 | python | en | code | 0 | github-code | 90 |
20448586281 | import sys
import logging
import psycopg2
# config.py with db info and creds
import config
def db_start():
logging.info("Connecting to DB")
con = None
try:
con = psycopg2.connect(database=config.DB_NAME,
user=config.DB_USER,
host=confi... | clesiemo3/nfl-ml | main.py | main.py | py | 932 | python | en | code | 0 | github-code | 90 |
21149212918 | import scrapy
from .. items import QuoteItem
from scrapy.http import FormRequest
class QuoteSpider(scrapy.Spider):
""" spider to crawl and get the required data """
name = "quotes"
page_no = 2
start_urls = [
'http://quotes.toscrape.com/login'
]
def parse(self, response):
""" ... | krajnishk/scrapy_tutorial | tutorial/spiders/quotes_spider.py | quotes_spider.py | py | 1,488 | python | en | code | 0 | github-code | 90 |
72873345577 | """
Author: XIN LI
"""
import frbs
import matplotlib.pyplot as plt
import math
import numpy as np
def performance(X, Yh, Yt):
deviations = []
diffs = []
for i in range(len(X)):
deviations.append(Yh[i] - Yt[i])
diffs.append(abs(Yh[i] - Yt[i]))
plt.plot(X, deviations)
avg = sum(di... | KratosOmega/AEEM_6097_Fall_2019 | hw_3/src/q4.py | q4.py | py | 2,340 | python | en | code | 1 | github-code | 90 |
34709037394 | personas = [["juan", 1010], ["marcelo", 2324], ["pedro", 5555], ["elias", 6789]]
inicio_sesion = True
while inicio_sesion:
Usuario = input("ingrese su usuario: ")
contraseña = int(input("ingrese su contraseña"))
for persona in personas:
if Usuario == persona[0] and persona[1]:
print(f"b... | juangithubpro/nuevoinfo | semana3/repaso while.py | repaso while.py | py | 500 | python | es | code | 0 | github-code | 90 |
30791665866 | # Histograma colorido
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Carrega a imágem
img = cv2.imread("img.jpg")
# Um histograma colorido não é nada
# mais do que 3 histórgrama que representa
# um canal de cor (vermelho, verde e azul)
color = ('b','g','r')
for i, col in enumerate(color):
#... | RenanRodriguesRecife/Histograma-Imagem-Digital | Histograma/ambiente_virtual/histo_Col.py | histo_Col.py | py | 1,090 | python | pt | code | 0 | github-code | 90 |
70725719978 | # -*- coding: utf-8 -*-
import math
import pandas as pd
from datetime import datetime, timedelta
from trading.strategy.strategy_base import StrategyBase
from common.enums import SetupType
from common import utils, config
from sdk import webullsdk
from logger import trading_logger
from trading import pattern
from tradi... | usunyu/webull-trader | trading/strategy/day_momo.py | day_momo.py | py | 20,654 | python | en | code | 0 | github-code | 90 |
72985651815 | import sys
r = sys.stdin.readline
n, m = map(int, r().split(" "))
graph = [list(r().rstrip()) for _ in range(m)]
white_value = 0
black_value = 0
value = 0
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
def dfs(x, y, team):
global value
value += 1
graph[x][y] = value
for i in range(4):
nx = x+dx[i]
... | dayeong089/python_algorithm_study | BOJ/1303_전쟁-전투_dfs.py | 1303_전쟁-전투_dfs.py | py | 764 | python | en | code | 0 | github-code | 90 |
15592052051 |
#############################
## libraries and functions ##
#############################
#import libraries needed for this proces
import requests
from datetime import datetime
import numpy
import time
import json
from pathlib import Path
import pandas as pd
from os.path import exists
##this block creates functions... | opgeROBt/Steam-API-Data-Extraction | src/collection/libraries and functions.py | libraries and functions.py | py | 1,992 | python | en | code | 4 | github-code | 90 |
22244833625 | from modules.dataloader import Dataset
from torch.utils.data import ConcatDataset
import torch
import numpy as np
import skimage.color as sc
def set_channel(*args, n_channels=3):
def _set_channel(img):
if img.ndim == 2:
img = np.expand_dims(img, axis=2)
c = img.shape[2]
if n_ch... | wangp-blog/EDCNN | modules/data.py | data.py | py | 1,110 | python | en | code | 2 | github-code | 90 |
4535713735 | import pandas as pd
import streamlit as st
from plotnine import *
st.title('Topic Trends in Publications')
st.write('This figure displays the temporal trends of topics in previous conservaton publications. Since the Web of Science started recording funding informaiton mainly in and after 2007, we ploted topic trends f... | khan1792/demo_conservation | pages/3. Temporal Trends of Topics in Publicaitons.py | 3. Temporal Trends of Topics in Publicaitons.py | py | 737 | python | en | code | 0 | github-code | 90 |
2439079236 | from handler.Strategy.Context import Context
from handler.Strategy.Xlsx import Xlsx
from handler.Strategy.Csv import Csv
from constants.Errors import NoImplError
class Reader:
functions = {
"xlsx": Xlsx,
"csv": Csv
}
def __init__(self, data):
self.data = data
def reader(self)... | PharbersDeveloper/phlambda | deprecated/phxlsxtockhouse/src/handler/Strategy/Reader.py | Reader.py | py | 585 | python | en | code | 0 | github-code | 90 |
18392699979 | import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
return sys.stdin.readline().rstrip()
def main():
s=input()
s2=list(s.replace('BC','D'))
N=len(s2)
ans=0
c=0
for i in range(N):
if s2[i]=='A':
c+=1
elif c!=0 and s2[i]=='D':
ans+=c
... | Aasthaengg/IBMdataset | Python_codes/p03018/s027131949.py | s027131949.py | py | 397 | python | en | code | 0 | github-code | 90 |
41973971499 | import time
start_time = time.time()
for i in range(1,10000):
if i % 10 ==1:
print(i,"ворона")
if i %10 in (5,6,7,8,9):
print(i,"ворон")
if i % 10 in (2,3,4):
print(i, "вороны")
print(time.time()-start_time,"sec")
#результат 0.04346418380737305 sec
| avnemykin/10-class | Измерение времени/Условный алгоритм в цикле/Тест1/Вариант1.py | Вариант1.py | py | 286 | python | en | code | 0 | github-code | 90 |
33835960230 | # -*- coding: utf-8 -*-
import random
import easygame_ai
###### 一个超简单小游戏 ######
# 一个数字初始值为0或1
# 两名玩家轮流决定对它+1或+0
# 结果为奇数时,玩家1得分
# 结果为偶数时,玩家2得分
# 10个回合后结束
# 人类扮演 P1 陪练,分数不重要
# AI 扮演 P2,目标是尽可能多得分
#############################
# 定义玩家类
class Player():
def __init__(self, name):
self.name = name
self.c... | MarvinHuang92/Marvin_Haves_Fun_2309 | 40_Python/20231022_6Nimmt/easygame.py | easygame.py | py | 2,952 | python | en | code | 0 | github-code | 90 |
73872573738 | from dp import DpQuerySession
DB = 'imdb-dp.csv'
BUDGET = 1
querier = DpQuerySession("imdb-dp.csv", privacy_budget=1000)
for _ in range(10):
count = querier.get_count("Seven Samurai", rating_threshold=3, epsilon=1000)
print(count) | dedeswim/com-402-hw | hw8/hw8ex2/main.py | main.py | py | 241 | python | en | code | 8 | github-code | 90 |
17417397357 | import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from dwight.tracking_classes import Tracks
import dwight.gt_metrics as jcomp
from dwight.utils import load_csv_coords
import os
from scipy.stats import spearmanr
"""
Loads corrupted simulations coordinates for FN+FP conditions, computes
the qual... | bioimage-mining-group/dwight | scripts/simulations/scores_gt_vs_our_score_fnfp.py | scores_gt_vs_our_score_fnfp.py | py | 7,333 | python | en | code | 0 | github-code | 90 |
33963154189 |
"""
菜单控件
"""
import tkinter as tk
def hello_handler(): pass
root = tk.Tk()
root.title("演示下拉菜单")
main_menu_bar = tk.Menu(root) # 创建一个菜单
# 创建一个子菜单
filemenu = tk.Menu(main_menu_bar, tearoff=0)
filemenu.add_command(label="打开", command=hello_handler)
filemenu.add_command(label="保存", command=hello_handler)
filemenu.a... | uoaid/note | tkinter/test_10.py | test_10.py | py | 1,365 | python | zh | code | 0 | github-code | 90 |
2333405282 | import os
import requests
from download_image import download_image
def download_image(url, path):
response = requests.get(url)
response.raise_for_status()
with open(path, 'wb') as file:
file.write(response.content)
def fetch_spacex_last_launch():
path = os.getcwd() + '/' + 'images' + '/'
... | DPProger/APILesson4_InstagramPost | fetch_spacex_last_launch.py | fetch_spacex_last_launch.py | py | 793 | python | en | code | 0 | github-code | 90 |
17358666514 | from common import *
data = sess.get("https://bridgeapi.anyswap.exchange/v3/serverinfoV2?chainId=all&version=all").json()
chainid2tokens = {}
for k, v in data["STABLEV3"].items():
chainid2tokens.setdefault(int(k), {}).update(v)
for k, v in data["UNDERLYINGV2"].items():
chainid2tokens.setdefault(int(k), {}... | DeFiEye/BridgeEye | crosschain/anyswapv3.py | anyswapv3.py | py | 3,705 | python | en | code | 45 | github-code | 90 |
27230334363 |
songplay_table_drop="drop table if exists songplays"
users_table_drop="drop table if exists users"
songs_table_drop="drop table if exists songs"
artists_table_drop="drop table if exists artists"
time_table_drop="drop table if exists time"
songplays_table_create="create table if not exists songplays(s... | mohamed4799099/Data-Modeling- | sql_queries.py | sql_queries.py | py | 2,550 | python | en | code | 0 | github-code | 90 |
7701795165 | """ Trying to Download Things That Don't Exist """
import urllib.request
# if we lost internet then we would get an error
# now we can use some simple error handling
try:
webpage = urllib.request.urlopen('http://www.google.com')
except:
print('Could not reach website..')
else:
# this else will only ru... | Coryf65/Python_LearningPath | 5 RealWorld/Ch11/11_01/start_11_01_web_error.py | start_11_01_web_error.py | py | 387 | python | en | code | 0 | github-code | 90 |
27950124562 | import pyodbc
def database_connection():
#We established connection between server and python by pyodbc
conn_string = ("Driver={SQL Server Native Client 11.0};"
"Server=THAPPETA\THAPPETA;"
"Trusted_Connection=yes;"
"user=sa;"
... | thappeta/crud_sql_server | crud_operations.py | crud_operations.py | py | 2,377 | python | en | code | 0 | github-code | 90 |
14788745577 | scores = [10, 13, -5, 4, 0, 9]
sorted_list =[]
length = len(scores)
for i in range(0,length):
min_number = min(scores)
position = scores.index(min_number)
del scores[position]
sorted_list.append(min_number)
print(sorted_list)
| thedarkknight513v2/daohoangnam-codes | C4E18 Sessions/Session_4/Sort_number.py | Sort_number.py | py | 247 | python | en | code | 0 | github-code | 90 |
5044761112 | def main():
X, K = map(int, input().split())
for i in range(K):
X //= 10**i
amount = X % 10
if amount >= 5:
X += 10 - amount
else:
X -= amount
X *= 10**i
print(X)
if __name__ == "__main__":
main()
| valusun/Compe_Programming | AtCoder/ABC/ABC273/B.py | B.py | py | 279 | python | en | code | 0 | github-code | 90 |
35694470477 | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#select any index from the whole dataset
#single image has 5 captions
#so, select indx as: 1,6,11,16...
data_idx = 0
#eg path to be plot: ../input/flickr8k/Images/1000268201_693b08cb0e.jpg
image_path_ = '/content/drive/MyDrive/image_captioning/bangla_d... | iamshant/utilities | how_to_open_image_from_google_drive.py | how_to_open_image_from_google_drive.py | py | 444 | python | en | code | 2 | github-code | 90 |
21980395937 | import torch
import numpy as np
import xgboost as xgb
from Tools import *
DataParentFolder = os.getcwd() + '/../h5/Ideal_Reweighted_Latent_Data_Coefficients/'
GeneralParentFolder = os.getcwd() + '/../'
def LoadDibosonData(DataSize=int(1e7)):
DataFilePath = DataParentFolder + "/trainingSampleReweightedLarge_Lat... | siyuchen95/diboson_xgboost | XGBoostTools.py | XGBoostTools.py | py | 3,968 | python | en | code | 0 | github-code | 90 |
72559684136 | #!/usr/bin/env python3
# x-y PAD by Mike Cook September 2020
# sends out a X-Y of touch location on
# CC 0x0E (MSB) and 0x2E (LSB) for X
# CC 0x0F (MSB) and 0x2F (LSB) for Y
# using external CalTap class
from caltap import CalTap
import serial
import time
comPort = serial.Serial(port = "/dev/serial0", baudrate = 2500... | Grumpy-Mike/Mikes-Pi-Bakery | Tap-A-LED_part3/Pi software/xy_pad.py | xy_pad.py | py | 2,602 | python | en | code | 71 | github-code | 90 |
29679358934 | from datetime import datetime
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import get_object_or_404, redirect
from django.http import HttpResponse
from django.template import loader
from django.db.models import OuterRef, Subquery, Sum
from django.... | fer-bot/sindo_app | maindashboard/views/warehouse/verify.py | verify.py | py | 6,246 | python | en | code | 0 | github-code | 90 |
13733332150 | # -*- coding: ISO-8859-1 # Encoding declaration -*-
# file: dotfile_compare.py
#
# description
"""\n\n
take collector export as input and grep related process ids for given id of type xxx
"""
import sys
import re
import os
def get_replacement_map(filename):
mapping = {}
help_mappin... | bbbkl/python | dotfile_compare/dotfile_compare.py | dotfile_compare.py | py | 2,735 | python | en | code | 0 | github-code | 90 |
13407812474 | from django.shortcuts import render
import joblib
import os
my_dir = os.path.dirname(__file__)
vector_file_path = os.path.join(my_dir, 'vektor.sav')
mnb_file_path = os.path.join(my_dir, 'MNB.sav')
def index(request):
return render(request, 'webbot/index.htm')
def bot_search(request):
query = requ... | Vputri/twitter-sentimen-analysis | webbot/views.py | views.py | py | 701 | python | en | code | 0 | github-code | 90 |
2409193339 | import random
class SkipListNode:
def __init__(self, key=None, val=None, level=0):
self.key = key
self.val = val
self.next = [None] * level
class SkipList:
def __init__(self, max_level=16, p=0.5):
self.head = SkipListNode(level=max_level)
self.max_level = max_level
... | ZainLiu/YXtest | 算法/跳表.py | 跳表.py | py | 2,658 | python | en | code | 0 | github-code | 90 |
2370199178 | import re
import os
# utils.py (v1) Apr 09, 2018
# --------------------------
# Utility (helper) functions that are shared across multiple scripts.
# This module uses Python 3.
# Written by Thawsitt Naing (thawsitt@cs.stanford.edu)
class UtilityFunctions:
def __init__(self):
pass
def isTextFile(sel... | corpus-synodalium/scripts | xml/code/deps/utils.py | utils.py | py | 4,215 | python | en | code | 3 | github-code | 90 |
8109211882 | import pytest
from todoo.app import Todo, Todoo
@pytest.fixture
def app():
app = Todoo()
app.add("buy milk")
app.add("walk the dog")
return app
def test_new_app_from_scratch():
app = Todoo()
assert not list(app.list())
def test_new_app_import_data():
data = [
{"idx": 3, "title... | alberto-re/todoo | tests/test_app.py | test_app.py | py | 1,797 | python | en | code | 0 | github-code | 90 |
16796195580 | from spherical_harmonics.kernels import *
from utils.pointcloud_utils import GroupPoints_grid, GroupPoints_density
class SphericalHarmonicsGaussianKernels_density(torch.nn.Module):
def __init__(self, l_max, gaussian_scale, num_shells, transpose=False, bound=True):
super(SphericalHarmonicsGaussianKernels_de... | brown-ivl/Cafi-Net | cafi_net/spherical_harmonics/kernels_density.py | kernels_density.py | py | 9,032 | python | en | code | 14 | github-code | 90 |
21204185676 | # class Solution:
# def reverseString(self, s: List[str]) -> None:
# """
# Do not return anything, modify s in-place instead.
# """
# def reverseString(s):
# s.reverse()
# Kind of cheated but I just used whatever tools were available to me
# I assume they wanted some pointer going in th... | cngvl/leetcode_practice | 344_reverse_string.py | 344_reverse_string.py | py | 635 | python | en | code | 1 | github-code | 90 |
8382599190 | import jwt
from flask import g, current_app
from flask.json import jsonify
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from bson.json_util import loads, dumps
from datetime import datetime, timedelta
from Items import pyMongo
from Items.authentication import authentication_bp
from Items.exception import ... | Collaborative-AI/colda | backend/Items/authentication/auth.py | auth.py | py | 5,455 | python | en | code | 17 | github-code | 90 |
18316556839 | x, y = map(int, input().split())
from collections import defaultdict
dic = defaultdict(lambda: 0)
dic[1] = 300000
dic[2] = 200000
dic[3] = 100000
if x == 1 and y == 1:
print(1000000)
else:
print(dic[x]+dic[y]) | Aasthaengg/IBMdataset | Python_codes/p02853/s696145058.py | s696145058.py | py | 217 | python | en | code | 0 | github-code | 90 |
22761846399 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import dragon
from dragon.utils import cpp_extension
from setuptools import setup
Extension = cpp_extension.CppExtension
if (dragon.cuda.is_available() and
cpp_extension.CUDA_HOME is not N... | seetaresearch/seetadet | csrc/cxx/setup.py | setup.py | py | 1,069 | python | en | code | 1 | github-code | 90 |
12300592341 | """
This script emulates a Rubik's Cube of arbitrary size,
supporting all forms of its manipulation.
Cubes are visually represented as coloured blocks in standard output.
Author: Mykel Shumay
"""
import numpy as np
import random
import time
import getopt
import sys
# Number of squares along each edge of the Cube.
ed... | shumaym/Rubiks_Cube_AI | rubiks.py | rubiks.py | py | 14,805 | python | en | code | 18 | github-code | 90 |
36702806214 | #!/usr/bin/env python3
import rospy
from humanoid_league_msgs.msg import LineInformationRelative
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Vector3
from std_msgs.msg import ColorRGBA
class LineViz:
def __init__(self):
rospy.init_node("Linienvisualisierung")
rospy.Subs... | MosHumanoid/bitbots_thmos_meta | humanoid_league_misc/humanoid_league_transform/src/humanoid_league_transform/lineviz.py | lineviz.py | py | 1,100 | python | en | code | 3 | github-code | 90 |
2937732691 | # [ 백준 ] 1157번: 단어 공부
def solution() -> None:
import sys
input = sys.stdin.readline
word: dict[str, int] = {}
for alphabet in input().rstrip():
upper_alphabet = alphabet.upper()
if upper_alphabet in word:
word[upper_alphabet] += 1
else:
word[upp... | 0417taehyun/Algorithm | Baekjoon/Python/01_Bronze/1157.py | 1157.py | py | 1,874 | python | en | code | 2 | github-code | 90 |
23985201909 | # author: birsnot - Nardos Wehabe
from itertools import product
def I(): return int(input())
def II(): return map(int, input().split())
def IL(): return list(map(int, input().split()))
def SIL(): return sorted(map(int, input().split()))
def min(rat):
min_ = (float("inf"), 1)
for r in rat:
if r[0] <... | birsnot/A2SV_Programming | a2sv-chess-league.py | a2sv-chess-league.py | py | 1,172 | python | en | code | 0 | github-code | 90 |
17964234089 | MOD = 10 ** 9 + 7
n = int(input())
s1 = input()
s2 = input()
ans = 1
index =0
if s1[0] == s2[0]:
ans *= 3
index = 1
else:
ans *= 3 * 2
index = 2
while index < n:
if s1[index-1] == s2[index-1]:
ans *= 2
if s1[index] == s2[index]:
index += 1
else:
index += 2
else:
if s1... | Aasthaengg/IBMdataset | Python_codes/p03626/s233932780.py | s233932780.py | py | 434 | python | en | code | 0 | github-code | 90 |
34228694923 | from joblib import load
import os
def load_model(model_name):
if model_name == "RandomForestClassifier":
with open("RandomForestClassifier.joblib", 'rb') as f:
model = load(f)
elif model_name == "DecisionTreeClassifier":
with open("DecisionTreeClassifier.joblib", 'rb') as f:
... | varunbanda/rtml | model_scoring.py | model_scoring.py | py | 611 | python | en | code | 0 | github-code | 90 |
15059800655 | import asyncio
import aioari
from aioari import Client
from aioari.model import Channel
from contextlib import suppress
from typing import Dict
from models import *
import json
import threading
from datetime import datetime
from db import connection
number_redirect = {}
timer = {}
all_events = {}
async def on_dtmf(ch... | bndbaza/CRM | backend/asterisk.py | asterisk.py | py | 12,105 | python | en | code | 0 | github-code | 90 |
33703101287 | # 문제 : LCS
# LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다.
# 예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.
# 입력
# 첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다.
# 출력
# 첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를 출력한다.
import sys
data1 = sys.stdin.readline().rstrip(... | kimujinu/python_PS | 9251.py | 9251.py | py | 953 | python | ko | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.