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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32310929702 | import networkx as nx
import matplotlib.pyplot as plt
import random
import itertools
def get_signs_of_tris(triangle_list,G):
#triangle_list=[[1,2,3][4,5,6][7,8,9]]
#all_signs=[[1,2->'+',2,3->'-',1,3->'-'][][]]
all_signs=[]
for i in range(len(triangle_list)):
temp=[]
temp.append(G[ triangle_list[i][0]] [triangl... | harsimarsingh/iitroparProjects | BalancedTrianglesInGraph.py | BalancedTrianglesInGraph.py | py | 5,608 | python | en | code | 0 | github-code | 1 |
43200698161 | import pandas as pd
from .common_utils import json_to_dataframe
from datetime import datetime
import os
import requests
import cv2
import numpy as np
import pydicom
from pydicom.filereader import dcmread
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.pixel_data_handlers.numpy_handler import pack_bit... | mdai/mdai-client-py | mdai/utils/dicom_utils.py | dicom_utils.py | py | 53,457 | python | en | code | 24 | github-code | 1 |
31056606907 | import logging
import numpy as np
from scipy.signal import hilbert
from copy import deepcopy
Logger = logging.getLogger(__name__)
def linstack(streams, normalize=True):
"""
Compute the linear stack of a series of seismic streams of \
multiplexed data.
:type streams: list
:param streams: List o... | eqcorrscan/EQcorrscan | eqcorrscan/utils/stacking.py | stacking.py | py | 5,526 | python | en | code | 155 | github-code | 1 |
42245890561 | from config import PMUS_SHEET
from shared import clean_value, get_data, dump_data
def model_pmu(row):
# Transform a row into PMU object
# according to the schema in /schemas/pmu.json
# Make sure update /schemas/pmu.json while changing here
return {
"state": clean_value(row[0]),
"name"... | coronasafe/10bedicu | scraper/src/pmu.py | pmu.py | py | 680 | python | en | code | 4 | github-code | 1 |
37297444746 | import os
import lintreview.docker as docker
from lintreview.tools import Tool, process_quickfix, extract_version
class Puppet(Tool):
name = 'puppet-lint'
def version(self):
output = docker.run('ruby2', ['puppet-lint', '--version'], self.base_path)
return extract_version(output)
def ch... | markstory/lint-review | lintreview/tools/puppet.py | puppet.py | py | 2,012 | python | en | code | 292 | github-code | 1 |
74767959713 | #Importando Librerias
import re
import tkinter as tk
from tkinter import messagebox
from ply import lex, yacc
from subprocess import call
#Definir los tokens
tokens = (
'WHILE',
'SYSTEM',
'OUT',
'INT',
'ID',
'NUM',
'STRING',
'PLUS',
'SEMICOLON',
'LPAREN',
... | Marc-Zun/Compiladores | SUB4/Act. 4.1 Proyecto Final Analizadores/Proyecto Final Compiladores/sintactico.py | sintactico.py | py | 5,654 | python | es | code | 0 | github-code | 1 |
4906137841 | # coding: utf-8
import sys
import torch
import time
import pickle
import pandas as pd
from gensim import corpora, models, similarities
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score
def test_on(model, data_dl, output_path=None, checkpoint_path=None):
print("loading model from {... | JinYang88/sentence-matching | utils/evaluator.py | evaluator.py | py | 1,060 | python | en | code | 1 | github-code | 1 |
20791526735 | from PyQt5.QtCore import Qt, QTimer, QTime
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import (QWidget, QApplication,
QLabel, QPushButton,
QLineEdit, QHBoxLayout, QHBoxLayout)
from instr import *
from final_win import *
class Experiment():
... | dannilkiba606/test | second_win.py | second_win.py | py | 6,240 | python | en | code | 0 | github-code | 1 |
70809880354 | import json
import sys, os
import requests
import urllib, urllib3
import time
import threading
import cv2
import kivy
import cognitive_face as CF
import numpy as np
from kivy.app import App
from kivy.cache import Cache
from kivy.clock import Clock, mainthread
from kivy.graphics import *
from kivy.uix.... | lukazd/DistributedAdvertisingBoard | rpi_software/IOT_Project/main.py | main.py | py | 11,984 | python | en | code | 3 | github-code | 1 |
28897833664 | import random
uzivatel_vyhry = 0
pc_vyhry = 0
moznosti = ["kámen", "nůžky", "papír"]
while True:
uzivatel_vstup = input("Napište Kámen / Nůžky / Papír nebo Q k ukončení program: ").lower().strip()
if uzivatel_vstup == "q":
break
if uzivatel_vstup not in moznosti:
continue
... | tomandavid1/MiniProjects | kamen_nuzky_papir.py | kamen_nuzky_papir.py | py | 1,013 | python | cs | code | 0 | github-code | 1 |
18323454254 | import copy
import logging
import numpy as np
import torch
from d2go.data.dataset_mappers import (
D2GoDatasetMapper,
D2GO_DATA_MAPPER_REGISTRY,
)
from d2go.data.dataset_mappers.d2go_dataset_mapper import (
PREFETCHED_SEM_SEG_FILE_NAME,
read_image_with_prefetch,
)
from detectron2.data import detection_... | facebookresearch/sylph-few-shot-detection | sylph/data/dataset_mapper/meta_learn_dataset_mapper.py | meta_learn_dataset_mapper.py | py | 10,913 | python | en | code | 54 | github-code | 1 |
3855367432 |
# FV ADI - HV scheme
import numpy as np
#import matplotlib.pyplot as plt
from scipy.stats import beta
import os
import pickle
import datetime
def genMesh1d01(x0, m):
X = np.zeros(m+1)
xMax = m*x0
c = x0/5
dxi = ( np.arcsinh((xMax-x0)/c)-np.arcsinh(-x0/c) )/m
for i in ... | dennis0004/modelGSL | FPK_FV_ADI_GSLm.py | FPK_FV_ADI_GSLm.py | py | 24,292 | python | en | code | 0 | github-code | 1 |
8020342676 | import random
import sys
stake = 10
goal = 40
trials = 1000
bets = 0
wins = 0
for t in range (0, trials):
# run one experiment
cash = stake
while (cash > 0) and (cash < goal):
bets += 1
if random.randrange(0,2)==0:
cash -= 1
else:
cash += 1
if cash == g... | paulhylam/Intro_Python | gambler.py | gambler.py | py | 422 | python | en | code | 0 | github-code | 1 |
18347650895 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 28 22:47:04 2018
@author: Alan
"""
import numpy as np
import math
import random
import pprint
#import pygame
import sys
import matplotlib.pyplot as plt
#===========CHANGABLE PARAMETERS=================
REWARD = 1
PENALTY = -1
DISCOUNT = 0.8
LEA... | AlannnZzz/Bounce | test.py | test.py | py | 10,648 | python | en | code | 0 | github-code | 1 |
14089824645 | from http import HTTPStatus
class CouldNotLoginGnocchi(Exception):
def __init__(self, id=None, secret=None):
self.status_code = HTTPStatus.UNAUTHORIZED
if id and secret:
self.message = f'Could not login on OpenStack"'
else:
self.message = 'Could not get authenticatio... | OrwellMonitoring/orwell-middleware | middleware/app/gnocchi/gnocchi_exceptions.py | gnocchi_exceptions.py | py | 434 | python | en | code | 0 | github-code | 1 |
27838958033 | from tkinter import *
expression= ""
#Operations
def input_num(number,equation):
global expression
expression=expression+str(number)
equation.set(expression)
def clear_input(equation):
expression=" "
expression.set("Enter The Expression")
def evaluate(equation):
global expression
try:
... | PranaliRaorane02/Python | Calculator.py | Calculator.py | py | 3,278 | python | en | code | 0 | github-code | 1 |
1541068799 | from mindstorms import MSHub, Motor, MotorPair, ColorSensor, DistanceSensor, App
from mindstorms.control import wait_for_seconds, wait_until, Timer
from mindstorms.operator import greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to, equal_to, not_equal_to
import math
# Create your objects here.
hu... | mckenzie-nicol/COMP1510_202310_A3_BYTEBEAST | follow_line_corey.py | follow_line_corey.py | py | 2,829 | python | en | code | 0 | github-code | 1 |
40305120214 | import tensorflow as tf
import random
# import matplotlib.pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
# load mnist dataset
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more informa... | boiihong/mnist_for_fpga | 2_predict_and_store.py | 2_predict_and_store.py | py | 2,228 | python | en | code | 0 | github-code | 1 |
14593750596 | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Post, Comment
from .forms import PostForm, CommentForm
from authuser.models import USER_GROUPS
from news_posts.models import POST_STATUSES
# Create your views here.
def post_... | Pragmatique/simple-news-site | simple_news_site/news_posts/views.py | views.py | py | 1,895 | python | en | code | 0 | github-code | 1 |
10678635822 | class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, hours, pay_rate,CPF_rate):
self.name = name
self.hours = hours
self.pay_rate = float(pay_rate)
self.CPF_rate = float(CPF_rate)
self.gross_pay = self.hours* self.pay_rate
se... | thepoppycat/cp2019 | p01/q7_generate_payroll.py | q7_generate_payroll.py | py | 1,307 | python | en | code | 1 | github-code | 1 |
31550149375 | import azure.cognitiveservices.speech as speechsdk
class config:
# token keys
speech_key = "8fef2f6c1ac445369bf27c1ef31ed8b8"
service_region = "eastus"
# Set the voice we want to use
voice_name = "en-US-JennyNeural"
S3_PATH_TEXT = "speechaudio"
S3_PATH_AUDIO = "speechaudio"
class inpu... | saeed97/voice-ai | Flask-Backend/app/main/service/Speech/config.py | config.py | py | 782 | python | en | code | 0 | github-code | 1 |
38458045168 | import requests
from datetime import datetime
import os
APP_ID = os.environ["NT_APP_ID"]
API_KEY = os.environ["NT_API_KEY"]
headers = {
"x-app-id": APP_ID,
"x-app-key": API_KEY,
"x-remote-user-id": "0"
}
exersise_param = {
"query": input("Enter your Query: ")
}
exersise_endpoint = "https://trackapi.... | Scienceloop/Workout_Tracking_Google_sheet | main.py | main.py | py | 1,118 | python | en | code | 0 | github-code | 1 |
17362831035 | import os
import pytest
from hamcrest import *
from .postgres import Postgres
from .seeds import *
release = 'sql/release/201901XX_solr_view/registry/namex/'
migration = 'create.sql'
def sut():
content = open(release + migration).read()
target = content[content.find('@') + 1:]
return open(release + targe... | bcgov/namex | nro-legacy/tests/test_solr_corp_vw.py | test_solr_corp_vw.py | py | 3,931 | python | en | code | 6 | github-code | 1 |
14897569954 | from creating_bot import bot, dp
from aiogram import types, Dispatcher
from aiogram.filters.command import Command
from aiogram import md, F
from aiogram.filters import Text
from datetime import datetime
@dp.message(Command('food'))
async def button_creation(message: types.Message):
# тут мы типа создали заготовки... | Markizoid/tg-bot-training | handlers/other.py | other.py | py | 2,585 | python | ru | code | 0 | github-code | 1 |
42127689269 | #!/usr/bin/env python3
from pathlib import Path, PurePath
from nltk.corpus import wordnet as wn
import os
import common as cm
used_language = 'all'
# Analyze word classes, takes a list of words, returns a list of word classes:
def printWordClasses(wordlist):
for word in wordlist:
line = word + ', '
... | JKAbrams/SeedphrasePictogram | dictionary_table_maker.py | dictionary_table_maker.py | py | 3,784 | python | en | code | 0 | github-code | 1 |
18486957831 | import math
import sys
from queue import Queue
sys.setrecursionlimit(10000)
def calc_node_dist(start_node, end_node):
fromX = start_node.locationX
fromY = start_node.locationY
toX = end_node.locationX
toY = end_node.locationY
total_length = math.sqrt(math.pow((toX - fromX), 2) + math.pow((toY - fr... | KaleidoscopeIM/A-Star-Heuristics | utils.py | utils.py | py | 3,747 | python | en | code | 1 | github-code | 1 |
25209477746 | # import smbus
import math
import time
import keyboard
import os
import json
import matplotlib
import random
matplotlib.use("AGG")
import matplotlib.pyplot as plt
# from scipy.fftpack import fft
# from pymongo import MongoClient
# client = MongoClient('localhost', 27017)
# db = client.test_database
from pynput imp... | MPiorunn/Master-Thesis | Master/Raspberry/words.py | words.py | py | 4,154 | python | en | code | 0 | github-code | 1 |
758246612 | import pandas as pd
import numpy as np
import math
df=pd.read_csv('M.csv', header=None)
#print(df)
q_0=pd.Series([1,0,0,0,0,0,0,0,0,0])
#print(q_0)
t=2048
t_0=100
def matrixPower(t, df, q_0):
M_t=np.linalg.matrix_power(df.values, t)
q=np.matmul(M_t, q_0.values)
return q.tolist()
def statePropagation(t,... | ishaan09kapoor/data_mining_2022 | Assignment8/assignment8.py | assignment8.py | py | 1,538 | python | en | code | 0 | github-code | 1 |
29624945873 | '''
N皇后问题,输出方案的个数
'''
class Solution:
def totalNQueens(self, n: int) -> int:
if n < 1:
return 0
return len(self.queen(n))
def conflict(self, current, arranged):
length = len(arranged)
flag = False
for i in range(length):
if abs(current - int(arran... | wangxinyufighting/algorithom | Search/Backtracking/52. N-Queens II.py | 52. N-Queens II.py | py | 797 | python | en | code | 0 | github-code | 1 |
20146507778 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {integer[]} preorder
# @param {integer[]} inorder
# @return {TreeNode}
def buildTree(self, preorder, inorder):
... | henrylu518/LeetCode | Construct Binary Tree from Preorder and Inorder Traversal.py | Construct Binary Tree from Preorder and Inorder Traversal.py | py | 587 | python | en | code | 0 | github-code | 1 |
9558573625 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 19:09:22 2023
@author: Administrador
"""
def isYearLeap(yr):
#
# Codigo from LAB Listas y return
#
if yr%4 == 0 and (yr%100!=0 or yr%400==0):
return(True)
else:
return(False)
def daysInMonth(year, month):
#
# put your new... | erafavc/python-courseEPN | diasMes.py | diasMes.py | py | 937 | python | en | code | 0 | github-code | 1 |
20974866293 | #-----MENSAJES-----
MENSAJE_BIENVENIDA = "Bienvenido al programa de cálculo de peso de envio"
PREGUNTA_PAYASOS = "Ingrese el numero de payasos que serán enviados porfavor \n"
PREGUNTA_MUÑECAS = "Ingrese el numero de muñecas que serán enviadas porfavor \n"
MENSAJE_CALCULO = "El peso total del envio es de "
MENSAJE_CALCU... | elenaposadac27/Programaci-n1 | EjerciciosDePractica/ejercicio1.3.py | ejercicio1.3.py | py | 715 | python | es | code | 0 | github-code | 1 |
18798952098 | from gi.repository import Gtk, Gdk, Gedit
from . import log
try:
debug_plugin_message = Gedit.debug_plugin_message
except: # before gedit 3.4
debug_plugin_message = lambda fmt, *fmt_args: None
CONTROL_MASK = Gdk.ModifierType.CONTROL_MASK
CONTROL_SHIFT_MASK = Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_... | jefferyto/gedit-control-your-tabs | controlyourtabs/keyinfo.py | keyinfo.py | py | 2,285 | python | en | code | 91 | github-code | 1 |
24653739965 | import tkinter as tk
from tkinter import font
from PIL import Image, ImageTk
from logic import *
def app_gui(title, width, height):
root = tk.Tk()
app_theme = "default"
#app_theme = pick_theme()
ui_config_lst = theme_config(app_theme)
global ui_config_dict
ui_config_dict = {
"text_colou... | HashBukhtiar/CubeTimer | gui.py | gui.py | py | 5,523 | python | en | code | 0 | github-code | 1 |
71223354595 | # Pairs with Specific Difference
# Given an array arr of distinct integers and a nonnegative integer k, write a function findPairsWithGivenDifference
# that returns an array of all pairs [x,y] in arr, such that x - y = k. If no such pairs exist, return an empty array.
# Note: the order of the pairs in the output array ... | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | problems/PRAMP8.py | PRAMP8.py | py | 834 | python | en | code | 0 | github-code | 1 |
43805654873 | import sys
sys.stdin = open("금속막대.txt")
T = int(input())
for test_case in range(1, T+1):
N = int(input())
driver = list(map(int,input().split()))
connect = []
for i in range(0, N):
for j in range(0, N):
if driver[2*i] == driver[2*j+1]:
break
if j == N-1:
... | 01090841589/ATM | 20190816/금속막대.py | 금속막대.py | py | 608 | python | en | code | 0 | github-code | 1 |
70765234275 | from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
import sys
import os
from data import *
from Common_Object_def import Network
bus = {}
class Ui_Export_PT(object):
def setupUi(self, Export_PT):
bus["Export_PT"] = Export_... | farzad1132/NetPlanner | ExportPhysicalTopology.py | ExportPhysicalTopology.py | py | 6,187 | python | en | code | 2 | github-code | 1 |
40653074312 | import os
import sys
#import matplotlib.pyplot as plt
import numpy as np
#import scipy.stats as stats
import xlwt
import subprocess
import pathlib
import pandas as pd
import time
from random import randint
from vehicleClass import Vehicle
from openSpaceClass import OpenSpace
from oneLaneClass import oneLaneObject
from ... | alexlssc/ProjectDegree | Code/main.py | main.py | py | 3,670 | python | en | code | 0 | github-code | 1 |
17460026299 | from . import views
from django.urls import path
"""
Url paths extended from from django.urls
"""
app_name = 'products'
urlpatterns = [
path('products/', views.product_list_view, name='products'),
path('products/<int:id>/', views.product_get_view),
]
| sgs22/needapc | products/urls.py | urls.py | py | 269 | python | en | code | 0 | github-code | 1 |
73798956195 | # -*- coding:utf-8 -*-
import sys, pickle, os, random
import numpy as np
import io
## tags, BIO
pre_tag2label = {"O": 0,
"B-PER": 1, "I-PER": 2,
"B-LOC": 3, "I-LOC": 4,
"B-ORG": 5, "I-ORG": 6
}
tag2label = {u'0': 0,u'1': 1}
def read_corpus(corpus_path):
"""
... | auas/granduate-project_auas | zh-NER-TF-master/data.py | data.py | py | 5,594 | python | en | code | 2 | github-code | 1 |
28772398965 | #문제 : https://programmers.co.kr/learn/courses/30/lessons/42747
#
#
#예시 : citations | return
# [3, 0, 6, 1, 5] 3
def solution(citations):
count = len(citations)
#5
citations.sort(reverse=True)
#citations = [6, 5, 3, 1 ,0]
cnt = 0
for i in range(count, 0, -1):
#i는 5부터 0 까지 -1씩 적용된다.... | yoncho/Algorithm_programmers | coding_test_practice/4.SORT/H_index.py | H_index.py | py | 1,005 | python | ko | code | 0 | github-code | 1 |
31290217365 | from filecmp import dircmp
import os
import argparse
import easygui
import pandas as pd
from pathlib import Path
import sys
from PyQt5.QtWidgets import (QFileDialog, QAbstractItemView, QListView,
QTreeView, QApplication, QDialog)
def convert_bytes(num):
#this function will convert byt... | thiloschild/FSDC | tests/dir_diff.py | dir_diff.py | py | 1,769 | python | en | code | 0 | github-code | 1 |
22942125072 | import json
import logging
import multiprocessing
import os
from typing import Any, Dict, Optional, Union
import lib.infers
import lib.trainers
from monai.networks.nets import BasicUNet
from monailabel.interfaces.config import TaskConfig
from monailabel.interfaces.tasks.infer_v2 import InferTask
from monailabel.inter... | Project-MONAI/MONAILabel | sample-apps/pathology/lib/configs/segmentation_nuclei.py | segmentation_nuclei.py | py | 3,756 | python | en | code | 472 | github-code | 1 |
3196314573 | # Given N axis-aligned rectangles where N > 0, determine if they all together fo
# rm an exact cover of a rectangular region.
#
# Each rectangle is represented as a bottom-left point and a top-right point. F
# or example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-lef
# t point is (1, 1) and to... | niufenjujuexianhua/Leetcode | [391]Perfect Rectangle.py | [391]Perfect Rectangle.py | py | 2,138 | python | en | code | 0 | github-code | 1 |
38129824817 | from flask import Flask,jsonify, Blueprint, render_template
from sys import version
import numpy
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from flask_login import login_required
import os
from pathogen_memo.controllers import countbyquery
#Set word_count_site_name
barplotbv = Blueprint('ba... | NajlaBioinfo/pathogen_memo_app | pathogen_memo/views/barplotb.py | barplotb.py | py | 1,590 | python | en | code | 0 | github-code | 1 |
28541241808 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 1 20:08:09 2021
@author: antons.sincovs
"""
import time
# fibonnacci calculation with iteration
def fib_rec(n):
if n <= 1:
return n
else:
return fib_rec(n - 1) + fib_rec( n - 2)
# fibonacci calclation with recursion
def fib_iter(n):
if n <= ... | aquarios77/python | 2021-04-06/fibonacci.py | fibonacci.py | py | 956 | python | en | code | 0 | github-code | 1 |
13497465134 | print("Welcome to the Band name generator!")
# Overcomplicated functions to prevent blank names
def request_city():
city = input("Enter your birth city:\n") # Request City
if city == "":
print("City cannot be blank!")
return request_city() # City is blank, loop back and ask again
el... | tgpethan-alt/pyaaa | band_name_generator.py | band_name_generator.py | py | 755 | python | en | code | 0 | github-code | 1 |
19323620462 | import copy
row_length, column_length = 0, 0
def is_quadrate(i, j, board, dp):
global row_length, column_length
if i-1 < 0 or j-1 < 0:
return board[i][j]
else:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1
return dp[i][j]
def solution(board):
global row_length, col... | hanameee/Algorithm | Programmers/연습문제/src/가장큰정사각형찾기.py | 가장큰정사각형찾기.py | py | 744 | python | en | code | 2 | github-code | 1 |
34380064426 | """
Module with Q-learning
Classes:
Qlearning
"""
import environment as ev
from agent import Agent
class Qlearning:
@staticmethod
def learn_strategy(
agent: Agent,
discount_factor: float,
learning_rate: float,
epochs: int,
max_steps: int
) -> None:
"""
... | BartekWrzalski/Maze_Q-learning | q_learning.py | q_learning.py | py | 2,387 | python | en | code | 0 | github-code | 1 |
14195692388 | #loading all the needed libraries
import dash
import dash_core_components as dcc
from dash import html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
# must add this line in order for the app to be deployed successfully on Heroku
# from app import server
from app import app
... | rcreddykovvuri/Military-plotly | index.py | index.py | py | 2,636 | python | en | code | 0 | github-code | 1 |
10604125433 | myDict = {
"prabhat": "mr Perfect",
"gudan": "monu lover",
"marks": [1,2,3,4,5,6,7,8,9,0] ,
"anotherDict" : {'Lovely':'Lohra lover' },
1:2
}
# Method of dictionary
print(list(myDict.keys()))# printing the keys of dictionary
print(list(myDict.values())) # printing the values of dictionar... | prabhatadvait/PYTHON-ALL-CHAPTER | Python course with Prabhat/5. Chapter 5/02_dictionary_methods.py | 02_dictionary_methods.py | py | 935 | python | en | code | 2 | github-code | 1 |
75004236192 | from collections import OrderedDict
from scipy.integrate import odeint
from abstract_model import ModelABC
import numpy as np
class OdeModel(ModelABC):
"""Differential-based Models integrated with SciPy LSODA wrapper
Attributes
----------
model : func (x0, t, xout, p)
A callable function that... | FedericoV/SysBio_Modeling | model/ode_model.py | ode_model.py | py | 6,931 | python | en | code | 2 | github-code | 1 |
38583826955 | """
App project
"""
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
try:
import pygame
pygame.mixer.init()
except ModuleNotFoundError:
pygame = None
def play... | Sheer0wn/App | main.py | main.py | py | 3,182 | python | en | code | 2 | github-code | 1 |
622199866 | import torch.nn.functional as F
import torch
import numpy as np
def to_crop_resize(img, bbox, landm, resize=128):
buff = torch.zeros(img.size(0), img.size(1), resize, resize)
landm_buff = torch.zeros_like(landm)
for i, (box, mark) in enumerate(zip(bbox, landm)):
# image cropping and resizing
... | blacknwhite5/privacy-preserving-v2 | utils.py | utils.py | py | 4,092 | python | en | code | 0 | github-code | 1 |
538086250 | #!/usr/bin/env python
"""Time tracking
Usage:
timetracking -p PROJECTNAME [-c] start
timetracking [-p PROJECTNAME] end
timetracking [-a] list
timetracking report
timetracking add
timetracking -h
Options:
-p PROJECTNAME --project=PROJECTNAME project name
-c --continue also cont... | teroyks/timetracking | timetracking.py | timetracking.py | py | 2,164 | python | en | code | 0 | github-code | 1 |
73501732514 | """
Author: Brian Mascitello
Date: 12/5/2017
Websites: http://adventofcode.com/2015/day/12
Info: --- Day 12: JSAbacusFramework.io ---
--- Part Two ---
"""
import json
data = json.load(open('Day12Q1 2015 Input.txt'))
def calculate_sum(input_data):
summation = 0
if not isinstance... | Brian-Mascitello/Advent-of-Code | Advent of Code 2015/Day 12 2015/Day12Q2 2015.py | Day12Q2 2015.py | py | 833 | python | en | code | 0 | github-code | 1 |
7681825183 | # 2. Задайте список. Напишите программу, которая определит,
# присутствует ли в заданном списке строк некое число.
import os
os.system("clear")
list1 = ["2", "43", "5", "331", "91", "35", "79", "53"]
x = input("Введите число: ")
for i in list1:
if x == i:
print(f"число {i} присутствует в списке")
... | Zabaluna/HW-Python | Sem3/Seminar3.py/Task2.py | Task2.py | py | 959 | python | ru | code | 0 | github-code | 1 |
416318020 | import csv
import os
from users_api.models import WdaeUser
from django.core.management.base import BaseCommand, CommandError
from .import_base import ImportUsersBase
class Command(ImportUsersBase, BaseCommand):
help = (
"Delete all users and adds new ones from csv. "
"Required column names for the... | iossifovlab/gpf | wdae/wdae/users_api/management/commands/users_restore.py | users_restore.py | py | 1,232 | python | en | code | 1 | github-code | 1 |
12178673975 | n=int(input("Type of cross(eg:3 4 5...): "))
cond=True
while cond:
if n<3:
print("Cross starts from 3 ONLY!!!")
n=int(input("Type of cross(eg:3 4 5...): "))
else:
cond=False
matrix=['0' for x in range(n**2)]
def check(player): #Function for checking whether the player has won
... | Akash-Raj-ST/TicTacToe | tictactoeSoftcode.py | tictactoeSoftcode.py | py | 3,394 | python | en | code | 0 | github-code | 1 |
16003087147 | from disco.bot import Plugin
class TutorialPlugin(Plugin):
@Plugin.command('ping')
def command_ping(self, event):
event.msg.reply('pong')
@Plugin.command('test')
def command_test(self, event):
event.msg.reply('I pass')
@Plugin.command('divide', '<a:int> <b:int>', group='math')
... | Alitech3/Question-Bot | plugins/tutorial.py | tutorial.py | py | 1,430 | python | en | code | 0 | github-code | 1 |
10443648012 | import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load, load_module, reload_module, get_stdout, check_source
from functools import reduce
import os
import textwrap
from random import randint
exercise = 'src.histogrammi'
function = 'histogrammi'
@points('5.histogrammi')
clas... | dnnijmlinn/Python-mooc-2021 | osa05-12_histogrammi/test/test_histogrammi.py | test_histogrammi.py | py | 4,383 | python | fi | code | 1 | github-code | 1 |
5278882979 | import json
import requests
from bs4 import BeautifulSoup
import sys
import os
import os.path
import shutil
try : # Tries to create a folder called images
os.mkdir('images')
except: # If the image folder already exists it deletes the folder and creates a new one to get rid of residual images
print("Image Fold... | GongCode/SocialMediaPG | image_scraper.py | image_scraper.py | py | 3,056 | python | en | code | 0 | github-code | 1 |
12048268158 | import pytest
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from sqlalchemy.orm import clear_mappers
from app import create_app
from repositories.sql_alchemy.mapping.user_mapping import user_mapping
from repositories.sql_alchemy.mapping.favorite_document_mapping import favorite_docum... | gerbless/clean-architecture-example-project | repositories/tests/pytest_fixture_db.py | pytest_fixture_db.py | py | 1,380 | python | en | code | 0 | github-code | 1 |
36105392593 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""This module implements the combiner class."""
import numpy as np
from numpy import ma
try:
import bottleneck as bn
except ImportError:
HAS_BOTTLENECK = False
else:
HAS_BOTTLENECK = True
from .core import sigma_func
from astropy.nddata i... | astropy/ccdproc | ccdproc/combiner.py | combiner.py | py | 38,231 | python | en | code | 86 | github-code | 1 |
23149056100 | #!/usr/bin/env python
###############################################################################
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License... | donovan-h-parks/DBB | dbb/expand.py | expand.py | py | 3,614 | python | en | code | 1 | github-code | 1 |
28773442507 | texto= (input("Digite um texto: "))
texto = str(texto)
ind=0
result=''
while ind < len(texto):
result = texto [ind] + result
ind +=1
if texto == result:
print ('O texto é palindromo.')
else:
print('O texto não é palindromo.') | camilobmoreira/Fatec | 1_Sem/Algoritmos/texto_palindromo.py | texto_palindromo.py | py | 244 | python | pt | code | 0 | github-code | 1 |
13412598410 | import sqlite3
# open the connection to the database
connection = sqlite3.connect("C:\\Users\\User\\HW2database1.db")
cursor = connection.cursor()
def create_tables():
"""
Creates tables Provider and Canteen
"""
# sql command to create table Provider
sql_command = """
CREATE TA... | TslEdv/Python-Advanced | HW2/main.py | main.py | py | 5,484 | python | en | code | 0 | github-code | 1 |
37621328814 | from espn_api.football import League
import pandas as pd
import time
from tabulate import tabulate
from operator import itemgetter
from calcPercent import percent
import random
start_time = time.time()
# Pennoni Younglings
league = League(league_id=310334683, year=2022, espn_s2='AEC3jc8inPISUEojfHvhzvOsdtsGWNv8sGIxjk... | LouieR3/FantasyFootballApp | remainingSched.py | remainingSched.py | py | 6,737 | python | en | code | 2 | github-code | 1 |
31172710171 | N = int(input())
N_list = list(map(int,input().split()))
result = 0
for i in N_list:
if i == 2:
result += 1
for k in range(2,i):
if i % k == 0:
break
if k == i-1:
result += 1
print(result) | Juseong-Yu/Baekjoon | 1000/1978.py | 1978.py | py | 245 | python | en | code | 0 | github-code | 1 |
19701089503 | from tkinter import*
from tkinter.messagebox import showerror # pour le message d'erreur si y a r d'ecrit
from Enigma import* #import enigma et ses fonctions dans tkinter
Alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
R... | thomasfroger/Enigma | Enigma test/tkinter.py | tkinter.py | py | 3,641 | python | fr | code | 0 | github-code | 1 |
14099855837 | from django.urls import path
from admin import views
from admin.views import *
urlpatterns = [
path('',views.Counts,name='admindash'),
path('login', views.Login.as_view(), name='login'),
path('hospital', views.Hospital_details, name='hospital_details'),
path('hospital_approval/<int:id>', views.Hospita... | Nasim004/Project-easyDoc-Backend | admin/urls.py | urls.py | py | 899 | python | en | code | 0 | github-code | 1 |
7137304548 | import pymc3 as pm
import numpy as np
import arviz as az
import matplotlib.pyplot as plt
x_size = 100
global x1,x2
x1 = np.random.randn(x_size)
x2 = np.random.randn(x_size)
def sim_model(a,b):
#x_size = 10000
#x1 = np.random.randn(x_size)
#x2 = np.random.randn(x_size)
return x1*a + x2*b +3
... | HITwanghaitao/bayes_test_model | test1.py | test1.py | py | 783 | python | en | code | 0 | github-code | 1 |
69847575393 | from elasticsearch import Elasticsearch
import pandas as pd
import json
import csv
def indexTMDB(filename):
f = open(filename,"r", encoding="UTF8")
reader = csv.DictReader(f)
for i,row in enumerate(reader):
if i == 4553: continue
movie = {
"budget" : float(row["budget"]),
... | didrikmunther/DD2477-group-11 | backend/dataloader.py | dataloader.py | py | 1,971 | python | en | code | 2 | github-code | 1 |
34215681035 | import torch
from torch.nn import functional as F
import numpy as np
import torch.nn as nn
from . import ramps
class DiceLoss(nn.Module):
def __init__(self, n_classes):
super(DiceLoss, self).__init__()
self.n_classes = n_classes
def _one_hot_encoder(self, input_tensor):
tensor_list = ... | Huiimin5/comwin | code/utils/losses.py | losses.py | py | 1,934 | python | en | code | 11 | github-code | 1 |
72507336674 | #AutoTraceDraw.py
import turtle
turtle.title('自动绘制轨迹')
turtle.setup(800,600,0,0)
turtle.pencolor("red")
turtle.pensize(5)
#数据读取
datals = []
f = open("data.txt")
for line in f:
line =line.replace("\n", "")
datals.append(list(map(eval, line.split(","))))
f.close()
#自动绘制
for i in range(len(datals))... | SPOOKY01/Vanilla | Python北京理工大学MOOC/#AutoTraceDraw.py | #AutoTraceDraw.py | py | 547 | python | en | code | 1 | github-code | 1 |
26972100247 | fruit = {"Orange": "a sweet, organge, citrus fruit",
"Apple": "good for making citrus fruit",
"Lemon": "a sour, sweet fruit growing in bunches",
"Grape": "a small, sweet fruit growing in bunches",
"Lime": "a sour, green citrus fruit"}
print(fruit)
# ordered_keys = list(fruit.keys())
... | Hanan-Hussein/dictonaries-py | dictionaries3.py | dictionaries3.py | py | 648 | python | en | code | 0 | github-code | 1 |
2208901653 | import argparse
import csv
import io
import logging
import pathlib
import sys
import tabulate
from . import constants
from . import util
from . import psf
def csv_line(data):
"""csv_line
Generate a single line of CSV as a string.
:param data: list of items constituting the record
"""
output = i... | charlesdaniels/pretor | pretor/export.py | export.py | py | 4,212 | python | en | code | 0 | github-code | 1 |
44946984296 | # Reference.
# https://pypi.org/project/sumy/
# https://newsapi.org/docs/endpoints/top-headlines
import requests
from goose3 import Goose
from transformers import TFAutoModelWithLMHead, AutoTokenizer
def get_top_headlines():
print('Entered get_top_headlines.')
# Get top headlines from API.
respons... | karanasher/news_summarizer | wisk/articles/utils.py | utils.py | py | 3,642 | python | en | code | 0 | github-code | 1 |
24512988407 | import os
import zipfile
SOURCE_ZIP_NAME = 'source_code.zip'
def zip_dir(directory: str, zip_file: str):
with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(directory):
for file in files:
zipf.write(os.path.join(root, file))
de... | shemetz/Google_Hashcode_2022 | src/zip_source.py | zip_source.py | py | 638 | python | en | code | 0 | github-code | 1 |
36959104536 | """
A module to create gdf from df
"""
import warnings
import geopandas as gpd
def df_to_gdf(df, x='long', y='lat'):
"""
Transform raw Lat/Long data to GeoDataFrame
Parameters
==========
df: DataFrame
x: Latitude
y: Longitude
Returns
=======
gdf: Point GeoDataFrame (unprojected)
"""
gdf = gpd.GeoData... | shuai-zhou/gps2space | gps2space/geodf.py | geodf.py | py | 425 | python | en | code | 3 | github-code | 1 |
23612968205 | from InternalControl import cInternalControl
import tkinter.messagebox as tkMessageBox
import tkinter as tk
import tkinter.font as tkFont
import cfdi_quart_excel_version as win_cfdi
import postgresql as bd
import utils as tool
import datetime
import os
import threading
import sys
objControl= cInternalControl()
registe... | gitquart/appCFDIMasivoSAT | login_window.py | login_window.py | py | 12,745 | python | en | code | 0 | github-code | 1 |
74826794272 | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from cams import views
router = DefaultRouter()
router.register(r'cams', views.ChannelViewSet)
router.register(r'records', views.RecordViewSet)
urlpatterns = [
path('image_stream/<int:channel_id>/', views.image_stream, name='i... | EL-BID/distancia2-api | cams/urls.py | urls.py | py | 373 | python | en | code | 5 | github-code | 1 |
42927270425 | import requests
url = "https://0a4f008504c83dafc07450e9003f007b.web-security-academy.net/my-account/change-email"
data = {
"email": "test@test2.com"
}
cookies = {
"session": "ZVCrXoUWWZoIUkHRUsB8uxaA2ebMb7nr"
}
r = requests.post(url, data=data, cookies=cookies)
print(r.text) | singha-brother/Web_Security_Notes | Portswigger/Labs_test_with_python/CSRF/lab01.py | lab01.py | py | 282 | python | en | code | 1 | github-code | 1 |
6333529757 | '''
VERSION
20180916
PUBLIC DOMAIN NOTICE
The utility posted on this page is based on the program "FZERO.F",
written by L. F. Shampine (SNLA) and H. A. Watts (SNLA),
based upon a method by T. J. Dekker.
FZERO.F is part of the SLATEC library of programs, and
its original FORTRAN cod... | aalmela/2020 | 10_Practicas_Laboratorio/inductores/calculo_solenoide/fzero.py | fzero.py | py | 7,735 | python | en | code | 4 | github-code | 1 |
21088567211 | import torch
def calc_psnr(img1, img2):
# input: img1 (img2)
# torch.Tensor, range in [0, 1.0]
img1, img2 = img1 * 255.0, img2 * 255.0
mse = torch.mean((img1 - img2) ** 2)
if mse == 0:
return float('inf')
return 20 * torch.log10(255.0 / torch.sqrt(mse))
class AverageMeter... | jzsherlock4869/denoise-ignet | utils.py | utils.py | py | 645 | python | en | code | 2 | github-code | 1 |
29164305065 | from termcolor import colored
from random import randint
shapes = []
shapes.append([(0,0), (1,0), (2,0), (3,0)])
shapes.append([(1,0), (0,1), (1,1), (2,1), (1,2)])
shapes.append([(2,2), (2,1), (0,0), (1,0), (2,0)])
shapes.append([(0,0), (0,1), (0,2), (0,3)])
shapes.append([(0,0), (1,0), (0,1), (1,1)])
colors = ["red"... | ericekstrm/advent-of-code | 2022/17.py | 17.py | py | 4,856 | python | en | code | 0 | github-code | 1 |
4220179859 | def game_over(board):
for row in board:
if ' ' in row:
return False
return True
def win_horizontaly(board, player):
for row in board:
for column in range(4):
if row[column] == player \
and row[column+1] == player \
and row[col... | CleverAndWitty/CIS1501-Fall2018 | Lab8/Connect4.py | Connect4.py | py | 2,662 | python | en | code | 0 | github-code | 1 |
29522467721 | import numpy as np
class GaussianNB:
def __init__(self):
"""
_classes: ndarray, class labels (obtained from y)
_mean, _var: ndarray, ndarray; mean and variance of the Gaussian distribution.
Shape is (n_classes, n_features). Initialized to 0s.
_priors: ndarray... | Duckchoy/AI-algos | ML/supervised/NaiiveBayes.py | NaiiveBayes.py | py | 3,156 | python | en | code | 0 | github-code | 1 |
33574594955 | # set module search path
import os
ast2pyast_path = os.path.abspath('../antlr2pyast/')
import sys
sys.path.append(ast2pyast_path)
# system packages
import argparse
import re
# AST tree generation/conversion packages
from converter import antlr2pyast
import ast
####### functions to print an AST tree
def str_node(node... | ProgrammingEduBVI/JupyterVox | ASTVox_Antlr4/src/tests/test.py | test.py | py | 5,802 | python | en | code | 0 | github-code | 1 |
1777293937 | # -*- coding: UTF-8 -*-
#
from __future__ import with_statement
import urllib,re,random,json
from google.appengine.api import files
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import blobstore_handlers
from goog... | usbuild/GAEBucket | disk/index.py | index.py | py | 3,490 | python | en | code | 2 | github-code | 1 |
42614609033 | import math
def convert_mm(x, y, z, rx, ry, rz, re):
str_x = "{:4d}.{:03d}".format(x // 1000, x % 1000)
str_y = "{:4d}.{:03d}".format(y // 1000, y % 1000)
str_z = "{:4d}.{:03d}".format(z // 1000, z % 1000)
str_rx = "{:4d}.{:04d}".format(rx // 10000, rx % 10000)
str_ry = "{:4d}.{:04d}".format(ry // ... | wendycahya/Yaskawa-Communication | gui/sampleCodeTest/1-functionTest.py | 1-functionTest.py | py | 3,915 | python | en | code | 3 | github-code | 1 |
73915807713 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Module to solve stochastic equations of motion."""
__name__ = 'qom.solvers.stochastic'
__authors__ = ["Sampreet Kalita"]
__created__ = "2023-08-13"
__updated__ = "2023-09-14"
# dependencies
from copy import deepcopy
import numpy as np
import time
# qom modules
from ... | Sampreet/qom | qom/solvers/stochastic.py | stochastic.py | py | 11,572 | python | en | code | 0 | github-code | 1 |
22419105675 | from experiment import *
import copy
INPUT_DIR = '/lustre/work1/wallach/jmoore/email_networks/input/nhc/'
OUTPUT_DIR = '/lustre/work1/wallach/jmoore/email_networks/output/nhc/'
N_TOPICS_DIMENSIONS = [1, 2, 5, 10, 25, 50, 75, 100, 125, 150, 200]
ALPHAS = [0.0001, 0.001, 0.01, 0.1]
BETAS = [0.01]
NUM_AUTHORS = 30
GLO... | pkrafft/topic-partitioned-multinetwork-embeddings | scripts/run_script/nhc_experiments.py | nhc_experiments.py | py | 3,593 | python | en | code | 1 | github-code | 1 |
40880659247 | import numpy as np
"""
i:本层的第i次运算,从0开始,至K-1结束
W矩阵:前一层(m维)和该层(n维)的连接矩阵,输入应该为(n*m)的形状
U矩阵:本层(n维)的连接矩阵,输入应该为(n*n)的形状
K:输入序列的长度
"""
def con_matrix (i, K, W, U, bs):
if ( i == 0 ):
W = W
b = bs
n = np.shape(W)[0]
m = np.shape(W)[1]
S = np.zeros((np.shape(W)[0],(K-1)*m))
... | LeungCAC/BPMC2-Verifier | network_computation.py | network_computation.py | py | 1,771 | python | en | code | 0 | github-code | 1 |
21509245631 | #!/usr/local/bin/python3
import os, sys, pprint, logging
import Inventory_Modules
import argparse, boto3
from colorama import init,Fore,Back,Style
from botocore.exceptions import ClientError, NoCredentialsError
init()
parser = argparse.ArgumentParser(
description="We\'re going to find all resources within any of th... | alincalinciuc/Inventory_Scripts | all_my_cfnstacksets.py | all_my_cfnstacksets.py | py | 4,303 | python | en | code | null | github-code | 1 |
34517192383 | dict_history = [];
def binary_search(list, item):
# array indices
low = 0
high = len(list) - 1
global dict_history;
def print_dic(dict):
for val in dict:
# print(val) # prints dict at index # {'item': 9, 'low': 0, 'high': 100, 'mid': 50, 'guess': 50}
# prin... | stevekutz/django_algo_exp1 | bin_search.py | bin_search.py | py | 2,339 | python | en | code | 0 | github-code | 1 |
39181025783 | import requests
from bs4 import BeautifulSoup
from lxml import html
from lxml import etree
import pandas as pd
import numpy as np
from pprint import PrettyPrinter
from re import sub
# my pp
pp = PrettyPrinter()
# # This code is meant to import screenplays from imsdb.com (Futurama) and automatically import all of the... | rayyungdev/tf_benderbot | imdsb_scrape.py | imdsb_scrape.py | py | 3,928 | python | en | code | 0 | github-code | 1 |
25484172384 | def commonCharacterCount(s1, s2):
#return sum([min(s1.count(c),s2.count(c)) for c in set(s1) & set(s2)])
d1 = {}
d2 = {}
for c in s1:
d1[c] = d1.get(c, 0) + 1
for c in s2:
d2[c] = d2.get(c, 0) + 1
t = 0
for i in range(ord('a'), ord('z')+1):
t += min(d1.get(chr(i), 0)... | pineman/code | chall/codesignal/arcade/10-commonCharacterCount.py | 10-commonCharacterCount.py | py | 355 | python | en | code | 1 | github-code | 1 |
37376977207 | import json
import subprocess
import time
import argparse
import datetime
def main(a):
if not a.json:
return
data = json.load(open(a.json))
data = sorted(data, key=lambda x: x["score"] / x["g_cost"])
for result in data:
print("{seed}:".format(seed=result["seed"]))
print("S = {S... | kenkoooo/WanderingTheCity | python/analysis.py | analysis.py | py | 1,114 | python | en | code | 0 | github-code | 1 |
15127971142 | # O(N) time | O(1) space
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
ROWS, COLS = len(image), len(image[0])
def dfs(row, col, startColor=image[sr][sc]):
if not 0 <= row < ROWS or not 0 <= col < COLS or image[row][... | mmichalak-swe/Algo_Expert_Python | LeetCode/733_Flood_Fill/attempt_1.py | attempt_1.py | py | 636 | python | en | code | 3 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.