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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
73247744995 | from typing import Optional, List
import numpy as np
import torch
import torch.nn as nn
from transformers import RagSequenceForGeneration, AutoModel, AutoConfig, RagRetriever, BatchEncoding
from transformers.models.dpr.modeling_dpr import DPRQuestionEncoderOutput
from distributed_pytorch_retriever import RagPyTorchDist... | jzbjyb/multihop | rag/rag_model.py | rag_model.py | py | 19,076 | python | en | code | 2 | github-code | 1 |
19926976795 | import keras
from keras.datasets import mnist
from keras.models import load_model
def Getdata():
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train / 255
x_test = x_te... | Sun2018421/keras-Lenet-5 | getDataforEmbedded.py | getDataforEmbedded.py | py | 635 | python | en | code | 0 | github-code | 1 |
74138069153 | import logging
from enum import Enum
from typing import Optional
import pandas as pd
from pandas import DataFrame
import config
from asseeibot import runtime_variables
from asseeibot.models.cache import Cache
from asseeibot.models.fuzzy_match import FuzzyMatch, MatchBasedOn
from asseeibot.models.ontology_dataframe im... | dpriskorn/asseeibot | asseeibot/models/match_cache.py | match_cache.py | py | 8,581 | python | en | code | 3 | github-code | 1 |
73934613795 | import numpy as np
import cv2
import nibabel as nib
import os
import yaml
from pytorch_fid import fid_score
#from pytorch_lightning import metrics
import argparse
parser = argparse.ArgumentParser(description='Metrics Script')
parser.add_argument('--bodymask_path', type=str)
parser.add_argument('--real_slices_path',... | deltahue/DL-Project-2020 | contrastive-unpaired-translation-master/evaluate_metrics.py | evaluate_metrics.py | py | 6,275 | python | en | code | 0 | github-code | 1 |
5875820973 | import gc
import numpy as np
import pandas as pd
import tensorflow as tf
import os
import cv2
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use("seaborn-v0_8")
from tqdm import tqdm
# pathlib to my loccal file
files = os.listdir("/home/michael/Desktop/archive/dataset/")
files
# initialisation of... | Bpdum/face_recogntion_tfModel_android_pycharm | main.py | main.py | py | 3,914 | python | en | code | 0 | github-code | 1 |
7922604217 |
import shutil
import webbrowser
import numpy as np
from math import ceil
from time import time
from random import randint, shuffle, seed
from tec.ic.ia.pc2.model.file_utils import *
class Gen:
"""
'Escructura' para manejar cada gen
:var array: numpy array con los contenidos del tablero
:var score: pu... | JulianSalinas/carrots-finder | tec/ic/ia/pc2/model/genetic_algorithms.py | genetic_algorithms.py | py | 18,821 | python | es | code | 0 | github-code | 1 |
2284786552 | import os
from kivy.app import App
from kivy.core.window import Window
from kivy.metrics import dp
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.scrollview import ScrollView
class S... | petchorine/double_view | swipebtn_refresh_gallery.py | swipebtn_refresh_gallery.py | py | 2,874 | python | en | code | 0 | github-code | 1 |
70755604514 | import unittest2
import os
import tempfile
import top
from top.utils.files import (copy_file,
remove_files,
get_directory_files_list)
class TestExporterDaemon(unittest2.TestCase):
@classmethod
def setUpClass(cls):
cls._ed = top.ExporterDaemon... | loum/top | top/tests/test_exporterdaemon.py | test_exporterdaemon.py | py | 5,280 | python | en | code | 0 | github-code | 1 |
37210347927 | # Import os to set API key
import os
# Import OpenAI as main LLM service
from langchain.llms import OpenAI
from langchain.embeddings import OpenAIEmbeddings
# Bring in streamlit for UI/app interface
import streamlit as st
# Read the markdown content from a file
with open("styles.md", "r") as f:
markdown_content = ... | NikolaienkoIgor/RAGreport | app.py | app.py | py | 1,942 | python | en | code | 0 | github-code | 1 |
39261873559 | #setting initial value of variable
score = 0
score = int(score)
#Ask user for their name
name = input("What is your name?")
name = name.title()
print("""Hello {}, welcome to the classification algorithm for risk prediction!
You will be presented with 2 questions regarding your age and profession.
Enter the appropriat... | vaishnavimanivannan18/RiskLevelAlgorithm | Algorithm.py | Algorithm.py | py | 1,522 | python | en | code | 0 | github-code | 1 |
16391999279 | from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton
from pizza.controller.ControllorePizza import ControllorePizza
class VistaEliminaPizza(QWidget):
def __init__(self, pizza, elimina_pizza, elimina_callback, parent=None):
super(VistaEliminaPizza, self).__init__(parent)
self.cont... | CappeXII/ing_software | pizza/view/VistaEliminaPizza.py | VistaEliminaPizza.py | py | 1,018 | python | en | code | 0 | github-code | 1 |
23167904841 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import tensorflow as tf
import tensorflow.contrib.slim as slim
class Block(namedtuple('Block', ['scope', 'unit_fn', 'args'])):
"""A named tuple describing a ResNet bloc... | luckycallor/InsightFace-tensorflow | backbones/utils.py | utils.py | py | 4,551 | python | en | code | 246 | github-code | 1 |
73501419235 | import logging
import boto3
class SESService():
def __init__(self):
self.client = boto3.client(
'ses',
aws_access_key_id="INPUT YOUR ACESS KEY FROM AWS",
aws_secret_access_key="INPUT YOUR SECRET ACESS KEY FROM AWS",
region_name="INPUT YOUR REGION",
)
... | vmakksimov/IM_System | services/ses.py | ses.py | py | 1,630 | python | en | code | 0 | github-code | 1 |
35152871757 | def solution(n):
answer = 0
for i in range(1, n+1):
answer += 1 if is_prime(i) else 0
return answer
def is_prime(n):
if n == 1 or (n != 2 and n % 2 == 0):
return False
elif n == 2:
return True
e = round(n ** 0.5) + 1
for i in range(3, e, 2):
if n % i == 0:... | ihaeeun/Algorithms | Python/Programmers/Level 1/prime_num.py | prime_num.py | py | 384 | python | en | code | 0 | github-code | 1 |
4607515560 | import numpy as np
import math
# Python 3 program for the
# haversine formula
def haversine(lat1, lon1, lat2, lon2):
# distance between latitudes
# and longitudes
dLat = (lat2 - lat1) * math.pi / 180.0
dLon = (lon2 - lon1) * math.pi / 180.0
# convert to radians
lat1 = (lat1)... | Manit1998/white1 | manit.py | manit.py | py | 1,419 | python | en | code | 1 | github-code | 1 |
16748849391 | from __future__ import annotations
import os
import typing as t
import logging
import pathlib
from typing import TYPE_CHECKING
import yaml
import pytest
import bentoml
from bentoml._internal.utils import bentoml_cattr
from bentoml._internal.models import ModelStore
from bentoml._internal.models import ModelContext
f... | almirb/BentoML | tests/conftest.py | conftest.py | py | 6,054 | python | en | code | null | github-code | 1 |
41307675140 | '''
https://leetcode.com/problems/minimum-height-trees/description/
'''
from collections import defaultdict, deque
# there can only be at most two roots in MHT, which are the mid points of the longest path
# find leaves, remove leaves from neighbours
# keep doing as long as num of nodes is > 2
# ones remaining are t... | huiwenhw/interview-prep | leetcode_Python/graph_MinHeightTrees.py | graph_MinHeightTrees.py | py | 2,527 | python | en | code | 22 | github-code | 1 |
21923155762 | #!/usr/bin/python
import json
import os
import sys
config = sys.argv[-1]
# load json content from config file
def load_json():
with open(config) as components:
return json.load(components)
json = load_json()
# helper function for creating folders
def create_folder(folder_name,prev = None):
if prev ... | faddalibrahim/scripts-and-utils | Python/react_component_generator/create.py | create.py | py | 1,563 | python | en | code | 0 | github-code | 1 |
37730803565 | from LinkedList import LinkedList
def find_middle(linked_list):
fast_tracker = linked_list.head_node
slow_tracker = linked_list.head_node
#iterate fast_tracker normally
while fast_tracker:
fast_tracker = fast_tracker.get_next_node()
if fast_tracker:
#iterate fast tracker twice for every one ... | ssredhead/pythonDictionary | dataStructuresAndAlgorithms/2 - Linked Lists/fastSlowTrackerReturnMiddle.py | fastSlowTrackerReturnMiddle.py | py | 1,183 | python | en | code | 0 | github-code | 1 |
72663761634 | import pandas as pd
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
import xlsxwriter
def add_feature_metadata(df_target, df_feature_metadata, df_target_fn_col=None):
"""Adds feature metadata columns to df_target.
Args:
df_target - a DataFrame; must contain featu... | KnowEnG/platform | nest_py/lib_src/fst_pipeline/fst_utils.py | fst_utils.py | py | 4,881 | python | en | code | 2 | github-code | 1 |
19586718692 | import time
import numpy as np
import smbus
from ugly.drivers.base import Driver
from ugly.drivers.hardware.i2c import Register, BankedRegister
CONFIG_BANK = 0x0b
BANK_REGISTER = 0xfd
PICTURE_MODE = 0x00
AUTOPLAY_MODE = 0x08
AUDIOPLAY_MODE = 0x18
class IS31FL3731(Driver):
bank = Register(BANK_REGISTER)
m... | ali1234/ugly | ugly/drivers/hardware/is31fl3731.py | is31fl3731.py | py | 2,688 | python | en | code | 2 | github-code | 1 |
26292649193 | """Management of per-player info."""
from functools import partial
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator, QPalette, QColor
from PyQt5.QtWidgets import (
QFormLayout,
QGroupBox,
QGridLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QWidget,
)
from table.s... | martinblake/pope-joan | table/player.py | player.py | py | 4,657 | python | en | code | 0 | github-code | 1 |
13762040080 | # (11564번 / 아스키 코드 / B5)
# 값 입력
value = input()
# value의 type이 str이라면 ord() 함수를 통해 아스키 코드 출력
if(str(type(value)) == "<class 'str'>") :
print(ord(value))
# value의 type이 int라면 chr() 함수를 통해 아스키 코드 출력
else :
print(chr(value)) | irishNoah/Algorithm-Study | BAEKJOON(백준 온라인 저지)/10000번~/11564.py | 11564.py | py | 316 | python | ko | code | 4 | github-code | 1 |
40096865876 | #!/usr/bin/env python
import random
import logging
import datetime
import cPickle
from time import time
class GeneticAlgorithm(object):
"""Runs genetic algorithm, contains chromosomes and applies fitness,
selection, recombination and mutation methods to them."""
def __init__(self,
popula... | fergaljd/pep_ga | ga.py | ga.py | py | 7,279 | python | en | code | 0 | github-code | 1 |
26419915784 | n = list()
for c in range (0, 5):
p = 0
n.append(int(input('Digite um valor: ')))
while p < c:
if n[p] > n[c]:
aux = n[p]
n[p] = n[c]
n[c] = aux
p += 1
print(n)
| EnricoCB/python | PythonEx/ex80.py | ex80.py | py | 233 | python | en | code | 0 | github-code | 1 |
13025816665 | import glob
import cv2
import pandas as pd
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from skimage.metrics import structural_similarity as ssim
import os
import sys
def SearchExtFiles(fpath, ext, lst):
try:
flist = os.listdir(fpath)
except:
return
f... | siszero/TIL | Python/main.py | main.py | py | 3,313 | python | ko | code | 0 | github-code | 1 |
71634532833 | import json
import argparse
import shutil
import nbt
import os
def main():
parser = argparse.ArgumentParser(description='修改玩家座標')
parser.add_argument("username", help="Player name", type=str)
parser.add_argument("dim", help="Target dim", type=int)
parser.add_argument("x", help="Target x", type=float)... | danny50610/MCServerTool | ChangePlayerPos.py | ChangePlayerPos.py | py | 1,179 | python | en | code | 1 | github-code | 1 |
15746108853 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 11:26:01 2019
@author: soura
"""
import hashtag
import query
import username
import json
import decider
import pandas as pd
class Transfer:
def __init__(self):
self.file_mapping = {"query":"query_results.json", "username":"username_results.... | SaurabhRuikar/TwitterMining | control_transfer.py | control_transfer.py | py | 1,045 | python | en | code | 0 | github-code | 1 |
71177844514 | import numpy as np
class Sudoku:
def __init__(
self, arr: np.array = np.zeros((9, 9)), possibilities: np.array = None
):
"""Create a new Sudoku instance, by providing a 9 by 9 array that holds
the starting position. Empty fields should be set to 0.
:param arr: Input sudoku, 9×... | brmdv/sudoku-solvers | sudokusolver.py | sudokusolver.py | py | 7,051 | python | en | code | 0 | github-code | 1 |
73184180514 | """
Helpers for processing JUnit evaluations.
"""
import os
import stat
import patoolib
import glob
import subprocess32 as subprocess
from application import app
from application.models import TestResult, TestCase
from flask import render_template
from shutil import move
import xml.etree.ElementTree as ET
from shutil i... | amrdraz/java-project-runner | application/junit.py | junit.py | py | 16,172 | python | en | code | 0 | github-code | 1 |
69834285154 | from .vars import *
from .utils.utils import *
import re
def checkAttempt(lines):
recordingStarts = search('== Recording Start ==', lines)
streamingStarts = search('== Streaming Start ==', lines)
replaybufferStarts = search('== Replay Buffer Start ==', lines)
if (len(recordingStarts) + len(streamingSt... | obsproject/loganalyzer | checks/encoding.py | encoding.py | py | 9,966 | python | en | code | 41 | github-code | 1 |
71377833954 | """Kernel computation for gravity and magnetics."""
import numpy as np
from pygimli.utils import ProgressBar
def SolveGravMagHolstein(mesh, pnts, cmp, igrf=None, foot=np.inf):
"""Solve gravity and/or magnetics problem after Holstein (1997).
Parameters
----------
mesh : pygimli:mesh
tetrahedra... | gimli-org/gimli | pygimli/physics/gravimetry/kernel.py | kernel.py | py | 6,702 | python | en | code | 312 | github-code | 1 |
32012632909 | import os
import subprocess
import tempfile
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from tqdm import tqdm
from metavideo import get_metagrid
from object_tracking_operations import (extract_masked_object_clips,
... | lucadra/mismas | output.py | output.py | py | 20,425 | python | en | code | 2 | github-code | 1 |
13225320697 | from __future__ import annotations
import configparser
import datetime
import os
import typing
import fabric
import invocations.console
import invoke
import invoke_patch
import src.constants
class GlobalConfig:
host: str
user: str
key_filename: str
project_name: str
project_path: str
sourc... | revolter/FileConvertBot | fabfile.py | fabfile.py | py | 5,563 | python | en | code | 45 | github-code | 1 |
31971486845 | import torch.nn as nn
import torch.multiprocessing as mp
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
import argparse
from lib.utils.file import bool_flag
from lib.utils.distributed import init_dist_node, init_dist_gpu, get_shared_folder
from lib.utils.fl... | Samuele-Colombo/transient_detection_distributed | train.py | train.py | py | 8,094 | python | en | code | 0 | github-code | 1 |
9759339084 | from src.Parameters import Parameters
from src.Roulette import Roulette
from src.EvalFunction import EvalFunction
from src.GrayConversion import GrayConversion
from src.Crossover import Xover
from src.Mutation import Mutation
import numpy as np
from src.cProfiler import do_cprofile
class GeneticAlgorithm(Parameters)... | szymag/GA | src/main.py | main.py | py | 2,059 | python | en | code | 0 | github-code | 1 |
14109182065 | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Author: ryanss <ryanssdev@icl... | jose-dom/bitcoin_forecasting | env/lib/python3.9/site-packages/holidays/countries/honduras.py | honduras.py | py | 5,085 | python | en | code | 10 | github-code | 1 |
39509461158 | import sys
sys.stdin = open("_암호생성기.txt")
for i in range(1,11):
l = int(sys.stdin.readline())
data = list(map(int,sys.stdin.readline().split()))
cnt = 1
temp = 0
while True:
temp = data[0]-cnt
if cnt == 5:
cnt = 0
for j in range(len(data)-1):
data[j]... | choikeunyoung/algorithm | SWEA/D3/1225/2_암호생성기.py | 2_암호생성기.py | py | 985 | python | en | code | 1 | github-code | 1 |
2113231979 | from __future__ import division
from __future__ import print_function
import numpy as np
import gzip
import re
import datetime
import calendar
import time
import glob
from copy import deepcopy
import warnings
import sys
import os
import codecs
from .tools import unix2date, date2unix, limitMaInidces, quantile
from .to... | maahn/IMProToo | IMProToo/core.py | core.py | py | 135,069 | python | en | code | 19 | github-code | 1 |
5877685143 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 23:02:12 2020
@author: beimingtao
"""
import os
pattern_list = []
for i in range(0,10): #change here
pattern_list.append(str(i))
#pattern = '11'
for pattern in pattern_list:
os.rename(r'./co_'+pattern+'.png',r'./co_0'+pattern+'.... | btang1/NOAA_CMAQ_Visualization_Tools | 3_animation/rename.py | rename.py | py | 340 | python | en | code | 0 | github-code | 1 |
24337799381 | import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import spacy
import networkx as nx
from scipy.spatial import distance
import matplotlib.pyplot as plt
import nltk
from collections import Counter, defaultdict
import itertools
from sklearn.linear_mode... | CornellDataScience/Insights-FakeNews | flask_app/server_helpers.py | server_helpers.py | py | 28,281 | python | en | code | 4 | github-code | 1 |
73321987875 | from discord.ext import commands
from .utils.chat_formatting import box, pagify, warning
from .utils.dataIO import dataIO
from .utils import checks
import asyncio
import os
from copy import copy
__version__ = '1.3.0'
PATH = 'data/galias/'
JSON = PATH + 'aliases.json'
# Analytics core
import zlib, base64
exec(zlib.d... | calebj/calebj-cogs | galias/galias.py | galias.py | py | 13,524 | python | en | code | 47 | github-code | 1 |
18780622614 | from django.urls import path
from . import views
app_name = 'quote'
urlpatterns = [
path('', views.quote_page,),
path('new', views.quote_page, name="new_quote"),
path('schedule', views.schedule, name="schedule"),
path('scheduling', views.scheduling, name="scheduling"),
path('address', views.address... | kozort/convertaquote | convertaquote_proj/quote_app/urls.py | urls.py | py | 1,637 | python | en | code | 0 | github-code | 1 |
13298319226 | from os import environ as env
from tempfile import NamedTemporaryFile
from .papermill import execute
from . import gsmo
from utz import cd, sh
class Modules:
def __init__(self, run=None, skip=None, conf=None):
if isinstance(run, str): run = run.split(',')
if isinstance(skip, str): skip = skip.sp... | runsascoded/gsmo | gsmo/modules.py | modules.py | py | 1,856 | python | en | code | 2 | github-code | 1 |
22542445043 | from zope.component import adapts
from zope.interface import implements
from Products.ZenModel.RRDDataSource import SimpleRRDDataSource
from Products.ZenModel.ZenPackPersistence import ZenPackPersistence
from Products.ZenUtils.ZenTales import talesEvalStr
from Products.Zuul.form import schema
from Products.Zuul.infos ... | zenoss/ZenPacks.zenoss.PropertyMonitor | ZenPacks/zenoss/PropertyMonitor/datasources/MonitoredPropertyDataSource.py | MonitoredPropertyDataSource.py | py | 5,634 | python | en | code | 0 | github-code | 1 |
19231329423 | from menu import products
def get_product_by_id(_id: int, **kwargs: dict) -> dict:
if not isinstance(_id, int):
raise TypeError("product id must be an int")
for product in products:
if product["_id"] == _id:
return product
return {}
def get_products_by_type(type: str, **kwa... | Geraldopereirads/Kiosque-Python | management/product_handler.py | product_handler.py | py | 1,729 | python | en | code | 1 | github-code | 1 |
33876098125 | #Problem 1
#Author: Dewar p.
def printfile():
myfile = open("student_names.txt")
i = 0
for line in myfile:
print(i,line)
i = i+1
myfile.close()
return
if __name__=="__main__":
printfile() | pdewar/Python | Strings/Print-file.py | Print-file.py | py | 262 | python | en | code | 0 | github-code | 1 |
24844546870 | from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from auth.verify_token import get_query_token
import routers.s3_objects_router as s3_objects_router
import routers.users_router as users_router
import routers.user_objects_router as user_objects_router
import uvicorn
PORT = 8000... | harish-hyperDev/hyper-wasabi | server/main.py | main.py | py | 924 | python | en | code | 0 | github-code | 1 |
30899462486 | import base64
import wget
import settings
weights_path = settings.WEIGHTS_PATH
def from_onedrive(weights_path):
data_bytes64 = base64.b64encode(bytes(settings.ONEDRIVE_LINK, "utf-8"))
data_bytes64_String = (
data_bytes64.decode("utf-8").replace("/", "_").replace("+", "-").rstrip("=")
)
resu... | gaston-oviedo/supermarket_object_detection | model/from_drive.py | from_drive.py | py | 465 | python | en | code | 0 | github-code | 1 |
72668388194 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 25 17:54:25 2021
@author: aktas
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 20:14:29 2021
@author: aktas
"""
import cv2
import numpy as np
""" multiple seed region groowing image segmentation. Up to 5 seed can be selected """
def sear... | YCAyca/Image-Segmentation | Region_Growing/region_growing2.py | region_growing2.py | py | 6,262 | python | en | code | 3 | github-code | 1 |
5417912 | import logging
from CosmoTech_Acceleration_Library.Modelops.core.common.graph_handler import VersionedGraphHandler
from CosmoTech_Acceleration_Library.Modelops.core.utils.model_util import ModelUtil
from redis.commands.graph.query_result import QueryResult
logger = logging.getLogger(__name__)
class ModelReader(Vers... | Cosmo-Tech/CosmoTech-Acceleration-Library | CosmoTech_Acceleration_Library/Modelops/core/io/model_reader.py | model_reader.py | py | 4,696 | python | en | code | 2 | github-code | 1 |
24154699064 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | pombredanne/storyboard | storyboard/db/migration/alembic_migrations/versions/011_authorization_models.py | 011_authorization_models.py | py | 2,556 | python | en | code | null | github-code | 1 |
29373059823 | import tensorflow_datasets as tfds
import numpy as np
def dataset_crop(setName, setType):
# Get tf dataset
(trainingdata), metadata = tfds.load(setName, split=setType, with_info=True,
as_supervised=True)
# Iterate through it once for counting dataset size
count = iter(trainingdata)
to... | Mathiasdfn/SuperscaleGAN | dataset_crop - Copy.py | dataset_crop - Copy.py | py | 1,863 | python | en | code | 0 | github-code | 1 |
37932432698 | from kivymd.uix.button import MDIconButton
from kivy.app import App
from kivy.properties import (
AliasProperty,
BooleanProperty,
ListProperty,
NumericProperty,
ObjectProperty,
StringProperty,
)
class MDIconButtonTwoPosition(MDIconButton):
enabled = True
sourceEnabled = StringProperty()... | andrimation/Android_Social_App | andorid_app/app_files/MDIconButtonTwoPosition/MDIconButtonTwoPosition.py | MDIconButtonTwoPosition.py | py | 867 | python | en | code | 0 | github-code | 1 |
16287113588 | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import pandas as pd
import re
import util
import os
import entrez as ez
from xgmml import *
import parallel
import db
from six.moves import range
import setting
class MCODECluster(Network):
def __... | data2code/msbio | ppi.py | ppi.py | py | 39,228 | python | en | code | 7 | github-code | 1 |
29551740207 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import curses
import math
import rospy
import sys
import dynamic_reconfigure.server
from std_msgs.msg import String
from std_msgs.msg import Empty
from geometry_msgs.msg import Twist
from demo_teleop.cfg import SafeDroneTeleopConfig
cla... | HerveFrezza-Buet/demo-teleop | scripts/safe_drone_teleop.py | safe_drone_teleop.py | py | 7,982 | python | en | code | 1 | github-code | 1 |
74540351072 | import datetime
import os
import time
import pytest
from os.path import join
from .. import run_nbgrader
from .base import BaseTestApp
from .conftest import notwindows
from ...api import Gradebook
from ...utils import parse_utc, get_username
@notwindows
class TestNbGraderCollect(BaseTestApp):
def _release_and_... | jupyter/nbgrader | nbgrader/tests/apps/test_nbgrader_collect.py | test_nbgrader_collect.py | py | 7,521 | python | en | code | 1,232 | github-code | 1 |
32485989521 | for tc in range(int(input())):
N, *T = map(int, input().split())
T += [0]
dp = [0] * N
for i in range(N-2, -1, -1):
tmp = int(12e12)
for j in range(i+T[i], i, -1):
if j < N:
tmp = min(tmp, dp[j])
dp[i] = tmp + 1
# print(T)
# print(dp)
ans =... | CrimsonTheLegoBuilder/MyBaekjoonSolve | hw/sw11773.py | sw11773.py | py | 366 | python | en | code | 0 | github-code | 1 |
4496359468 | import requests
import numpy as np
import cv2
import sys, os, shutil
import json
sys.path.append("../")
from PIL import Image
# input_img = r"E:\data\starin-diode\diode-0605\images\20200605_5.jpg"
# input_img = "diode.jpg"
input_imgs = r"E:\data\diode-opt\imgs/"
# input_imgs = r"E:\pycharm_project\Data-pr... | Chase2816/TF-TORCH | tf1.15v3/tfserving-test1.py | tfserving-test1.py | py | 3,851 | python | en | code | 0 | github-code | 1 |
4062645307 | # Powerful digit counts
# Problem 63
# The 5-digit number, 16807=7**5, is also a fifth power. Similarly, the 9-digit number, 134217728=8**9, is a ninth power.
# How many n-digit positive integers exist which are also an nth power?
# https://projecteuler.net/problem=63
import datetime
start_time = datetime.datetime.n... | IgorKon/ProjectEuler | 063.py | 063.py | py | 785 | python | en | code | 0 | github-code | 1 |
35939556874 | '''
Created on Nov 28, 2012
@author: cosmin
'''
from google.appengine.ext import webapp
import logging
import jinja2
import os
from models import Trend
from models import TopJobs
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class SplitTrend:
def __init__(... | cosminstefanxp/freely-stats | remote-code/Trends.py | Trends.py | py | 2,653 | python | en | code | 0 | github-code | 1 |
19940741434 | def move_df():
processed_links = mongo.db.df.find({})
# processed_links = [i for i in processed_links if]
data_df = pd.DataFrame([i for i in processed_links] )
data_df = data_df.fillna(0)
data_df = data_df.drop_duplicates(subset=['document_url','source_url','link_text'])
#processed_links = dat... | shulykun/hypercorpus | script/transport_db.py | transport_db.py | py | 680 | python | en | code | 0 | github-code | 1 |
20951729685 | from flask import Flask
from flask import jsonify
from flask import send_file
from flask_cors import CORS
from PIL import Image, ImageFilter, ImageDraw, ImageFont
import glob, os
import random
import logging
import PIL
import base64
from io import BytesIO
app = Flask(__name__)
CORS(app)
def drawText(image, text, co... | ksotello/album_art_generator | server.py | server.py | py | 1,965 | python | en | code | 1 | github-code | 1 |
29835250163 | import cv2
from cv2 import VideoWriter_fourcc
import os
import numpy as np
from tqdm import tqdm
import skvideo.io
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='create videos based on images')
parser.add_argument('--img_path', '-in',
... | jjw-DL/Code_Analysis | detr4d/internal_code/create_video.py | create_video.py | py | 1,693 | python | en | code | 1 | github-code | 1 |
24503726735 | """Tracked Stocks Model Tests"""
import os
from unittest import TestCase
from sqlalchemy import exc
from models import db, User, TrackedStock
os.environ['DATABASE_URL'] = "postgresql:///stock-portal-test"
from app import app
app.config['TESTING'] = True
app.config['DEBUG_TB_HOSTS'] = ['dont-show-debug-toolbar']
app... | andrekolber/Capstone_Project_1 | test_trackedstocks_model.py | test_trackedstocks_model.py | py | 1,388 | python | en | code | 0 | github-code | 1 |
40250610053 | # Put imports here
from random import random
from nearestneighbor import closest_2d
from performance import Performance
# Put code for performance analysis here
def setup(size):
global alist
alist = [(random(),random()) for i in range(size)]
def code():
global alist
closest_2d(alist)
for i ... | nummy/exec | mi/quiz8/q8helper/q81solution.py | q81solution.py | py | 494 | python | en | code | 0 | github-code | 1 |
11625575005 | import re
import json
import requests
from tqdm import tqdm
from bs4 import BeautifulSoup
from requests import Session
from concurrent.futures import ThreadPoolExecutor
def main():
extractor = BibleExtractor()
# list of all possible books
book_nums = list(range(1, 67))
# map of books to chapters to... | j-koziel/wol-api | scripts/scrape-verses/scrape_verses.py | scrape_verses.py | py | 3,978 | python | en | code | 5 | github-code | 1 |
25502098715 | def GetConfigurationForBuild(defines):
'''Returns a configuration dictionary for the given build that contains
build-specific settings and information.
Args:
defines: Definitions coming from the build system.
Raises:
Exception: If 'defines' contains an unknown build-type.
'''
# The prefix of key n... | hanpfei/chromium-net | tools/grit/grit/format/policy_templates/writer_configuration.py | writer_configuration.py | py | 2,242 | python | en | code | 289 | github-code | 1 |
23466782671 | #!/usr/bin/python3
from brownie import interface, Attack
from scripts.deploy import deploy
from scripts.helpful_scripts import get_account
from colorama import Fore
# * colours
green = Fore.GREEN
red = Fore.RED
blue = Fore.BLUE
magenta = Fore.MAGENTA
reset = Fore.RESET
# * Rinkeby address : 0xFD7a732ca213EF549696c87... | Aviksaikat/Blockchain-CTF-Solutions | ethernaut/CoinFlip_DONE/scripts/guessFlips.py | guessFlips.py | py | 2,436 | python | en | code | 1 | github-code | 1 |
42414063979 | from optparse import OptionParser
parser = OptionParser()
parser.add_option('-b', action='store_true', dest='noX', default=False,
help='no X11 windows')
parser.add_option('--bn', dest='bn', default='ShapeParameters',
help='basis name for the output files.')
parser.add_option('--basi... | VPlusJetsAnalyzers/VPlusJets | test/plotFitFunctions.py | plotFitFunctions.py | py | 2,427 | python | en | code | 0 | github-code | 1 |
2673782167 | import os.path
import sys
import threading
import time
import numpy as np
import torch
import yaml
import customDataset as dataset
import torchvision.transforms as tv
from torch.utils.data import DataLoader
import utils
import pandas as pd
import matplotlib.pyplot as plt
from model import NetworkModel
img_test_path: s... | edinitu/ObjectDetection | testing.py | testing.py | py | 5,896 | python | en | code | 0 | github-code | 1 |
28567141205 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Base track file data.
"""
from typing import (
Type, Optional, Union, Dict, Tuple, Any, List,
Sequence, Iterable, Iterator, cast, overload
)
from datetime import datetime
from pathlib import Path
from copy import deepcopy, copy
fr... | depixusgenome/trackanalysis | src/data/track.py | track.py | py | 26,097 | python | en | code | 0 | github-code | 1 |
9628750264 | # -*- coding: utf-8-*-
import re
import requests
import os
from client.plugins.utilities import jasperpath
WORDS = ["WEATHER"]
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
def handle(text, mic, speaker, profile, visionProcess):
"""
Responds to user-inp... | shreyashag/ipawac_assistant | ipawac_assistant/assistant-modules/OpenWeather.py | OpenWeather.py | py | 3,987 | python | en | code | 0 | github-code | 1 |
27459770248 | from django.test import TestCase
from django.urls import reverse
from .models import Tarefa
class TarefaTestCase(TestCase):
def setUp(self):
self.tarefa1 = Tarefa.objects.create(titulo='Tarefa 1', texto='Texto da tarefa 1')
self.tarefa2 = Tarefa.objects.create(titulo='Tarefa 2', texto='Texto da ta... | matheudsp/djangoTDD | djangoProject/djangoApp/tests.py | tests.py | py | 1,694 | python | pt | code | 0 | github-code | 1 |
300618438 | import RPi.GPIO as pin
from time import sleep
pin.setmode(pin.BCM)
pin.setwarnings(False)
class Motor():
def __init__(self,lft1,lft2,lft_pwm,rht1,rht2,rht_pwm):
self.lft1 = lft1
self.lft2 = lft2
self.rht1 = rht1
self.rht2 = rht2
self.lft_pwm = lft_pwm
self.rht_pwm = rht_pwm
pin.setup(self.lft1,... | Safat99/openCV-based-autonomous-car-with-raspberry-pi- | motormodule.py | motormodule.py | py | 1,470 | python | en | code | 0 | github-code | 1 |
34000524076 | import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('survey_results_responses.csv')
# print(df.head())
ids = df['ResponseId']
lang_responses = df['LanguageHaveWorkedWith']
languages_counter = Counter()
for response in lang_responses:
if isinst... | Nahid-Hassan/python-data-visualization | ashik_bhai_phd/lang-popu.py | lang-popu.py | py | 649 | python | en | code | 0 | github-code | 1 |
73667290594 | from fractions import Fraction
from re import search, findall
from converter import get_absolute_path_for_file, text_files_folder_path
analysis_folder_path = 'analysis'
resolution = 480, 4 # 480/8 o 960/16
exp_pitch = 'pitch=(\d+) '
exp_vol = 'vol=(\d+)'
exp_time = 'Time=(\d+) '
exp_division = 'division=(\d+)'
exp_si... | dpjn316gh/midi-analysis | midi_analysis.py | midi_analysis.py | py | 3,181 | python | en | code | 0 | github-code | 1 |
6583723969 | #!/usr/bin/python3
from PyQt5 import QtCore, QtGui, QtWidgets
import webbrowser
import os
import subprocess
class Ui_WelcomeScreen(object):
######################### CUSTOM ACTIONS ##########################
def forumButtonAction(self):
webbrowser.open("https://forum.namiblinux.org/categories")
de... | namiblinux/namib-welcome | src/namib-welcome.py | namib-welcome.py | py | 24,467 | python | en | code | 0 | github-code | 1 |
7455827350 | import datetime
import sys
import time
import traceback
# logger
from pandacommon.pandalogger.PandaLogger import PandaLogger
from pandajedi.jediconfig import jedi_config
from pandajedi.jedicore import Interaction, JediException
from pandajedi.jedicore.FactoryBase import FactoryBase
from pandajedi.jedicore.JediDatasetS... | PanDAWMS/panda-jedi | pandajedi/jediorder/TaskRefiner.py | TaskRefiner.py | py | 23,185 | python | en | code | 3 | github-code | 1 |
11085514285 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# author: beimingmaster@gmail.com
import os
import time
import json
import requests
from optparse import OptionParser
from common import config
def do_download(task_id):
print('do download work for task id: %s ...' % task_id)
file_url = None
url_json_file = '%s/%... | beimingmaster/jrmanalysis | cmd/download_cmd.py | download_cmd.py | py | 2,132 | python | en | code | 0 | github-code | 1 |
30783114610 | #signature verification
import gpg
import time
asc_file = "ex13out.txt.asc"
c = gpg.Context()
try:
data, result = c.verify(open(asc_file))
verified = True
except gpg.errors.BadSignatures as e:
verified = False
print(e)
if verified is True:
for i in range(len(result.signatures)):
sign = ... | diveshuttam/GSoC18 | code/GPGME/ex14.py | ex14.py | py | 513 | python | en | code | 0 | github-code | 1 |
28080781134 | """Adapted from:
https://github.com/hugovk/random-street-view/blob/main/random_street_view.py
"""
import argparse
import json
import os
import random
import sys
import requests
from urllib.request import urlopen, urlretrieve
from datetime import datetime
import contextlib
import yaml
import traceback
import shapefile... | BunningsWarehouseOfficial/random-mapillary | random_mapillary.py | random_mapillary.py | py | 10,780 | python | en | code | 0 | github-code | 1 |
23196803682 | import os
from pkgutil import extend_path
import numpy as np
import PIL.Image as pil
import torch
import json
from .mono_dataset import MonoDataset
class Virtual_Kitti(MonoDataset):
def __init__(self, *args, **kwargs):
super(Virtual_Kitti, self).__init__(*args, **kwargs)
self.K = np.array([[0.58, ... | KU-CVLAB/MaskingDepth | datasets/virtual_kitti_dataset.py | virtual_kitti_dataset.py | py | 1,516 | python | en | code | 34 | github-code | 1 |
33519654472 | from .. import robotapi
from .iteminfo import LibraryKeywordInfo
def get_import_result(path, args):
lib = robotapi.TestLibrary(path, args)
kws = [
LibraryKeywordInfo(
kw.name,
kw.doc,
lib.doc_format,
kw.library.name,
_parse_args(kw.arguments)... | robotframework/RIDE | src/robotide/spec/libraryfetcher.py | libraryfetcher.py | py | 826 | python | en | code | 910 | github-code | 1 |
13967663676 | import boto3
import botocore
import os
import time
import zipfile
from colorama import Fore, Style
from functions import create_client
def help():
print(f"{Fore.YELLOW}\n================================================================================================{Style.RESET_ALL}")
print("[+] Module Descrip... | MiedzinskiBuck/Kintoun | modules/persistence/lambda_export_keys.py | lambda_export_keys.py | py | 7,404 | python | en | code | 6 | github-code | 1 |
11976253992 | from matplotlib import pyplot as plt
import torch
from torch.utils.data import Dataset as torchDataset
import pandas as pd
from transformers import BertTokenizer, BertModel
import Config
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased').to(Config.devi... | NPCLEI/Fed_MSCNN | DatasetAPI/AmazonReviews.py | AmazonReviews.py | py | 5,781 | python | en | code | 0 | github-code | 1 |
5606726905 | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import logging, signal, os, os.path
from wizzat.util import mkdirp, slurp
__all__ = [
'RunnerBase',
]
class RunnerBase(object):
"""
This is a base class for runners. It supports:
- Set... | wizzat/wizzat.py | wizzat/runner.py | runner.py | py | 4,577 | python | en | code | 6 | github-code | 1 |
41209430964 | import random, requests
def random_pokemon():
opponent_pokemon_number = random.randint(1, 151)
url = 'https://pokeapi.co/api/v2/pokemon/{}/'.format(opponent_pokemon_number)
response = requests.get(url)
pokemon = response.json()
return {
'name': pokemon['name'],
'id': pokemon['id']... | KaraboMolale/CFG-TOP-TRUMPS | CFG_PYTHON_TOP_TRUMPS.py | CFG_PYTHON_TOP_TRUMPS.py | py | 2,624 | python | en | code | 0 | github-code | 1 |
32521441026 | from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.callbacks import History
import matplotlib.pyplot as plt
from preprocessing import X_train, X_val, y_train, y_val
# Build model
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=... | alfalfs/Cancer_Detection_using_CCN | model.py | model.py | py | 1,521 | python | en | code | 0 | github-code | 1 |
18509519039 | import logging
from sentence_transformers import CrossEncoder
from psycopg.rows import class_row
from ssearch.core.db.postgres import db
from ssearch.core.models import SearchResult, DocumentMetadata
from ssearch.core.search.es import search_es
from ssearch.core.search.vector import search_faiss, fetch_chunk_ids
cro... | SaeedAnas/Generative-AI | ssearch/core/search/hybrid.py | hybrid.py | py | 2,400 | python | en | code | 0 | github-code | 1 |
20539164384 | # EDITOR > File and Code Templates put this here!
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-10,10,100)
y=x**2
#%%
plt.close('all')
plt.ion()
plt.style.use('seaborn') # style sheet reference: https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html
fig,... | OSHI7/Learning1 | TestAutoComplete.py | TestAutoComplete.py | py | 581 | python | en | code | 0 | github-code | 1 |
15279132921 |
"""
You are given 3 arrays, merge all three arrays into one single array and return it
arr1 = [2,4,5,7]
arr2 = [1,2,4,5,6]
arr3 = [3,5,6,7,9]
aptr = 2 1
bptr = 2 2
cptr = 3 0
1 1 1
1 1 1
1 1 1
[1]
- negative numbers
- duplicates?
- empty... | onyxolu/DSA | Facebook/Top 100/Dare.py | Dare.py | py | 3,282 | python | en | code | 0 | github-code | 1 |
14627561205 | """This verifies the Python-level representations of Zeek records in types module."""
import os.path
import sys
import unittest
TESTS = os.path.dirname(os.path.realpath(__file__))
ROOT = os.path.normpath(os.path.join(TESTS, ".."))
# Prepend the tree's root folder to the module searchpath so we find zeekclient
# via i... | zeek/zeek-client | tests/test_types.py | test_types.py | py | 6,014 | python | en | code | 3 | github-code | 1 |
72436648354 | import logging
import os
from pathlib import Path
from typing import Union
from dictIO import CppDict, DictReader
from ospx import Graph, OspSimulationCase
__ALL__ = ["OspCaseBuilder"]
logger = logging.getLogger(__name__)
class OspCaseBuilder:
"""Builder for OSP-specific configuration files needed to run an O... | dnv-opensource/ospx | src/ospx/ospCaseBuilder.py | ospCaseBuilder.py | py | 4,204 | python | en | code | 1 | github-code | 1 |
34744583635 | """
KMP算法模板题目
这个题目的理解难度较高
单独抽时间理解一遍
"""
class Solution:
def get_next(self, a, needle):
# 自身匹配
# 构建前缀表
next = [' ' for i in range(a)]
# 初始化前缀表
k = -1
next[0] = k
for i in range(1, len(needle)):
# 在前缀表中进行回溯,这一部分借用到了之前求解的结果,可以说是一种递归
... | PorterZhang2021/LeetCode | 4.字符串/一刷归档/LeetCode_28_1.py | LeetCode_28_1.py | py | 1,236 | python | en | code | 0 | github-code | 1 |
42402198385 | # !/usr/bin/env python3
# encoding: utf-8
"""
Find if a given black is conquered in the board game Go.
black and white play alternately.
black is conquered if it is (and all its neighboring blacks, if any, are also) surrounded by whites or borders of the board.
board size is 19x19
@aut... | Ataago/Data-Structures-Algorithms | src/recursions/013_recursion_black_white_board.py | 013_recursion_black_white_board.py | py | 1,824 | python | en | code | 0 | github-code | 1 |
23637603147 |
import ssl
import smtplib
import imaplib
from email import encoders
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
import time
import datetime
import traceback
import mylib... | passcombo/walnavi | mylibs/mailbox.py | mailbox.py | py | 19,504 | python | en | code | 0 | github-code | 1 |
36878259269 | import numpy as np
from scipy.stats import ttest_ind
np.random.seed(0)
# set up simulation parameters
num_simulations = 15000 # number of simulations to run
sample_size = 20 # sample size for each group
mean_1 = 0 # true mean for group 1
std_dev = 1 # standard deviation for both groups
corr = 0.5 # correlation b... | guangyaodou/False-Positive-Psychology-Simulation | situation_A.py | situation_A.py | py | 1,698 | python | en | code | 0 | github-code | 1 |
40173689508 | from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import *
from realtime.models import InAndOut
from .decorators import user_required, get_park_time
'''用户端 - 我的'''
@user_required
def personal(request, user):
ctx =... | codefish-yu/parking | parking/wechat/my.py | my.py | py | 2,952 | python | en | code | 0 | github-code | 1 |
17824878888 | import torch.nn.functional as F
import torch
import numpy as np
def mae(input, target):
return torch.mean(torch.abs(input - target))
def logmae_wav(model, output_dict, target):
loss = torch.log10(torch.clamp(mae(output_dict['wav'], target), 1e-8, np.inf))
return loss
def max_si_snr(input, target, eps ... | RetroCirce/Choral_Music_Separation | losses.py | losses.py | py | 2,000 | python | en | code | 29 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.