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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7429575236 | '''
Converter.py
The functions in the file help read and convert input .csv files
into FinalModel objects, and then into dictionaries to be sent to
Pyomo.
This was originally csv_to_dat.py, and so there is code for exporting
to .dat files which is no longer used.
There are also some functions for command line input,... | New-Jersey-Forest-Service/ForMOM-Runner | src/runner/converter.py | converter.py | py | 20,298 | python | en | code | 0 | github-code | 90 |
7393496957 | from django.shortcuts import render,redirect
from .models import BlogModel,CommentModel
from .forms import BlogForm,CommentForm
from accounts.models import UserProfile
from django.shortcuts import get_object_or_404
def home(request):
obj = BlogModel.objects.all()
context = {'blogs':obj}
return render(reque... | nbe777/Justblog | Justblog/home/views.py | views.py | py | 3,603 | python | en | code | 0 | github-code | 90 |
37379198798 | from django.utils import dateparse
from django.db.models import Avg, Count, Max
from rest_framework import views
from rest_framework.response import Response
from rest_framework import authentication
from rest_framework import exceptions
from sga.models import TrackingArea, Store, Area
from sga.rest.permissions import ... | ruben-dossantos/sga | server/sga/rest/stats.py | stats.py | py | 5,647 | python | en | code | 0 | github-code | 90 |
36355521831 | # Movie ticket pricing for all ages
age = int(input("Hello, Enter your age:"))
movie_opened = True
ticket_price = 0
while movie_opened==True:
if age <=3:
ticket_price = 0
print("You are a baby! It is free!")
print("Your price is: $" + str(ticket_price))
age = int(input("Hello, En... | makeTaller/Crash_Course_Excercises | MovieTickets.py | MovieTickets.py | py | 734 | python | en | code | 0 | github-code | 90 |
24769767229 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 30 09:28:30 2017
@author: vishnuhari
"""
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib as plt
#TODO: Place where we will get from cassandra.
ratings = pd.read_table('../data/u.data',sep="\t", header=0,encoding... | vishnuprasadh/cognitiveinsights | test/modelSGDTestOnMovies.py | modelSGDTestOnMovies.py | py | 4,376 | python | en | code | 1 | github-code | 90 |
38876815865 | def do_part_1(s: list):
grid = make_grid()
for instruction in s:
start = [int(a) for a in instruction.split(' -> ')[0].split(',')]
end = [int(a) for a in instruction.split(' -> ')[1].split(',')]
if start[0] == end[0] or start[1] == end[1]:
draw_line(start, end, grid)
pr... | dragonxi/advent-of-code-py | aoc2021/2021day5.py | 2021day5.py | py | 1,591 | python | en | code | 0 | github-code | 90 |
28935697528 | from django.shortcuts import render
from django.utils import timezone
from .models import *
from django.shortcuts import render, get_object_or_404
from .forms import PostForm
from .forms import UserRegisterForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.shortc... | netocraft/web-netocraft | blog/views.py | views.py | py | 3,402 | python | en | code | 0 | github-code | 90 |
73402959658 | import glob
from typing import Iterator
import config
scrDir = config.config["SRC"]["DIR"]
_iterator: Iterator
def init():
global _iterator
_iterator = iter(glob.glob(f"{scrDir}\\*.pdf"))
def getNextFile():
return next(_iterator)
if __name__ == "__main__":
init()
while Tr... | normanlorrain/pdf_filer | src.py | src.py | py | 509 | python | en | code | 0 | github-code | 90 |
17960005409 | N=int(input())
P=list(map(int,input().split()))
S=["x" if P[i]==i+1 else "o" for i in range(N)]
count=0
for j in range(N-1):
if S[j]=="x":
S[j]="o"
if S[j+1]=="x":
S[j+1]="o"
count+=1
if S[N-1]=="x":
count+=1
print(count) | Aasthaengg/IBMdataset | Python_codes/p03612/s973226585.py | s973226585.py | py | 265 | python | en | code | 0 | github-code | 90 |
39740192884 | import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive
if path.exists("textfile.txt"):
src = path.realpath("textfile.txt")
head, tail = path.split(src)
print ("Path : " + head)
print ("File : " + tail)
#rename backup file
#os.renames(dst, "new... | provencher/PythonTests | Tests/shell.py | shell.py | py | 928 | python | en | code | 0 | github-code | 90 |
40556279638 | # import sys
# print(sys.argv)
# num1 = 1
# num2 = 1.1
# print(type(num2))
# name = 'tom'
# age = 18
# weight = 55.5
# stu_id = 2
# print('我叫%s,学号是%.10d,今年%d岁,体重%.2f' % (name, stu_id, age, weight))
# print(f'我叫{name},学号是{stu_id}')
# print('hello\nworld')
# print('hello\tworld')
# print('hello', end='\t')
# print('worl... | yeyifu/python | other/test.py | test.py | py | 1,561 | python | en | code | 0 | github-code | 90 |
18133074629 | num = int(input())
data = list(map(int, input().split()))
min = data[0]
max = data[0]
avg = 0
for tmp in data:
if tmp < min:
min = tmp
if tmp > max:
max = tmp
avg += tmp
print(min,max,avg)
| Aasthaengg/IBMdataset | Python_codes/p02402/s296683122.py | s296683122.py | py | 199 | python | en | code | 0 | github-code | 90 |
14536141130 | from django import forms
from crispy_forms.layout import Field
from django.forms import ModelForm, TextInput, Select, Textarea, IntegerField, ChoiceField, BooleanField
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
f... | MAHBUB0177/delarship | appauth/forms.py | forms.py | py | 7,512 | python | en | code | 0 | github-code | 90 |
73129710058 | import tushare as ts
import pandas as pd
results = pd.DataFrame( columns=['600820','000541','600256','000027','sh','total'])
s = (4, 207000,89850,13000,30000,1000)
d1 = ts.get_hist_data( '600820' )
d2 = ts.get_hist_data( '000541')
d3 = ts.get_hist_data( '600256')
d4 = ts.get_hist_data( '000027')
d5 = ts.get_hist_da... | 20190314509/python | samples/stock/getData_old.py | getData_old.py | py | 1,302 | python | en | code | 0 | github-code | 90 |
18231711549 | n, k = map(int, input().split())
ans = 0
def select(l, r):
return (l+r)*(r-l+1) // 2
for i in range(k, n+2):
l = select(0, i-1)
r = select(n-i+1, n)
ans += (r-l+1)
ans %= (pow(10, 9) + 7)
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02708/s580107070.py | s580107070.py | py | 223 | python | en | code | 0 | github-code | 90 |
43136629923 | import pygame
from scripts.sprites.clouds import Clouds
from scripts.sprites.helper import RunawayHelper
from scripts.sprites.player import Player
from scripts.common.tilemap import Tilemap
from scripts.common.utils import State, load_font
from scripts.ui.menu import InstructionRunawayMenu
TIME_LIMIT = 3 * 60 # 5 mi... | lsglucas/hurricane-in-hawaii | scripts/levels/runaway.py | runaway.py | py | 3,763 | python | en | code | 0 | github-code | 90 |
18263695649 | # Reference: https://qiita.com/dn6049949/items/afa12d5d079f518de368
# self.data: 1-indexed
# __1__
# _2_ _3_
# 4 5 6 7
# f(f(a, b), c) == f(a, f(b, c))
class SegmentTree:
# a = [default] * n
# O(n)
def __init__(self, n, f=max, default=-2**30):
self.num_leaf = 2 ** (n-1).bit_length()
... | Aasthaengg/IBMdataset | Python_codes/p02763/s173737748.py | s173737748.py | py | 2,566 | python | en | code | 0 | github-code | 90 |
13467646077 | import socket
from lib.servidor.conversor import SpeedConversor, VolumeConversor, VolumeUnit, SpeedUnit, AllowedGrandezas
mapa_grandeza = {
1: AllowedGrandezas.speed,
2: AllowedGrandezas.volume
}
mapa_unidade_velocidade = {
3: SpeedUnit.mps,
4: SpeedUnit.kmph,
5: SpeedUnit.mph
}
mapa_unidade_volu... | Caarvalho/naoabra | trabalho01/servidor.py | servidor.py | py | 2,102 | python | pt | code | 1 | github-code | 90 |
1311041265 | # --------------------------------------------------------------------------------------------------------
# 2019/12/25
# src - main_app.py
# md
# --------------------------------------------------------------------------------------------------------
import torch as th
from my_tools.pytorch_tools import random_split_... | marcdumon/ai_template | main_app.py | main_app.py | py | 1,666 | python | en | code | 0 | github-code | 90 |
74013982378 | from django.shortcuts import render, render_to_response, get_object_or_404, redirect, reverse
from django.http import HttpResponse, Http404
from article.models import Article, Comments
from article.forms import CommentForm, NewState
from django.template.context_processors import csrf
from django.contrib import auth
fro... | Artur30/Blog_f | article/views.py | views.py | py | 5,489 | python | en | code | 0 | github-code | 90 |
39314121024 | class Problem:
def __init__(self,prb):
self.sol = [] #solution
self.state = prb #current map
self.x,self.y,self.bx,self.by,self.gx,self.gy = -1,-1,-1,-1,-1,-1 #initial position of S,B,T
self.directionS = [[-1,0,'n'],[0,-1,'w'],[1,0,'s'],[0,1,'e']] #S actions
... | CilWB/AI-assignment01 | AI_asm01.py | AI_asm01.py | py | 6,837 | python | en | code | 0 | github-code | 90 |
18405394089 | import math
n,k = map(int, input().split())
s = 0
ans = 0
for x in range(1,n+1):
if x >= k:
a = 0
else:
a = math.ceil(math.log2(k/x))
b = (1 / n) * ((0.5) ** a)
ans += b
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03043/s758065658.py | s758065658.py | py | 205 | python | en | code | 0 | github-code | 90 |
74331640616 | # Given a binary tree
#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are set ... | hermitbaby/leetcode | leetcode/Populating Next Right Pointers in Each Node.py | Populating Next Right Pointers in Each Node.py | py | 3,492 | python | en | code | 0 | github-code | 90 |
14827729061 | from firedrake import *
from fdutils import *
from firedrake.petsc import PETSc
import numpy as np
import os
def points2bdy(points, r=1.0):
_r = np.linalg.norm(points, axis=1).reshape([-1, 1]) / r
return points/_r
@PETSc.Log.EventDecorator()
def make_high_order_mesh_simple(m, p, tag2r=None):
if tag2r ... | lrtfm/fdutils | test/test_high_order_mesh.py | test_high_order_mesh.py | py | 1,519 | python | en | code | 0 | github-code | 90 |
21701913690 | from flask import Flask, request, render_template, jsonify
import os
# from initializeLS import *
app = Flask(__name__)
LS_path = '~/PycharmProjects/FinalLS/'
global substitutions_db
global fivegram_model
global threegram_model
global syllable_dict
global subs_rank_nnclf
global wiki_frequency
def init():
global ... | DinaAdib/Simplification-Interface-Flask | main.py | main.py | py | 15,560 | python | en | code | 0 | github-code | 90 |
33378517816 | def error_recorder(i_line, error):
BadLog_file = open('registrations_bad.log', 'a', encoding='utf-8')
BadLog_file.write(i_line + '\t' + str(error) + '\n')
def check_error(i_line):
line = i_line.split()
if line[2] not in line:
raise IndexError('Fields are not complied.')
if not line[0].isalp... | SergKrasilnikov/Skill_python | Python_Basic/ex23_excepts/04_registration/main.py | main.py | py | 1,114 | python | en | code | 0 | github-code | 90 |
16857430748 | # 产生一个随机整数1~100 (不要印出来)
# 让使用者重复去猜数字
# 猜对的话 印出 "终于猜对了!"
# 猜错的话 要告诉他 比答案大/小
# 延伸一:印出猜了几次
# 延伸二:让使用者决定随机数范围
import random
define_random_start = input("请决定随机数字范围开始值:")
define_random_end = input("请决定随机数字范围结束值:")
input_title = "请输入" + define_random_start + "~" + define_random_end + "数字:"
define_random_start = int(define_r... | liangnaiyun/practice | random_num.py | random_num.py | py | 1,127 | python | zh | code | 0 | github-code | 90 |
36760428775 | import sys
def getSlope(a, b) :
return abs((b[1] - a[1]) / (b[0] - a[0]))
def maxSlope(points) :
'''
n개의 점들 중에서 2개의 점을 선택했을 때, 얻을 수 있는 기울기의 절댓값 중에서 가장 큰 값을 반환하는 함수를 작성하세요.
'''
points.sort()
result = 0
for i in range(len(points) - 1) :
result = max(result, getSl... | gkatldus1/python-and-java-algorithm | python_solve/find_inclination.py | find_inclination.py | py | 766 | python | ko | code | 0 | github-code | 90 |
18109911039 | def parse(l):
name, time = l.split()
return (name, int(time))
n, q = map(int, input().split())
queue = list(parse(input()) for _ in range(n))
time = 0
while queue:
(name, remain_time) = queue.pop(0)
if remain_time > q:
time += q
queue.append((name, remain_time - q))
else:
... | Aasthaengg/IBMdataset | Python_codes/p02264/s627525396.py | s627525396.py | py | 365 | python | en | code | 0 | github-code | 90 |
70789531816 | from option import args
from utils import mkExpDir, set_random_seed
from dataset import dataloader
from importlib import import_module
from waveloss.loss import get_loss_dict
from trainer import Trainer
import torch
import torch.nn as nn
import warnings
warnings.filterwarnings('ignore')
if __name__ == '__... | zskuang58/WTRN-TIP | main.py | main.py | py | 1,672 | python | en | code | 15 | github-code | 90 |
18575434283 | import torch as th
def smallest_positive(inputs, dim):
"""
Args
inputs: 3d array [B,T,L].
dim: dimension on which the largest tj lower than t is evaluated.
Return
(delta_t, idx_delta_t), is_candidate:
delta_t: t - tj, where th is the largest value lower than t
... | babylonhealth/neuralTPPs | tpp/utils/utils.py | utils.py | py | 1,196 | python | en | code | 24 | github-code | 90 |
17825699005 | from src.interface import IEXData
from typing import List
import numpy as np
import pandas as pd
db = IEXData()
def create_model(symbol, save_to_excel=False):
income = db.get_income_statements(symbol, n_quarters=12)
balance_sheets = db.get_balance_sheets(symbol, n_quarters=12)
cash_flow = db.get_cashflow_sta... | carterjfulcher/automodel | src/model/main.py | main.py | py | 1,658 | python | en | code | 0 | github-code | 90 |
18284290289 | import math
def lcm(x, y):
return (x * y) // math.gcd(x, y)
MOD = 1000000007
N = int(input())
A = list(map(int, input().split()))
lcm_ = 1
for a in A:
lcm_ = lcm(lcm_, a)
ans = 0
for a in A:
ans += lcm_ // a
ans %= MOD
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02793/s647004972.py | s647004972.py | py | 250 | python | en | code | 0 | github-code | 90 |
23985799089 | class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
N = len(source)
parent = list(range(N))
size = [1]*N
def find(v):
path = []
while parent[v] != v:
path.append(v)
... | birsnot/A2SV_Programming | minimize-hamming-distance-after-swap-operations.py | minimize-hamming-distance-after-swap-operations.py | py | 1,077 | python | en | code | 0 | github-code | 90 |
41663093582 |
import warnings
from KFT.job_utils import run_job_func
import numpy as np
import matplotlib.pyplot as plt
import os
PATH = ['public_data_t_fixed/' ,'public_movielens_data_t_fixed/' ,'tensor_data_t_fixed/' ,'electric_data/' ,'CCDS_data/','traffic_data/']
shape_permutation = [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2],... | MrHuff/KernelFriedTensor | KFT_fundamental_motivation_experiment.py | KFT_fundamental_motivation_experiment.py | py | 5,312 | python | en | code | 1 | github-code | 90 |
42747128615 | from cs110 import autograder
import pythonGraph
# ---------------------------------------------------------------------
# Lab: pythonGraph Soundboard
# Author: NAME GOES HERE
# Course: CS110Z, Spring 2020
# ---------------------------------------------------------------------
# Setup Tasks for the Window
pythonGraph.... | JakeH-32/Capstone-2.0 | Labs/lsn23_soundboard.py | lsn23_soundboard.py | py | 1,330 | python | en | code | 0 | github-code | 90 |
18500211209 | import math
N, K = map(int,input().split())
ans = 0
ans += (N//K)**3
if K%2 == 0:
cnt = 0
for i in range(1,N+1):
if i%K == int(K/2):
cnt += 1
ans += cnt**3
#ans += (math.ceil(N/K))**3
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03268/s221572391.py | s221572391.py | py | 231 | python | en | code | 0 | github-code | 90 |
21560903810 | # import pygame library so we can use it!
import pygame
# initialize pygame
pygame.init()
# setup Game Surface (screen)
WINDOW_WIDTH = 1000
WINDOW_HEIGHT = 1000
gameSurface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# setup game resources
# color definitions
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GR... | MaxT2/EWPythonDevelopment | First Session Code/pygameHouse.py | pygameHouse.py | py | 1,259 | python | en | code | 0 | github-code | 90 |
34561765424 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import workspace
import os
import tempfile
import unittest
class TestDB(unittest.TestCase):
def setUp(self):
handle, self.file_name = te... | facebookarchive/AICamera-Style-Transfer | app/src/main/cpp/caffe2/python/db_test.py | db_test.py | py | 1,255 | python | en | code | 81 | github-code | 90 |
2939163689 | import asyncio
import os
from temporalio.client import Client
from sentry.worker import GreetingWorkflow
async def main():
# Connect client
client = await Client.connect("localhost:7233")
# Run workflow
result = await client.execute_workflow(
GreetingWorkflow.run,
"World",
i... | temporalio/samples-python | sentry/starter.py | starter.py | py | 483 | python | en | code | 68 | github-code | 90 |
18130882194 | class Node:
def __init__(self, val, left, right):
self.val = val
self.left: Node = left
self.right: Node = right
def print(self):
print(self.val)
if self.left is not None:
self.left.print()
if self.right is not None:
self.right.print()
de... | sstrac/leetcode | binaryTree.py | binaryTree.py | py | 1,148 | python | en | code | 0 | github-code | 90 |
18374660839 | S = str(input())
cnt = 0
cha = []
for s in S:
if s not in cha:
cha.append(s)
elif s == cha[0]:
cnt += 1
if len(cha)==2 and cnt==1:
print('Yes')
else:
print('No') | Aasthaengg/IBMdataset | Python_codes/p02987/s634229696.py | s634229696.py | py | 180 | python | en | code | 0 | github-code | 90 |
2333375692 | import general_methods
import downloads_vacancies
def get_data_from_headhunter(language):
url = 'https://api.hh.ru/vacancies'
headers = {'User-Agent': 'HH-User-Agent'}
params = {'text': language,
'area': 1,
'period': 30,
'only_with_salary': True,
'p... | DPProger/API_Lesson5 | api_lesson5/headhunter.py | headhunter.py | py | 1,670 | python | en | code | 0 | github-code | 90 |
34963691776 | from django.utils.timezone import now
from django.utils import deprecation
from kw_webapp.models import Profile
from kw_webapp.tasks import past_time
class SetLastVisitMiddleware(deprecation.MiddlewareMixin):
"""
A middleware class which will update a last_visit field in the profile once an hour.
"""
... | Kaniwani/kw-backend | kw_webapp/middleware.py | middleware.py | py | 866 | python | en | code | 71 | github-code | 90 |
41540109631 | #!/usr/bin/python3
import sys
import os
# Advent of Code 2022
# Day 06
def markerStart(s, n):
for k in range(len(s)):
if len(set(s[k:k + n])) == n:
return k + n
def main(filename):
file = open(filename)
lines = file.readlines()
file.close()
line = lines[0]
# Part One:
... | TomCarton/AdventOfCode | 2022/day06/day06.py | day06.py | py | 887 | python | en | code | 2 | github-code | 90 |
41284742463 | # Reads entry data from file
input_data = []
with open('puzzle3_input.txt') as file:
for line in file:
input_data.append(line)
gamma_rate = ''
epsilon_rate = ''
l = len(input_data[0].strip())
for i in range(l):
counter_1 = 0
counter_0 = 0
for j in range(len(input_data)):
if input_data[... | arinabagele/advent-of-code-2021 | Day3/puzzle3a.py | puzzle3a.py | py | 714 | python | en | code | 0 | github-code | 90 |
11731859014 | def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def cube(*a):
for i in a:
i=int(i)
print(i*i*i)
def circle(r):
while True:
a=int(input("choose any option\n 1. diameter\n2.circumference\n3.area\n4. press 0 for exit"))
if a==1:
dia=2*r
... | RaunakMaini/Raunak | func1.py | func1.py | py | 1,147 | python | en | code | 0 | github-code | 90 |
74882046056 | from datetime import datetime
from scipy.interpolate import lagrange
from graphics.ValueBuilder import ValueBuilder
import numpy as np
class GraphicBuilder:
def __init__(self):
self.WINDOW_WIDTH = 30 / 2.54
self.WINDOW_HEIGHT = 13 / 2.54
self.MIN_X = -2
self.MAX_X = 2
sel... | d4tAloUh/ML_CS3 | Lab01_Karmeliuk/graphics/GraphicBuilder.py | GraphicBuilder.py | py | 2,545 | python | en | code | 0 | github-code | 90 |
26325975190 | from collections import defaultdict
import requests
import random
import json
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
from flask import Flask, render_template, request, redirect
def meters_to_miles(meters):
return meters / 1609
app = Flask(__name__)
@app.route("/")
... | jerillo/yelp-randomizer | app.py | app.py | py | 2,677 | python | en | code | 0 | github-code | 90 |
18411968449 | h,w=map(int,input().split())
a=[input() for _ in range(h)]
visited=[[0]*w for _ in range(h)]
from collections import deque
q=deque([])
for i in range(h):
for j in range(w):
if a[i][j]=="#":
q.append((i,j,0))
visited[i][j]=1
ans=0
while q:
i,j,count=q.popleft()
ans=max(ans,count)
for nxi,nxj in [... | Aasthaengg/IBMdataset | Python_codes/p03053/s889714969.py | s889714969.py | py | 480 | python | en | code | 0 | github-code | 90 |
41445712063 | import discord
import traceback
from discord import app_commands
import random
from creds import token
import sqlite3
"""
---------- Vibe Bot -----------
This is my Vibe Bot, which is found in over 500 servers and has issued thousands of vibe checks
Support Discord Server: https://discord.com/invite/7VemvMg
The major... | MurryPuppins/Discord.py-Bots | vibeBotOfficial/vibeBotOfficial.py | vibeBotOfficial.py | py | 5,403 | python | en | code | 0 | github-code | 90 |
31220898250 | import pandas as pd
import numpy as np
import Recommenders as Recommenders
import streamlit as st
import pickle
song_df_1 = pd.read_csv('triplets_file.csv')
song_df_2 = pd.read_csv('song_data.csv')
song_df = pd.merge(song_df_1, song_df_2.drop_duplicates(
['song_id']), on='song_id', how='left')
... | Abhishek-Sumn/streamlit | ap2.py | ap2.py | py | 1,259 | python | en | code | 0 | github-code | 90 |
4423521825 | def strStr(haystack,needle):
'''
A function that returns the first index of the occurence of the string needle in
the string haystack, and returns -1, otherwise.
Time complexity: O(len(haystack)), as at worst we iterate through each character
of haystack.
Space complexity: O(1), since not external storage ... | jd1618/Python-Codes | Leetcode/Strings/Easy/strStr.py | strStr.py | py | 493 | python | en | code | 1 | github-code | 90 |
42143678293 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 20:10:29 2019
@author: bmlhs
"""
import tkinter as tk
from tkinter import *
r = tk.Tk()
r.iconbitmap('gui_icon_HEj_icon.ico') # This gives the icon to the GUI
r.title('Flowers') # This is the title to the GUI
r.geometry("500x700")
v = tk.IntVar() ... | HannahCurrivan/GUIPythontkinter | gui_github.py | gui_github.py | py | 892 | python | en | code | 0 | github-code | 90 |
26870928915 | """
Test for the Fickett's model 01.
Nonlinear simulation.
Regression test that compares computed result to the previous result
recorded on 2018-03-12.
"""
from numpy.testing import assert_allclose, tempdir
from saf.action import solve
from saf.ffm.nonlinear.config import Config
from saf.ffm.nonlinear.asciireader im... | dmitry-kabanov/fickettmodel | tests/test_fm_01.py | test_fm_01.py | py | 1,356 | python | en | code | 0 | github-code | 90 |
6112204296 | import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os.path
import numpy.linalg as linalg
import os
import createModel as createModel
num_of_nn = 4
num_of_epoch = 100
cwd = os.getcwd()
... | zhengezhao/picture_wise_vis | data_generator.py | data_generator.py | py | 3,026 | python | en | code | 0 | github-code | 90 |
17818277381 | import numpy as np
import matplotlib.pyplot as plt
def gradient_function(x):
'''
gradient of func_
'''
return 2*(x-2.5)
def func_(x):
'''
y = (x-2.5)^2 + 3
'''
return (x-2.5)**2 +3
def gradient_descent(start_x, lr,
max_iterations=None,
... | marine0131/gradient_descent | find_minimum_2d.py | find_minimum_2d.py | py | 1,571 | python | en | code | 0 | github-code | 90 |
29076255558 | import firebase_admin
from firebase_admin import credentials
from datetime import datetime
from firebase_admin import firestore
cred = credentials.Certificate("key.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
activity = db.collection('activity')
status = db.collection('status')
store = 2
def ... | amaljoe/people-counter-opencv | database.py | database.py | py | 777 | python | en | code | 0 | github-code | 90 |
73820254697 | class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
size = len(arr)
min_diff = float('inf')
result = []
for idx, num in enumerate(arr):
if idx >= 1:
diff = num - arr[idx - 1]
if diff == min_... | HarrrrryLi/LeetCode | 1200. Minimum Absolute Difference/Python 3/solution.py | solution.py | py | 526 | python | en | code | 0 | github-code | 90 |
17921253115 | import ast
import itertools
import time
import networkx
import pulp
from pulp import lpSum as csum
from common import all_vectors
from graph import Graph
solver = pulp.PULP_CBC_CMD(msg=False)
def check_positive(G, winners):
for v in winners:
if not solve_one(G, v):
return False
return Tr... | blimmo/tfp | ilp.py | ilp.py | py | 5,339 | python | en | code | 0 | github-code | 90 |
14745525270 | # This function checks the number if it is prime or not...
# Author : Enes Kemal Ergin
# Date : 02/14/15
# Return true if the number p is prime...
import random
def IsPrime(p, max_tests):
# Perform the test up to max_tests times
for i in range(max_tests):
n = random.randint(1, p - 1)
if (pow(n... | eneskemalergin/Essential_Algorithms | IsPrime.py | IsPrime.py | py | 596 | python | en | code | 24 | github-code | 90 |
18905629021 | from random import randint
class Partition:
def __init__(self, randomized=False):
self.randomized = randomized
"""
CLRS and Wiki Hoare Partition Implementations happen to be same
Differences:
CLRS used pivot = a[l] & Wiki used pivot = a[l + (r - l) // 2] -> cho... | kaushalpranav/python-ds-training | standard_ds_stash/1002_Quick Sort.py | 1002_Quick Sort.py | py | 3,309 | python | en | code | 0 | github-code | 90 |
200937293 | # script to test the 4 channels of the ads1115
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)
# Create the ADC object using the I2C bus
ads = ADS.ADS1115(i2c)
# Create single-ended... | bensisney/BBQ_Monitor | functionalTests/test_ADS1115_AD8495_corr.py | test_ADS1115_AD8495_corr.py | py | 1,739 | python | en | code | 1 | github-code | 90 |
26911246720 | import pygame
class Square:
block_width = 50
block_height = 50
strikes = 0
def __init__(self, x, y, val=0):
self.selected = False
self.xy = (x, y)
self.value = val
self.rect = None
def set_rect(self, pixel_x, pixel_y):
self.rect = pygame.Rect(pixel_x, pixel... | foldupcircle/sudoku-solver | square.py | square.py | py | 399 | python | en | code | 0 | github-code | 90 |
1218402967 | from data_reader import DataReader
from copy import deepcopy
OBJECTIVE_MAP = {
"toppling_an_existing_leadership": 'nagobj_1',
"change_of_regime_type": 'nagobj_2',
"demands_for_autonomy": 'nagobj_3',
"territorial_demand": 'nagobj_4',
"demands_for_policy_change... | newtein/ArmedGroups | get_objective.py | get_objective.py | py | 723 | python | en | code | 0 | github-code | 90 |
2358422205 | import torch
import torch.nn as nn
import pretrainedmodels
import ssl
from utils.constants import *
def l2_norm(input, axis=1):
norm = torch.norm(input, 2, axis, True)
output = torch.div(input, norm)
return output
class BinaryHead(nn.Module):
def __init__(self, num_class=8, emb_size=2048, s=16.0):
... | TheNerdyCat/breast-cancer-detection | models/models.py | models.py | py | 1,720 | python | en | code | 0 | github-code | 90 |
2797556786 | """
lab 14: pick 6 - lottery simulator
"""
import random
import time
def pick6():
# ticket = []
# for i in range(6):
# ticket.append(random.randint(1, 99))
# return ticket
return [random.randint(1, 99) for i in range(6)]
def calculate_payout(winning, ticket):
"""
calculates payout ... | PdxCodeGuild/class_salmon | 1 Python/solutions/lab14-pick6.py | lab14-pick6.py | py | 1,966 | python | en | code | 5 | github-code | 90 |
3017975392 | import os
from setuptools import setup, find_packages
version = "0.6.0"
package_name = "gaama"
cwd = os.path.dirname(os.path.abspath(__file__))
def write_version_file():
version_path = os.path.join(cwd, package_name, "version.py")
with open(version_path, "w") as f:
f.write("__version__ = '{}'\n".fo... | prabhuomkar/bitbeast | gaama/setup.py | setup.py | py | 1,138 | python | en | code | 19 | github-code | 90 |
15425963386 | #versione aggressiva tutta multithreading
from bs4 import BeautifulSoup as BS4
from collections import Counter
import requests as req
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
def cleaner(data):
for items in data:
if items[0:len(our_url)] == our_url:
temp_data.a... | carloocchiena/keywords_crawler | web/backup/refactoring version hard backup/processing.py | processing.py | py | 2,565 | python | en | code | 0 | github-code | 90 |
30853638006 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('podcast', '0008_podcast_explicit'),
]
operations = [
migrations.AlterF... | Fablr/Web-App | fablersite/podcast/migrations/0009_auto_20151110_1900.py | 0009_auto_20151110_1900.py | py | 707 | python | en | code | 2 | github-code | 90 |
1970381790 | import os
import socket
import threading
from concurrent.futures import ThreadPoolExecutor
import shortuuid
def handle(conn):
remote_addr = conn.getpeername()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.send(b'Reply: ' + d... | ziwon/consulator | example/echo.py | echo.py | py | 1,622 | python | en | code | 0 | github-code | 90 |
31666050291 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/7/28 10:15
# @Author : YXH
# @Email : 874591940@qq.com
# @desc : 手机号码合成神器软件调用
import time
# 窗口操作
import win32con
import win32gui
# 模拟鼠标键盘
from pymouse import PyMouse
from pykeyboard import PyKeyboard
# 剪贴板
import pyperclip
# excel
import xlrd
import openpyxl... | xuhao1108/PhoneNumber | phone_number.py | phone_number.py | py | 6,812 | python | en | code | 0 | github-code | 90 |
4962471322 | r"""
{xrst_begin dir_cmd user}
{xrst_spell
dir
}
Converting Sphinx Command File Names
####################################
Syntax
******
``\{xrst_dir`` *file_name* ``}``
Purpose
*******
Sphinx commands that use file names must specify the file
relative to the :ref:`config_file@directory@rst_directory` .
The xrst ... | bradbell/xrst | xrst/dir_command.py | dir_command.py | py | 2,475 | python | en | code | 0 | github-code | 90 |
18166317649 | def main():
H, W, M = map(int, input().split())
hw = [tuple(list(map(int, input().split()))) for _ in [0]*M]
hw_set = set(hw)
h_count = [0 for i in range(H+1)]
w_count = [0 for i in range(W+1)]
for h, w in hw:
h_count[h] += 1
w_count[w] += 1
h_m = max(h_count)
w_m = max(w... | Aasthaengg/IBMdataset | Python_codes/p02580/s503432112.py | s503432112.py | py | 722 | python | en | code | 0 | github-code | 90 |
22692368996 | import unittest
from unittest import TestCase
from python_combat.src.chengyaojin import ChengYaoJin
from python_combat.src.hero_factory import HeroFactory
from python_combat.src.libai import LiBai
class TestHero(TestCase):
def test_fight(self):
#第一轮对打
chengyaojin = ChengYaoJin()
libai = L... | wangjinjin123/python_test_forme | python_combat/testcases/test_hero.py | test_hero.py | py | 1,066 | python | en | code | 0 | github-code | 90 |
6626239084 | # -*- coding: utf-8 -*-
"""Top-level package for SigPro."""
__author__ = """MIT Data To AI Lab"""
__email__ = 'dailabmit@gmail.com'
__version__ = '0.1.2.dev0'
import os
from mlblocks import discovery
from sigpro.core import SigPro
_BASE_PATH = os.path.abspath(os.path.dirname(__file__))
MLBLOCKS_PRIMITIVES = os.pa... | sintel-dev/SigPro | sigpro/__init__.py | __init__.py | py | 1,405 | python | en | code | 7 | github-code | 90 |
11037384477 | #August 12, 2015
#http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/
from __future__ import print_function
print("Program determines whether given whole number can be cut evenly into specified number of pieces")
while True:
inp=raw_input("Input a positive integer or Q/q to Quit---> ")
if ... | bang103/MY-PYTHON-PROGRAMS | WWW.CSE.MSU.EDU/CONTROL/SplitNumber.py | SplitNumber.py | py | 2,843 | python | en | code | 0 | github-code | 90 |
1844411776 | from flask import Flask, render_template
from flask import request, redirect
app = Flask(__name__)
products = {
"sku01": {
"id": "sku01",
"name": "Dig it. SUCKA!!!",
"price": 666,
"desc": "Can you dig it, SUCKA???",
"src": "https://i.ytimg.com/vi/AL4v0LUXR4k/maxresdefault.jpg" },
... | JamesWang0819/Mysite | 20200425python/shop.py | shop.py | py | 1,887 | python | en | code | 0 | github-code | 90 |
8711010688 | '''
Created on Dec 2, 2011
@author: guillaume.aubert@eumetsat.int
'''
import datetime
import eumetsat.dmon.common.log_utils as log_utils
import eumetsat.dmon.common.time_utils as time_utils
LOG = log_utils.LoggerFactory.get_logger('analyze_utils')
def print_rec_in_logfile(rec):
"""
Print rec in file
... | gaubert/rodd | src/eumetsat/dmon/common/analyze_utils.py | analyze_utils.py | py | 5,363 | python | en | code | 3 | github-code | 90 |
7262520855 | #!/usr/bin/env python
import rospy
from jsk_rviz_plugins.srv import EusCommand, EusCommandRequest, EusCommandResponse
from std_srvs.srv import Empty, EmptyRequest, EmptyResponse
from move_haro_in_circles import HaroMove
class RobotCommandServer(object):
def __init__(self):
# To make the robot command RVI... | wangcongrobot/fetch_simulation_ws | move_objects/haro/haro_description/scripts/robot_command_server.py | robot_command_server.py | py | 1,801 | python | en | code | 2 | github-code | 90 |
40581923400 |
def menu_user():
print('''Меню RLE алгоритма:
======
aaaasssffffff -> 4a3s6f -> aaaasssffffff
======
Что вы хотите?
1 - закодировать строку: aaaasssffffff -> 4a3s6f
2 - декодировать строку: 4a3s6f -> aaaasssffffff
''')
user_select = input('Выберите пункт меню: ')
if u... | Suxarik777/GB_Python_base | Py_HomeWork/Seminar_HomeWork_005/RLE_Algorithm(AAAAAAFDDCCC->6A1F2D3C)/menu.py | menu.py | py | 619 | python | ru | code | 0 | github-code | 90 |
871454835 | import os
import subprocess
folder_name = "FeatheredMaps"
folder_path = None
# iterate through all the drives on the computer
for drive in ['C:\\', 'D:\\', 'E:\\']:
# search for the folder in the drive
for root, dirs, files in os.walk(drive):
if folder_name in dirs:
folder_path = os.path.j... | MichaelPWalter/FeatheredMaps | test2.py | test2.py | py | 1,285 | python | en | code | 0 | github-code | 90 |
37186914830 | import boto3
import botocore
import datetime
import time
from datetime import date, timedelta
# Database to execute the query against
DATABASE = 'PROJECT_NAME'
# Output location for query results
output_bucket = 'PROJECT_NAME-compacted-logs'
# Generate every date in range
def daterange(start_date, end_date):
for... | nickloadd/python_scripts | compacted_logs.py | compacted_logs.py | py | 4,372 | python | en | code | 0 | github-code | 90 |
23415228417 | # palindrome
# NDXMYR001
# Myrin Naidoo
def palindrome(pal):
if(len(pal) == 0):
return pal
else:
return palindrome(pal[1:]) + pal[0]
strin = input("Enter a string:\n")
if(palindrome(strin)==strin):
print("Palindrome!")
else:
print("Not a palindrome!") | MyrinNaidoo12/ComSci | CSC1015F/Assignment8/palindrome.py | palindrome.py | py | 299 | python | en | code | 0 | github-code | 90 |
26243152783 | from __future__ import print_function
# from PyQt4.QtCore import *
from qgis.PyQt.QtCore import QThread, pyqtSignal
from emission.exceptions import RouteError
class RoadEmissionPlannerThread(QThread):
plannerFinished = pyqtSignal()
def __init__(self):
QThread.__init__(self)
self.emission_plan... | NPRA/RoadEmissionCalculator | RoadEmissionPlannerThread.py | RoadEmissionPlannerThread.py | py | 1,175 | python | en | code | 4 | github-code | 90 |
15072965519 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insertCompleteBST(root,index,lst):
if root is None:
root=Node(lst[index])
if (2*index)+1<=len(lst)-1:
root.left = insertCompleteBST(root.left,(2*index)+1,lst... | Manutsawin/ExDataStructure | 8/63010779_Lab08_3.py | 63010779_Lab08_3.py | py | 2,466 | python | en | code | 0 | github-code | 90 |
18314025549 | N = int(input())
from collections import deque
inp = []
for k in range(N-1):
a, b = map(int, input().split())
if a > b:
a, b = b-1, a-1
else:
a, b = a-1, b-1
inp.append((a, b, k))
inp.sort(key = lambda x: x[0])
inp = deque(inp)
mark = [[] for _ in range(N)]
def binary_search(list, item):
low = 0
... | Aasthaengg/IBMdataset | Python_codes/p02850/s471228173.py | s471228173.py | py | 999 | python | en | code | 0 | github-code | 90 |
75166908456 | import cv2
import numpy as np
win_name = "scanning"
img = cv2.imread('../../data/image/train/529/30.jpg')
img2 = cv2.imread('../../data/image/train/529/30.jpg')
rows, cols = img.shape[:2]
draw = img.copy()
pts_cnt = 0
pts = np.zeros((4, 2), dtype=np.float32)
def onMouse(event, x, y, flags, param):
global pts_cnt
... | lynhyul/AIA | lotte/perspective.py | perspective.py | py | 2,273 | python | ko | code | 3 | github-code | 90 |
23325987668 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 18:03:03 2020
@author: js
"""
import os
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
IMAGE_NET_DATA_PATH = '/ssd/datasets/public/imagenet/'
def get_data_loader(config):
batch_size = conf... | mobilint/quantization-suite | srcs/datagen.py | datagen.py | py | 1,643 | python | en | code | 2 | github-code | 90 |
4513817058 | # Arquitectura cliente servidor
# Mauricio Bueno Osorio
# Entrega II
import zmq # Provee la comunocación a través de sockets
import sys
import json
import hashlib
SIZE = 1048576
def strToSha(string):
hash_object = hashlib.sha1(string.encode())
name = hash_object.hexdigest()
nameAsN... | MaoBueno/cliente-servidor | cliente/cliente.py | cliente.py | py | 4,588 | python | en | code | 0 | github-code | 90 |
10398170615 | import cv2
import numpy as np
# add some external resources
cv2.ovis.addResourceLocation("packs/Sinbad.zip")
# camera intrinsics
imsize = (800, 600)
K = np.diag([800, 800, 1])
K[:2, 2] = (400, 100) # offset pp
# observer scene
owin = cv2.ovis.createWindow("VR", imsize)
cv2.ovis.createGridMesh("ground", (10, 10), (10... | iamrajee/roskinetic_catkin_ws | src/opencv3/opencv_contrib/ovis/samples/ovis_demo.py | ovis_demo.py | py | 909 | python | en | code | 20 | github-code | 90 |
18530500609 | from collections import Counter
n = int(input())
s = input()
e = int(s.count('E'))
ans = e
a = 0
for i in range(n):
if s[i] == 'W':
a += 1
b = e - ((i+1)-a)
ans = min(ans, a+b)
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03339/s760625043.py | s760625043.py | py | 210 | python | en | code | 0 | github-code | 90 |
24254812385 | from Animals.BaseAnimal import BaseAnimal
class Valier:
def __init__(self, biome, area=10):
self.animals = []
self.biome = biome
self.area = area
self.employedArea = 0
self.__food = {}
def addAnimal(self, animal: BaseAnimal):
if animal in self.anima... | Patatars/MyZoo | Valier.py | Valier.py | py | 2,078 | python | en | code | 0 | github-code | 90 |
43130867944 | # Time Complexity : O(n*m*(3^l)) - where l is the length of the word, 3 because we have 3 directions everytime, 4th directions is ignored becuase that is the path we come from
# Space Complexity : O(l) - recursive stack for DFS grows till length of the word
class Solution(object):
def exist(self, board, word):
... | Thirunaa/Blind75 | Word_Search/wordSearch.py | wordSearch.py | py | 1,517 | python | en | code | 0 | github-code | 90 |
70067415977 | import boto3
import paramiko
import os
import subprocess
import time
from botocore.config import Config
from configure import *
from stack import *
from keypair import *
from ami import *
from monitoring import *
if __name__ == '__main__':
ACCESS_KEY = os.environ['ACCESS_KEY']
SECRET_KEY = os.environ['SECRE... | Ilyassxx99/python-bdata-project | python/main.py | main.py | py | 5,045 | python | en | code | 0 | github-code | 90 |
40846675970 | import requests
def urlchecker(userArr):
badarray = []
for arr in userArr:
if ((arr.startswith("http://")) or (arr.startswith("https://"))):
newarr = arr
else:
newarr = "http://" + arr
r = requests.get(newarr)
if r.status_code != 200:
obj = {... | Kaizan08/cc1 | urlutils.py | urlutils.py | py | 421 | python | en | code | 0 | github-code | 90 |
6498711652 | from flask import Flask, session, render_template, url_for, redirect, flash, request
from datetime import timedelta
app = Flask(__name__)
app.secret_key='hello'
app.permanent_session_lifetime = timedelta(seconds=80)
@app.route('/')
def home():
return render_template('index6.html')
@app.route('/login/', methods=[... | alvinkg/flask_tutorial | tutorial_6a.py | tutorial_6a.py | py | 1,469 | python | en | code | 0 | github-code | 90 |
36600505518 | import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
# matplotlib.rcParams['font.family'] = 'AppleGothic'
matplotlib.rcParams['font.size'] = 15
matplotlib.rcParams['axes.unicode_minus']=False
import pandas as pd
df = pd.read_excel('score.xlsx')
x=df['지원번호']
y=df['키']
... | onulee/https---github.com-onulee-kdigital1 | 07.plt/p0509/p0509_01.py | p0509_01.py | py | 634 | python | en | code | 0 | github-code | 90 |
21041965158 | import math
def quadratic(a, b, c):
if b**2-4*a*c>=0:
x1=(-b+math.sqrt(b**2-4*a*c))/(2*a)
x2=(-b-math.sqrt(b**2-4*a*c))/(2*a)
return x1,x2
else:
print('方程式','ax^2+bx+c=0','无实根')
print('二元一次方程为:ax^2+bx+c=0')
a=int(input('请输入a的值:'))
b=int(input('请输入b的值:'))
c=int(input('请输... | tamlovincy/python | lianxi/解二元一次方程.py | 解二元一次方程.py | py | 451 | python | zh | code | 1 | github-code | 90 |
19028024177 | import tensorflow as tf
from keras import layers, Model, Input
from keras.utils import Progbar, to_categorical
from keras.datasets.mnist import load_data
import numpy as np
import matplotlib.pyplot as plt
import config
import datetime
img_height, img_width, _ = config.IMAGE_SHAPE
(X, Y), (_, _) = load_data()
X = X.re... | parth-shastri/Conditional_GAN | main.py | main.py | py | 7,432 | python | en | 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.