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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
63614571 | import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt # for making figures
import os
# read in all the words
current_dir = os.getcwd()
words = open(current_dir+'/makemore/names.txt', 'r').read().splitlines()
# print(f"{words[:8]}")
# build the vocabulary of characters and mappings to/from integ... | code-cp/bitesize_ai_rs | makemore/scripts/mlp.py | mlp.py | py | 2,642 | python | en | code | 2 | github-code | 6 |
22795567170 | import urllib2
import sys
user=sys.argv[1]
url='http://noaddress.x10.mx/chat/'
url+= user
url+=".txt"
response = urllib2.urlopen(url).read()
response=response[4:]
#RSA
def split(txt, seps):
default_sep = seps[0]
for sep in seps[1:]: # we skip seps[0] because that's the default seperator
txt = txt.repl... | noaddress/securemessenger | client/0.0-TheBeginnings/read.py | read.py | py | 491 | python | en | code | 0 | github-code | 6 |
4034606024 | import argparse
import glob
import multiprocessing as mp
import os
import shutil
import time
import cv2
import tqdm
import numpy as np
from detectron2.config import get_cfg
from partseg import add_partseg_config
from detectron2.data.detection_utils import read_image
from detectron2.utils.logger import setup_logger
fr... | hansongfang/CompNet | PartSeg/predict_net.py | predict_net.py | py | 5,233 | python | en | code | 33 | github-code | 6 |
38453799002 | T = int(input())
for i in range(1,T+1):
L = list(map(int,input().split()))
L.sort()
a,b,c = L
type = ""
if a+b <= c:
type = "invalid!"
elif a == b and b == c:
type = "equilateral"
elif a == b or b == c:
type = "isosceles"
else:
type = "scalene"
prin... | LightPotato99/baekjoon | math/geometry/triangle/triClassify.py | triClassify.py | py | 345 | python | en | code | 0 | github-code | 6 |
72602309309 | import sys
n1 = sys.stdin.readline()
n, m = n1.split(" ")
n = int(n)
m = int(m)
matrix=[]
for i in range(n):
n1 = sys.stdin.readline()
row =[]
for j in n1.strip():
row.append(int(j))
matrix.append(row)
def DFS(x,y,k,maze):
row = len(maze)
col = len(maze[0])
if k==0:
res.a... | CountyRipper/offer_py | mt2.py | mt2.py | py | 974 | python | en | code | 0 | github-code | 6 |
23013301215 | '''
The purpose of this python script is to produce a program, that when run, will provide two input options:
1. File path
2. Type of directory
One inputted, the program will create a directory with sub folders for data requests.
The best package to use may be Tkinter.
'''
from tkinter import *
from tkinter.ttk import... | jfkocher/Python_Code | Data Request/Batch_v3/main.py | main.py | py | 1,989 | python | en | code | 0 | github-code | 6 |
31153800734 | import pygame
import random
import numpy as np
class Explosion(pygame.sprite.Sprite):
def __init__(self, frames, xcoord, ycoord, scale=1.5, update_n=1):
pygame.sprite.Sprite.__init__(self) # call Sprite initializer
self.frame = 0
self.frames = frames
self.image = self.frames[self.... | Hiimbawb/Spacey | Spacey.py | Spacey.py | py | 32,449 | python | en | code | 0 | github-code | 6 |
22284911130 | # ---------------------------------------------------
#
# 필수 import 파일임:
# scripts 폴더의 스크립트들이 서로 import하기 위해서는
# scripts 폴더를 pythonpath에 등록해야한다.
#
# ---------------------------------------------------
import os
dirpath = os.path.dirname(os.path.realpath(__file__))
dirpath = dirpath + "\\scripts"
print('Using modif... | crack-love/KSL | Project_DNN/PYTHONPATH.py | PYTHONPATH.py | py | 447 | python | ko | code | 0 | github-code | 6 |
24013809061 | from QLearning import Game
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt
gamma = 0.1
def Menu():
usr_op = None
while usr_op != 0:
print('//-//-//-// Card-Jitsu Menu //-//-//-//')
print('\nSelect an option to continue: ')
print('1. Play game vs AI.'... | Marinovsky/Card-Jitsu | metrics_modifications/game.py | game.py | py | 3,225 | python | en | code | 0 | github-code | 6 |
73817284346 | """Basic status commands to check the health of the bot."""
import datetime
import discord
from discord.ext import commands
from metricity.config import BotConfig
DESCRIPTIONS = (
"Command processing time",
"Last event received",
"Discord API latency",
)
ROUND_LATENCY = 3
INTRO_MESSAGE = "Hello, I'm {nam... | python-discord/metricity | metricity/exts/status.py | status.py | py | 1,958 | python | en | code | 39 | github-code | 6 |
36347921741 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pyredatam
Tests for `pyredatam` module.
"""
from __future__ import unicode_literals
import unittest
import nose
import pyredatam
import queries
class RedatamTestCase(unittest.TestCase):
def test_arealist_query(self):
# Test case AREALIST1
... | abenassi/pyredatam | tests/test_pyredatam.py | test_pyredatam.py | py | 3,362 | python | en | code | 4 | github-code | 6 |
11579227616 | import cv2
import numpy as np
from imageclassifier import ImageClassifier
n_clusters = [3, 4, 5, 6, 7, 8]
kmeans_keys = [
[0], [1], [2],
[0, 1], [0, 2], [1, 2],
[0, 1, 2]
]
sorting_lambdas = [
lambda pixel: pixel[0],
lambda pixel: pixel[1],
lambda pixel: pixel[2],
lambda pixel: sum(pixe... | elraffray/pyImage | classifier.py | classifier.py | py | 4,167 | python | en | code | 0 | github-code | 6 |
10527381076 | '''
7. Reverse Integer
https://leetcode.com/problems/reverse-integer/description/
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit... | bhaveshratan/LeetCode-Programming-Solutions-in-Python | Reverse Integer.py | Reverse Integer.py | py | 799 | python | en | code | 0 | github-code | 6 |
75316082746 | import os
import wx
from wx.lib.colourchooser.canvas import Canvas
class ImageCanvas(wx.Panel):
"""
Image Panel
"""
def __init__(self, parent, image_path=None, *args, **kwargs):
"""
Constructor
:param parent:
"""
wx.Panel.__init__(self, parent=parent, *args, ... | JoenyBui/boa-gui | boaui/panel/image.py | image.py | py | 4,085 | python | en | code | 0 | github-code | 6 |
1002491820 | import unittest
from zag import *
from zag.configable import ConfigException
class ConfigTest(unittest.TestCase):
def test_stage(self):
foo = PyTask("zag.foo")
workflow = Sequence("foo-flow", stages=[
Stage("run-foo",
foo,
args=[
("... | Refefer/zag | tests/test_zag.py | test_zag.py | py | 3,411 | python | en | code | 1 | github-code | 6 |
9357540363 | #!/usr/bin/env python
__author__ = 'j5wagner@ucsd.edu'
import commands
from d3r.celppade.custom_protein_prep import ProteinPrep
class chimera_dockprep(ProteinPrep):
"""Abstract class defining methods for a custom docking solution
for CELPP
"""
ProteinPrep.OUTPUT_PROTEIN_SUFFIX = '.mol2'
... | drugdata/tutorial_rdock_implementation | tutorial_rdock_implementation/tutorial_rdock_implementation_protein_prep.py | tutorial_rdock_implementation_protein_prep.py | py | 3,827 | python | en | code | 0 | github-code | 6 |
29191289762 | import datetime
import json
import os
import re
import shutil
class Fileop():
def isDirectory(self, fDir):
return os.path.isdir(fDir)
def countDir(self, dPath):
dirListing = next(os.walk(dPath))[2]
return len(dirListing)
def CjsonLoad(self, jfile):
fdir = os.path.join(Fil... | kkweli/Avaya | Avy/avayaFile.py | avayaFile.py | py | 4,353 | python | en | code | 0 | github-code | 6 |
72143866108 |
from typing import Any, Dict
def play_game() -> None:
print('playing game')
def update_state(current_state: Dict) -> Dict:
print('here we change things')
possible_actions = {
'mod status': lambda : print('modifting status'),
'remove status': lambda : print('removing status'),
... | levensworth/udesa-pc-tutorial | 2022-a/4-testing_and_train/solutions/example_command.py | example_command.py | py | 1,096 | python | en | code | 2 | github-code | 6 |
11353167972 | # Licensed under a 3-clause BSD style license - see LICENSE
from __future__ import print_function, division
from astropy.table import Table, Column
from .import_modules import *
##----- ----- ----- ----- ----- ----- ----- ----- ----- -----##
## Miscellaneous utilities
## Contain functions that do not pertain to a p... | bretonr/Icarus | Icarus/Utils/Misc.py | Misc.py | py | 3,104 | python | en | code | 11 | github-code | 6 |
3508041211 | #!/usr/bin/env python3
import numpy as np
import re
position_re = re.compile('(\d+),(\d+).*?(\d+),(\d+)')
def execute(cmd: str, a: np.array, a2: np.array):
items = position_re.search(cmd)
pos1 = (int(items.group(1)), int(items.group(2)))
pos2 = (int(items.group(3)) + 1, int(items.group(4)) + 1)
if ... | pboettch/advent-of-code | 2015/6.py | 6.py | py | 987 | python | en | code | 1 | github-code | 6 |
16325116494 | from functools import wraps
from typing import Callable
from util.threading import Thread, TimeoutException
from util.typing import P
from .AbstractHandler import PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE, AbstractHandler
class AbstractTimeoutHandler(AbstractHandler[PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE]):
... | MysteriousChallenger/nat-holepunch | protocol/interface/request_handler/AbstractTimeoutHandler.py | AbstractTimeoutHandler.py | py | 1,804 | python | en | code | 0 | github-code | 6 |
37502345925 | import numpy as np
from typing import Callable, Dict, List, Optional, Tuple, Union
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_
from torch.cuda.amp import autocast
from detectr... | zfonemore/NewVIS | minvis/share_mask_fpn.py | share_mask_fpn.py | py | 10,597 | python | en | code | 0 | github-code | 6 |
21228252116 | from django.urls import path
from widgets.views import HomePageView, UserProfilePageView, SharedWidgetsPageView, \
PrivateWidgetsPageView, MemoryWidgetsView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('home/shared-widgets/', SharedWidgetsPageView.as_view(), name='shared-widgets'),
... | alex-polo/homepage | widgets/urls.py | urls.py | py | 607 | python | en | code | 0 | github-code | 6 |
856153134 | from setuptools import setup
import sys
VERSION = '1.2.1263'
plist = dict(
CFBundleName='VisTrails',
CFBundleShortVersionString=VERSION,
CFBundleGetInfoString=' '.join(['VisTrails', VERSION]),
CFBundleExecutable='vistrails',
CFBundleIdentifier='edu.utah.sci.vistrails',
)
sys.path.append('../..')
... | VisTrails/VisTrails | scripts/dist/mac/setup_itk.py | setup_itk.py | py | 1,027 | python | en | code | 100 | github-code | 6 |
32612633515 | # Реализовать базовый класс Worker (работник), в котором определить атрибуты:
# name, surname, position (должность), income (доход). Последний атрибут должен быть защищенным и
# ссылаться на словарь, содержащий элементы: оклад и премия, например, {"wage": wage, "bonus": bonus}.
# Создать класс Position (должность) на б... | Unst1k/GeekBrains-PythonCourse | DZ6/DZ6-3.py | DZ6-3.py | py | 2,365 | python | ru | code | 1 | github-code | 6 |
43242415991 | from os.path import abspath, dirname, join
from preggy import expect
from tornado.testing import gen_test
from tests.base import TestCase
from thumbor.compatibility.storage import Storage
from thumbor.config import Config
from thumbor.context import Context, ServerParameters
from thumbor.importer import Importer
STO... | thumbor/thumbor | tests/compatibility/test_compatibility_storage.py | test_compatibility_storage.py | py | 4,916 | python | en | code | 9,707 | github-code | 6 |
72784516667 | # https://www.codewars.com/kata/58fd9f6213b00172ce0000c9
def split_exp(n):
lenn = len(n)
res = []
pnt = n.find('.')
if pnt < 0:
res = [c + '0'*(lenn-i-1) for i, c in enumerate(n) if c != '0']
else:
for i,j in zip(range(0, pnt), range(pnt-1,-1,-1)):
if n[i]!= '0': res.ap... | blzzua/codewars | 7-kyu/simple_fun_205_split_exp.py | simple_fun_205_split_exp.py | py | 470 | python | en | code | 0 | github-code | 6 |
24615537845 | # Layers are stacked in order of drawing
level_0 = {
'tiles_sheet_path': '../imgs/terrain/mario_terrain.png',
'layers': {
'terrain': {
'path': '../levels/level_data/0/level0_Level.csv',
'type': 'static',
},
'ghost_passage': {
'path': '../levels/level_d... | ysbrandB/M6FinalProject | code/game_data.py | game_data.py | py | 3,637 | python | en | code | 0 | github-code | 6 |
71066866429 | from ....utils.onlinetex import tex_to_svg_file_online
from ....utils.jupyter import video
from ..scene import SceneGL
from ..config import Size
from .plot import Plot
from .scatter import Scatter
from pathlib import Path
import re
import time
import shutil
from manimlib import (
BLUE,
GREEN,
ShowCreation,... | beidongjiedeguang/manim-express | manim_express/backend/manimgl/express/eager.py | eager.py | py | 10,559 | python | en | code | 13 | github-code | 6 |
6969799516 | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
from torch import Tensor
from torch.jit.annotations import List
#added
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from load_utils... | ada-shen/icCNN | densenet_ori_train.py | densenet_ori_train.py | py | 20,335 | python | en | code | 18 | github-code | 6 |
73789760509 | def leiaint(msg):
while True:
try:
i = int(input(msg))
except KeyboardInterrupt:
print('entrada de dados interrompida pelo usuario.')
break
except (ValueError, TypeError):
print(f'\033[0;31m ERRO! digite um numero valido \033[m')
co... | Kaue-Marin/Curso-Python | pacote dowlond/curso python/exercicio113.py | exercicio113.py | py | 697 | python | pt | code | 0 | github-code | 6 |
10422172533 | from __future__ import annotations
from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt
from PySide6.QtWidgets import QLayout, QSizePolicy, QWidgetItem
class FlowLayout(QLayout):
def __init__(self, parent=None, center=False):
super().__init__(parent)
if parent is not None:
s... | randovania/randovania | randovania/gui/lib/flow_layout.py | flow_layout.py | py | 3,663 | python | en | code | 165 | github-code | 6 |
73008021309 | #Lesson / Exercise 23 my code, sort the customer total amount
from pyspark import SparkConf, SparkContext #boilerplate
conf = SparkConf().setMaster("local").setAppName("TotalAmountOrdered")
sc = SparkContext(conf = conf)
def parseLine(line):
fields = line.split(',')
return (int(fields[0]), float(fields[2])... | CenzOh/Python_Spark | MyCode/customerTotalAmountSorted.py | customerTotalAmountSorted.py | py | 1,078 | python | en | code | 0 | github-code | 6 |
29954994164 | from __future__ import print_function
import re
import bitarray
def filterFeatures(sr_obj, feature_types=None, qualifier_regexs=None):
"""Filter a `SeqRecord` object's `SeqFeature` list by type and qualifiers.
Args:
sr_obj (``SeqRecord``) : instantiated Biopython
... | Wyss/mascpcr | mascpcr/genbankfeatures.py | genbankfeatures.py | py | 7,725 | python | en | code | 2 | github-code | 6 |
41439897989 | from django.test import TestCase
from django.urls.base import reverse
from .models import Provinces
# Create your tests here.
class ProvincesModelTests(TestCase):
def test_get_one_province(self):
"""if not province exist with passed id, return appropiate message"""
province = Provinces.objects.cre... | matiasfeliu92/crud_provincias | server/provinciasCrud/tests.py | tests.py | py | 1,119 | python | en | code | 1 | github-code | 6 |
24199771377 | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 16:32:39 2019
@author: Administrator
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = {}
for i in strs:
key = tuple(sorted(i))
if key not in d.keys():
d[key] = [i]
... | AiZhanghan/Leetcode | code/49. Group Anagrams.py | 49. Group Anagrams.py | py | 403 | python | en | code | 0 | github-code | 6 |
42126550080 |
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name, " and age:", self.age)
class laptop:
def __init__(self, brand, ram):
self.brand = brand
self.ram = ram
... | Robinrrr10/python | src/innerClass.py | innerClass.py | py | 597 | python | en | code | 0 | github-code | 6 |
34221019372 | """
UP42 authentication mechanism and base requests functionality
"""
import json
from pathlib import Path
from typing import Dict, List, Optional, Union
import requests
import requests.exceptions
from tenacity import (
Retrying,
wait_fixed,
wait_random_exponential,
stop_after_attempt,
retry_if_exc... | stasSajinDD/up42-py | up42/auth.py | auth.py | py | 10,421 | python | en | code | null | github-code | 6 |
5243707290 | #!/usr/bin/env python3
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
NUMBER_OF_WORDS = 50
file_path = sys.argv[1]
lines = pd.read_table(file_path, header=None, delim_whitespace=True)
lines = lines.sample(NUMBER_OF_WORDS).reset_index(drop=Tru... | data-science-and-big-data-analytics/data-science-frameworks | FastText/evaluation.py | evaluation.py | py | 819 | python | en | code | 2 | github-code | 6 |
32169695426 | import requests
from .models import Item
import datetime
from django.utils.timezone import make_aware
def fetch_items():
conn = requests.get('https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty')
res = sorted(conn.json())
return list(reversed(res))[:5] # top 5 stories
def fetch_item_by_id(i... | Alisjj/HackerNews | newsList/fetcher.py | fetcher.py | py | 2,008 | python | en | code | 0 | github-code | 6 |
35241998177 | from flask import Flask
#from flask_cors import CORS, cross_origin
from pymongo import MongoClient
connection = MongoClient("mongodb://localhost:27017/")
def create_mongodatabase():
try:
dbnames = connection.database_names()
if 'cloud_native' not in dbnames:
db = connection.cloud_nativ... | AnatolyS1/Cloud-Native-Python | app.py | app.py | py | 8,921 | python | en | code | 0 | github-code | 6 |
21365592875 | from __future__ import print_function
import sys
import os
from os.path import exists, dirname
import numpy as np
import pickle
import json
import time
import six
if six.PY3:
import _thread as thread
from queue import Queue
else:
import thread
from Queue import Queue
from collections import OrderedDict
... | liyishuilys/SMPT | src/utils.py | utils.py | py | 7,884 | python | en | code | 0 | github-code | 6 |
31344968208 | from tkinter import *
import tkinter, threading
from tkinter import messagebox as tmsg
from tkinter import ttk
import random
import datetime
import imageio
import time
from PIL import Image, ImageTk
import smtplib as s
import config
root1 = Tk()
root1.geometry("1208x830")
root1.wm_iconbitmap("Artboard 1.... | zuwanish/Tour-Management-System | MAIN PROJECT GUI BASED.py | MAIN PROJECT GUI BASED.py | py | 30,680 | python | en | code | 0 | github-code | 6 |
71344208509 | import turtle as turtle
# Set up game screen
turtle.title("Pong game")
turtle.setup(400, 300)
turtle.bgcolor("lightblue")
welcome = turtle.Turtle()
welcome.color("black")
welcome.write("Welcome", align='center', font=("Arial", 40, "bold"))
p1 = input("Enter player1 name: ")
p2 = input("Enter player2 name: ")
welco... | SoumyadeepBera0230b/Pong_Game.github.io | pong.py | pong.py | py | 4,418 | python | en | code | 0 | github-code | 6 |
26425792111 | import pandas as pd
import optuna
import numpy as np
from pathlib import Path
import datetime
import lightgbm
import pickle
from functools import partial
import logging
import argparse
from clearml import Task
WORK_DIR = Path(".")
STUDY_PATH = WORK_DIR.joinpath(
f'total_dataset_study_{datetime.datetime.now().strft... | Anaksibia/Ticket_distribution_system | scripts/run_optuna_5_dates.py | run_optuna_5_dates.py | py | 13,803 | python | en | code | 0 | github-code | 6 |
10719490049 | import sys
import pathlib
import generator_func
import generator_logging
from datetime import datetime
from PyQt6.QtCore import QRunnable, QThreadPool, QDateTime, QSettings
from PyQt6.QtWidgets import (QApplication,
QDateTimeEdit,
QLabel,
... | Steelglowhawk/updateTool | generator_gui.py | generator_gui.py | py | 10,348 | python | ru | code | 1 | github-code | 6 |
2621863867 | ''' The elif clause executes if age < 12 is True and name == 'Alice' is False.
However, if both of the conditions are False,
then both of the clauses are skipped.
It is not guaranteed that at least one of the clauses will be executed.
When there is a chain of elif statements,
only one or none of the clauses will be... | ladamsperez/python_excercises | automatetheboringstuff/vampire.py | vampire.py | py | 718 | python | en | code | 0 | github-code | 6 |
24531644863 |
import os
import json
import random as rd
from copy import deepcopy
from matplotlib.pylab import *
import math
import torch
import torchvision.datasets as dsets
import torch.nn as nn
import torch.nn.functional as F
# import torch_xla
# import torch_xla.core.xla_model as xm
device = torch.device("cud... | DebadityaPal/RoBERTa-NL2SQL | seq2sql_model_internal_functions.py | seq2sql_model_internal_functions.py | py | 11,929 | python | en | code | 17 | github-code | 6 |
42929566304 | class Solution:
def decodeString(self, str):
num, stack, i = 0, [""], 0
while i < len(str):
if str[i].isdigit():
num = num*10 + int(str[i])
elif str[i] == "[":
stack.append(num)
num = 0
stack.append("")
... | shwetakumari14/Leetcode-Solutions | Miscellaneous/Python/394. Decode String.py | 394. Decode String.py | py | 702 | python | en | code | 0 | github-code | 6 |
75316085946 | import wx
import os
from .smart import SmartCheckBox, SmartInputLayout
__author__ = 'Joeny'
class CheckboxInputLayout(SmartInputLayout):
"""
Checkbox Input Layout
"""
def __init__(self, parent, checkbox=None, layout=None, *args, **kwargs):
label = None
if checkbox:
label... | JoenyBui/boa-gui | boaui/textbox/checkbox.py | checkbox.py | py | 675 | python | en | code | 0 | github-code | 6 |
33559300888 | #Declarar Varibles
contador = int ()
suma = int ()
#Limpiar/Inicializar Variables
contador = 0
suma = 0
#Asignar Valores a las variables
contador = 1
while (contador <= 10):
suma = suma + contador
contador = contador + 1
print("El resultado de la suma de estos numeros es: ", suma)
| renzovarela9/Proyectos-Propios | PYTHON/PROBANDO UNA SUMA CON WHILE.py | PROBANDO UNA SUMA CON WHILE.py | py | 302 | python | es | code | 0 | github-code | 6 |
29942141352 | import functools
import typing as tp
import shapely.geometry
import torch
import torchmetrics
from torch.nn.utils.rnn import PackedSequence
def _multiarange(counts: torch.Tensor) -> torch.Tensor:
"""Returns a sequence of aranges concatenated along the first dimension.
>>> counts = torch.tensor([1, 3, 2])
... | gchaperon/pointer-networks | ptrnets/metrics.py | metrics.py | py | 8,846 | python | en | code | 20 | github-code | 6 |
18187145317 | # -----------------------------
# pluieOS source code
# made with heart by dadoum
# -----------------------------
# Partly based on rainbox
# -----------------------------
import subprocess
import sys
import time
import signal
import os
import traceback
import matplotlib as matplotlib
import numpy
import sh... | Dadoum/pluieOS | pluieLauncher.py | pluieLauncher.py | py | 4,248 | python | en | code | 0 | github-code | 6 |
22879333885 | # import socket
# import json
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# # host = socket.gethostname()
# port = 9999
# s.connect(("127.0.0.1", port))
# msg = s.recv(1024)
# msg = msg.decode('utf-8')
# print(msg)
# s.close()
import socket
import json
s = socket.socket(socket.AF_INET, socket.SOCK_STR... | HugoXK/ECE-445-Senior-Design | client.py | client.py | py | 491 | python | en | code | 0 | github-code | 6 |
72740356347 | import subprocess
from dataclasses import dataclass
from typing import Dict
import json
from src.config import LOGGER
@dataclass
class Server:
server_name: str
server_id: int
class SpeedTestGateway:
@classmethod
def get_speed_test_result(cls, server_id: int) -> Dict:
command = [
... | galloramiro/internet-connection-log | src/speed_test_gateway.py | speed_test_gateway.py | py | 1,128 | python | en | code | 0 | github-code | 6 |
9989418734 | import socket
# Crear un socket TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Vincular el socket a un puerto conocido
server_address = ('', 12345)
sock.bind(server_address)
# Escuchar conexiones entrantes
sock.listen(1)
while True:
connection, client_address = sock.accept()
#... | JoseMiranda21/poli | poli2/app2.py | app2.py | py | 604 | python | es | code | 0 | github-code | 6 |
26171304664 | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.nn import CrossEntropyLoss
from torch.optim import Adam
from datetime import datetime
class MLPClassifier(nn.Module):
def __init__(self):
super().__init__()
self.MLP = nn.Sequential(
nn.Linear(10000... | Charlie-Bell/stack-overflow-classifier | src/MLP.py | MLP.py | py | 2,284 | python | en | code | 0 | github-code | 6 |
19703597779 | # check the costs after every time consuming all examples
# usage: python check_costs.py
import mnist_loader
training_data, validation_data, test_data = mnist_loader.load_data_wrapper()
import network
import numpy as np
import matplotlib.pyplot as plt
net = network.Network([784, 30, 10])
net.set_check_cost_inside_SGD... | hzget/machine-learning | dl_tutorial/check_costs.py | check_costs.py | py | 617 | python | en | code | 0 | github-code | 6 |
6400878080 | ##4. Write a program that takes a line as input and converts all lower-case letters to upper case and all upper-case letters to lower-case and spaces to $.
##Input Example:
##My NaMe is KhaN.
##Output:
##mY$nAmE$ISkHAn.
res=input()
rstr=''
for i in res:
if(i.isupper())==True:
rstr=rstr+(i.low... | bhumijaapandey248/Python-Programs-Assignments | assignment16.4.py | assignment16.4.py | py | 464 | python | en | code | 0 | github-code | 6 |
71484036668 | import sys
if sys.version[0] == '2':
range, input = xrange, raw_input
sys.setrecursionlimit(10 ** 6)
MAX_COINS = 500 * 100
INF = 10 ** 9
def dfs(idx, coins):
if idx == N:
return 0, 0
elif dp[idx][coins] != -1:
return dp[idx][coins]
ret = (0, -INF)
# not buy
ret = max(ret, dfs... | knuu/competitive-programming | aoj/16/aoj1603.py | aoj1603.py | py | 993 | python | en | code | 1 | github-code | 6 |
30665509176 | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('cows/', views.cows_index, name='index'),
path('cows/<int:cow_id>/', views.cows_detail, name='detail'),
path('cows/create/', views.CowCreate.as_view(), name='cow... | jessmucklow/cowcollector | main_app/urls.py | urls.py | py | 1,122 | python | en | code | 1 | github-code | 6 |
4343926541 | # make all the vowels become "g"
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g "
else:
... | silviawin/Giraffe_python_exercises | pyTranslator.py | pyTranslator.py | py | 516 | python | en | code | 0 | github-code | 6 |
31126701613 | from SensorGroup import SensorGroup
from DistanceSensor import DistanceSensor
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
r1 = DistanceSensor(21,20,'r1')
r2 = DistanceSensor(26,19,'r2')
sensorGroup = SensorGroup(sensors=[r1,r2],delay_between_pings_ms =1*1000)
try:
while True:
reading = sensorGroup.measur... | gregorianrants/technic-bot | technic/distance_sensors/SensorGroup.test.py | SensorGroup.test.py | py | 674 | python | en | code | 0 | github-code | 6 |
25168389335 | if __name__ == "__main__":
list_ = [4, -1, 10, -1, 3, -3, -6, 8, 6, 9]
list_n = [i for i in list_ if i % 2 == 1]
list_ch = [i for i in list_ if i % 2 == 0]
print(list_ch)
print(list_n)
z_n = len(list_n)
z_ch = len(list_ch)
if z_n > z_ch:
print("Нечетных больше")
elif z_n < z... | mur78/PythonPY100 | Занятие4/Лабораторные_задания/task1_5/main.py | main.py | py | 445 | python | ru | code | 0 | github-code | 6 |
24213867050 |
from django.contrib import admin
from django.urls import path, include
from . import views
#应用的名称
app_name = 'userprofile'
urlpatterns = [
path('login/', views.user_login, name='login'),
path('logout/', views.user_logout, name='logout'),
path('register/', views.user_register, name='register'),
#用户信息
pa... | blackjibert/Blog | myblog/userprofile/urls.py | urls.py | py | 392 | python | en | code | 0 | github-code | 6 |
6159880936 | import sys
def sum_int():
filename = sys.argv[1]
result = 0
numbers = []
file = open(filename, "r")
numbers = file.read()
numbers = numbers.split(' ')
for i in range(len(numbers)-1):
result = result + int(numbers[i])
return result
if __name__ == '__main__':
print (sum_int... | Vencislav-Dzhukelov/101-3 | week2/2-File-System-Problems/sum_numbers.py | sum_numbers.py | py | 324 | python | en | code | 0 | github-code | 6 |
35616526877 | # https://adventofcode.com/2022/day/15
from dataclasses import dataclass
from aoctk.data import Range, weighted_union_size
from aoctk.input import get_lines
from aoctk.metric import manhattan2d as md
@dataclass
class Sensor:
pos: complex
beacon: complex
distance: int
def __init__(self, desc):
... | P403n1x87/aoc | 2022/15/code.py | code.py | py | 1,883 | python | en | code | 2 | github-code | 6 |
25091116397 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 13:14:13 2019
@author: jordan loll
Creating a cards library / deck
"""
import random
from PIL import Image, ImageDraw
#Local Path
local_path =r"C:\Users\jorda\Documents\PythonPrograms\Questar\Git_Stuff\Quest-Game"
#local_path = r"C:\Users\xTheC\Desktop\Quest\Quest-G... | scottwedge/Quest-Game | Old Files/cards.py | cards.py | py | 1,214 | python | en | code | 0 | github-code | 6 |
11296078217 | import requests
import json
data = {
"a": "GetBidYiDong",
"Token": "29db4b581d67ec1c46a231e09e919671",
"c": "StockBidYiDong",
"UserID": 19,
"day": "20171026"
}
url = "https://hq.kaipanla.com/w1/api/index.php"
respone = requests.post(url, data)
respone.encoding = "unicode_escape"
result = respone.... | mykright/auto_stock_search | 竞价.py | 竞价.py | py | 778 | python | en | code | 3 | github-code | 6 |
38722538066 | import pandas as pd
import numpy as np
import tensorflow as tf
import sklearn.model_selection as sk
import helper as hp
import preprocessing as pre
import machine_learning as ml
import json
import os
from flask import Flask, redirect, url_for, request, jsonify
from tensorflow.keras import layers
from tensorflow.keras.... | ahmedhazemfekry/Neural-Network-Flask-Server | server.py | server.py | py | 4,067 | python | en | code | 0 | github-code | 6 |
36724497528 | from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count
from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse_lazy, reverse
from django.utils import t... | zawi99/web-boards | boards/views.py | views.py | py | 4,855 | python | en | code | 0 | github-code | 6 |
23936105649 | import numpy as np
from scipy.io import loadmat
from variables import*
def load_mat_file(mat_file):
mat_data = loadmat(mat_file)
x, y = mat_data['X'], mat_data['y']
x = x.reshape(
-1,
input_shape[0],
input_shape[1],
input_shape[2]
... | 1zuu/SVHN-Image-Classification | util.py | util.py | py | 543 | python | en | code | 0 | github-code | 6 |
22458997174 | import flask
from flask import Flask,request,jsonify
import json
from sqlib import cek_data_user, input_data,input_dataa, show_data, node1_suhu, node1_kelembapanudara, node1_kelembapantanah, node1_keltanah_konversi, node1_intensitascahaya, node1_curahhujan, node1_curahhujan_konversi, node2_suhu, node2_kelembapanudara, ... | triani16/Aplikasi-Monitoring-Tanaman | penerima.py | penerima.py | py | 6,735 | python | en | code | 0 | github-code | 6 |
71969681149 | """This module is useful for generating yaml files for the withParams tests and for running unformal
compiler tests during development."""
import time
from kfp.compiler import compiler
from kfp import dsl
from kfp.dsl import _for_loop
class Coder:
def __init__(self, ):
self._code_id = 0
def get_code... | kubeflow/kfp-tekton-backend | sdk/python/tests/compiler/compiler_withparams_test_helper.py | compiler_withparams_test_helper.py | py | 3,332 | python | en | code | 8 | github-code | 6 |
71997536508 | from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import *
from .models import *
# from my side...
@login_required(login_url='/useraccount/common_login')
def business_location_list(request):
if request.method =... | chaitphani/New-DivMart | div_settings/views.py | views.py | py | 3,238 | python | en | code | 0 | github-code | 6 |
70720136829 | import re
from zipfile import ZipFile
nothing = 90052
nothings = []
with ZipFile('channel.zip', 'r') as myzip:
def get_path(nothing):
return '{0}.txt'.format(nothing)
def get_next_nothing(nothing):
data = myzip.read(get_path(nothing)).decode('utf-8')
m = re.search('(\d*)$', data)
... | akiran/pythonchallenge | challenge7.py | challenge7.py | py | 758 | python | en | code | 0 | github-code | 6 |
17652959673 | saver = tf.train.Saver()
session=tf.InteractiveSession()
# Initializing the variables
session.run(tf.global_variables_initializer())
for itr in range(training_iters):
offset = (itr * batch_size) % (labels.shape[0] - batch_size)
batch_x = X_train[offset:(offset + batch_size), :, :]
batch_y = y_t... | AntoniaLovjer/audio_adversarial_training | train.py | train.py | py | 1,065 | python | en | code | 1 | github-code | 6 |
30424017235 | import numpy as np
import re
import operator
from Indice_Invertido import Indice_Invertido
class Consulta:
def formataString(self, s):
s = s.lower()
s = re.sub("[:,'|.@()?!#$&]"," ", s)
s = s.replace("\n", " ")
s = re.sub('[^A-Za-z0-9 ]+', '', s)
strings = s.split()
... | pdrsa/PSE | code/Consulta.py | Consulta.py | py | 2,563 | python | pt | code | 0 | github-code | 6 |
13453404410 | import sqlite3
from flask import Flask
import json
app = Flask(__name__)
@app.route('/animals/<idx>')
def animals(idx):
with sqlite3.connect("animal.db") as connection:
cursor = connection.cursor()
query = f"""
select * from animals_final
left join outcomes on outcomes.ani... | aquwue/lesson_15 | main_program.py | main_program.py | py | 812 | python | en | code | 0 | github-code | 6 |
18805686608 | # 3 - Imprima os 10 primeiros números naturais após um número inserido no console usando um loop while:
num = int(input('Informe um número: '))
contador = 0
while (contador < 10):
if num > 0:
num += 1
contador += 1
print(num)
else:
print('erro!, não existem números naturais neg... | chrystian-souza/exercicios_em_python | exerciciosAula4/exercicio03.py | exercicio03.py | py | 352 | python | pt | code | 0 | github-code | 6 |
17996198287 | # -*- coding:utf-8 -*-
# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
# 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
g... | shirleychangyuanyuan/LeetcodeByPython | 53-最大子序和.py | 53-最大子序和.py | py | 672 | python | zh | code | 0 | github-code | 6 |
13680558659 | """ Production Settings """
import os
import dj_database_url
from .dev import *
############
# SECURITY #
############
DEBUG = bool(os.getenv('DJANGO_DEBUG', ''))
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', SECRET_KEY)
ALLOWED_HOSTS = ['*']
###########
# LOGGING #
###########
LOGGING = {
'version': 1,
'h... | team-terminus17/dublin_bus | backend/settings/prod.py | prod.py | py | 604 | python | en | code | 1 | github-code | 6 |
28749398084 | import urllib2
import json
import mraa
import threading
import sys
import time
moveSensor = mraa.Gpio(20)
moveSensor.dir(mraa.DIR_IN)
soundSensor = mraa.Gpio(21)
soundSensor.dir(mraa.DIR_IN)
fotoSensor = mraa.Gpio(43)
fotoSensor.dir(mraa.DIR_IN)
gasSensor = mraa.Gpio(17)
gasSensor.dir(mraa.DIR_IN)
def update():
... | Jasiu0/SmartGlassIoT | client-linkit/rest_client.py | rest_client.py | py | 1,172 | python | en | code | 0 | github-code | 6 |
18028682844 | from pyfiglet import Figlet
import os
from shutil import copyfile
import shutil
import sqlite3
import subprocess
import winreg
import base64
import subprocess
import datetime
import socket
import ctypes
def init():
f = Figlet(font='slant')
print(f.renderText('Reboot'))
print("This program is Artifa... | KIMJOONSIG/Reboot3 | Windows/reboot3.py | reboot3.py | py | 36,418 | python | en | code | 0 | github-code | 6 |
10356870047 | import time
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import ExponentialLR
import argparse
import os
# pylint: disable=E1101, W0612
"""
# GPU CLUSTER
source = '/vol/gpudata/rar2417/src/model1' #path to code location
data_path = '/vol/gpudata/rar2417/Data'... | remit0/SpeechRecognitionProject | legacy/training3.py | training3.py | py | 4,844 | python | en | code | 0 | github-code | 6 |
18454402127 | # -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import sys
import argparse
import logging.config
from pathlib import Path
sys.path.append(str(Path().absolute()))
from mx_crm.main import run_completing
from mx_crm.settings import LOGGING
logging.config.dictConfig(LOGGING)
logger = log... | alexpinkevichwork/squirrel | complete_data.py | complete_data.py | py | 2,311 | python | en | code | 0 | github-code | 6 |
17510483933 | '''
start: 1:42?
end:
left and right pointers
come from both ends until sum of left and right equals target
if the sum isn't target. then if it is more than target decrement right. otherwise increment left
T: O(n) S: O(1)
'''
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
... | soji-omiwade/cs | dsa/before_rubrik/twosum_ordered_input.py | twosum_ordered_input.py | py | 675 | python | en | code | 0 | github-code | 6 |
30903913191 | import pdb
from models.gamedetail import Gamedetail
from models.game import Game
from models.team import Team
from repositories import gamedetail_repository, game_repository, team_repository
gamedetail_repository.delete_all()
game_repository.delete_all()
team_repository.delete_all()
team_1 = Team("Glasgow Clan", "... | GregorRoss/Ice_Hockey_Tracker | console.py | console.py | py | 5,470 | python | en | code | 1 | github-code | 6 |
811063416 | # Network Delay Time - https://leetcode.com/problems/network-delay-time/
'''There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node,
v is the target node, and w is the time it takes for a signal to travel from source to target.... | Saima-Chaity/Leetcode | Graph/networkDelayTime.py | networkDelayTime.py | py | 2,428 | python | en | code | 0 | github-code | 6 |
27284711802 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader as data
from sklearn.preprocessing import MinMaxScaler
# noinspection PyUnresolvedReferences
import silence_tensorflow.auto # for ignoring tensorflow info and warnings
from keras.layers import Dense, Dropout, LSTM
from ... | aashima1433/StockProject | LSTM_model.py | LSTM_model.py | py | 3,046 | python | en | code | 0 | github-code | 6 |
73401806589 | from torch import nn
class Mojmyr(nn.Module):
def __init__(self, input_shape, hidden_units, output_shape):
super().__init__()
# Copy TinyVGG structure, modify it slightly for this specific case
self.conv_block_1 = nn.Sequential(
nn.Conv2d(input_shape, hidden_units, 3, 1, 1),
... | PopeCorn/myr | code/model.py | model.py | py | 1,162 | python | en | code | 0 | github-code | 6 |
74589712187 | import cv2
smilecascade=cv2.CascadeClassifier('haarcascade\\haarcascade_smile.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img=cap.read()
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
smiles = smilecascade.detectMultiScale(img, 1.3,50 )
for (x,y,w,h) in smiles:
cv2.rectangle(img, ... | harshikesh-kumar/Projects | Project Smile Detect.py | Project Smile Detect.py | py | 488 | python | en | code | 0 | github-code | 6 |
44530888336 | import cv2
import numpy as np
from dlclive import DLCLive, Processor
from skimage.transform import (hough_line, hough_line_peaks)
folder = 'model/'
dlc_proc = Processor()
dlc_live = DLCLive(folder, processor=dlc_proc)
dlc_live.init_inference()
i = 0
while True:
# Load frame
i += 1
frame = cv2.imread('fra... | nghess/dlc-live-test | head-angle-vf.py | head-angle-vf.py | py | 2,324 | python | en | code | 0 | github-code | 6 |
26683394696 | #!/usr/bin/python3
'''This module adds all arguments to a Python list and saves them to a file
'''
import sys
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
load_from_json_file = __import__('6-load_from_json_file').load_from_json_file
filename = 'add_item.json'
try:
arguments = load_fro... | nzubeifechukwu/alx-higher_level_programming | 0x0B-python-input_output/7-add_item.py | 7-add_item.py | py | 692 | python | en | code | 0 | github-code | 6 |
25881543237 | #!/usr/bin/python
f = open("in.txt", "r")
kalorije = 0
sumkalorij = []
for vrstica in f:
if len(vrstica) <= 1:
sumkalorij.append(kalorije)
kalorije = 0
else:
kalorije += int(vrstica)
sumkalorij.sort(reverse=True)
print(sumkalorij[0] + sumkalorij[1] + sumkalorij[2]) | Anja159/Advent_of_code_2022 | Day1/part2.py | part2.py | py | 314 | python | hr | code | 1 | github-code | 6 |
24201915314 | from lnd_client import LND_CLIENT
from utilities import *
class Invoice:
def __init__(self, r_hash_hex, payment_request, add_index, is_paid=False):
self.r_hash_hex = r_hash_hex
self.payment_request = payment_request
self.add_index = add_index
self.decoded_pay_req = LND_CLIENT.rpc.... | willcl-ark/boltstore | invoices.py | invoices.py | py | 1,088 | python | en | code | 1 | github-code | 6 |
38036093112 | import logging
from collections import defaultdict
from typing import Dict, Optional, Tuple, Union
import numpy as np
from matplotlib import rcParams
from matplotlib.axes import SubplotBase
from matplotlib.axis import Axis
from matplotlib.colors import LogNorm
from matplotlib.ticker import AutoMinorLocator, MaxNLocato... | hackingmaterials/amset | amset/plot/lineshape.py | lineshape.py | py | 14,486 | python | en | code | 110 | github-code | 6 |
11708352884 | BOARD_SIZE = 9 # it's a square
def strip_zero_unique(list):
strip_zero = [i for i in list if i != 0]
return len(strip_zero) == len(set(strip_zero))
class Board:
def __init__(self):
self.cells = [ [ 0 for _ in range(1 + BOARD_SIZE) ] for _ in range(1 + BOARD_SIZE) ]
self.known_points = []
self.blac... | CristiMacovei/F-Puzzles-Sudoku | board.py | board.py | py | 7,944 | python | en | code | 0 | github-code | 6 |
3026162796 | #encoding: utf-8
'Support subclassing c++ objects in python, with some limitations. Useful primarily for pure-python preprocessors.'
from woo.core import *
from minieigen import *
class PyAttrTrait(object):
'''
Class mimicking the `AttrTrait` template in c++, to be used when deriving from :obj:`PyWooObject`, like ... | Azeko2xo/woodem | py/pyderived.py | pyderived.py | py | 20,207 | python | en | code | 2 | github-code | 6 |
28969795163 | """
Artifact module.
"""
from __future__ import annotations
import typing
from typing import Self
from sdk.entities.artifact.metadata import build_metadata
from sdk.entities.artifact.spec import build_spec
from sdk.entities.base.entity import Entity
from sdk.entities.utils.utils import get_uiid
from sdk.utils.api imp... | trubbio83/core | sdk/sdk/entities/artifact/entity.py | entity.py | py | 14,056 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.