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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
43280131003 | import numpy
import random
import OpenGL
import math
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import definitions
from definitions import *
def reflection_at_y(triangle):
triangle_matrix = numpy.array(definitions.get_triangle_coordinates_list(triangle))
reflect_matrix = numpy.a... | pritamzope/basic_graphics | Reflection/triangle_reflection.py | triangle_reflection.py | py | 1,920 | python | en | code | 2 | github-code | 1 |
5952900144 | import math
income = float(input())
grade = float(input())
minimal_wage = float(input())
Socialscholarship = 0.35*minimal_wage
Socialscholarship = math.floor(Socialscholarship)
results = grade * 25
results = math.floor(results)
if (grade < 4.5) or \
((income > minimal_wage) & (grade < 5.5)):
print("You ... | LachezarKostov/SoftUni | 01_Python-Basics/Exercise2/Exersice8.py | Exersice8.py | py | 783 | python | en | code | 1 | github-code | 1 |
9628500098 | from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
person = [
url(r'^$', views.PersonList.as_view(), name='person-list'),
url(r'^new/$', views.PersonCreate.as_view(), name='person-create'),
url(r'^(?P<pk>[^/]+)/$', views.PersonDetail.as_view(), name... | abertal/alpha | webapp/urls.py | urls.py | py | 4,421 | python | en | code | 5 | github-code | 1 |
72155807073 | from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy
import math
import sys
sys.setrecursionlimit(16000)
from Algorithms.circle_algorithms import circle_algorithms
def init():
glClearColor(0.0,0.0,0.0,0.0)
glMatrixMode
(GL_PROJECTION)
gluOrtho2D(0,640,0,48... | Siddharths8212376/PyOpenGL-for-Windows | boundary_fill_test.py | boundary_fill_test.py | py | 1,554 | python | en | code | 3 | github-code | 1 |
43200983306 | from faker import Faker
from git_class.models_new.database import create_db, Session
from git_class.models_new.car import Car
from git_class.models_new.info_car import InfoCar
def create_database(load_fake_data=True):
create_db()
if load_fake_data:
_load_fake_data(Session())
def _load_fake_data(sess... | Mil6734/git_class | Python2/dz38/create_base.py | create_base.py | py | 801 | python | en | code | 0 | github-code | 1 |
19578680978 | import os
from flask import Blueprint, request, make_response
from werkzeug.utils import secure_filename
from uploadFileTask import handle_file
from ..models import db,Products
import pandas as pd
#from uploadFileTask import handle_file
from multiprocessing.pool import ThreadPool as Pool
upload_products = Blueprint('u... | saxenakartik007/ACME | product_importer/routes/uploadProducts.py | uploadProducts.py | py | 2,808 | python | en | code | 0 | github-code | 1 |
24673403788 | # This code is modified from https://github.com/haoheliu/DCASE_2022_Task_5
# This code is modified from DCASE 2022 challenge https://github.com/c4dm/dcase-few-shot-bioacoustic
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from src.models.meta_learning import BaseModel
from to... | wty0511/MSc_Individual_Project | src/models/TriNet.py | TriNet.py | py | 17,765 | python | en | code | 0 | github-code | 1 |
8803791903 | # Write a function that meets these requirements.
#
# Name: halve_the_list
# Parameters: a single list
# Returns: two lists, each containing half of the original list
# if the original list has an odd number of items, then
# the extra item is in the first list
#
# Examples:
# * input... | Mihso/python-practice-problems | problems/problem_050.py | problem_050.py | py | 1,571 | python | en | code | 0 | github-code | 1 |
9640080626 | import random
import math
def counterRow(square):
rows = 0
for row in square:
count = 0
for cube in row:
if cube == 1:
count += 1
else:
count = 0
if count >= 4:
rows += 1
return rows
... | yixiatros/ergasies_python | εργασία_1.py | εργασία_1.py | py | 3,444 | python | en | code | 0 | github-code | 1 |
10813165237 | import flask
from flask import Flask,request , jsonify
from xyz import AddTwo as ad
app = Flask(__name__)
@ app.route('/')
def test():
return jsonify({"status":"ok"})
@ app.route('/parsename',methods=['GET'])
def test_name():
var_name = request.args.get("name")
return jsonify({"Entered name = ": var... | SaketJNU/software_engineering | rcdu_2750_practicals/rcdu_2750_flask.py | rcdu_2750_flask.py | py | 795 | python | en | code | 15 | github-code | 1 |
4566060055 | from datetime import datetime, timedelta
from unittest.mock import AsyncMock
from framework.clients.cache_client import CacheClientAsync
from framework.di.service_collection import ServiceCollection
from clients.azure_gateway_client import AzureGatewayClient
from clients.email_gateway_client import EmailGatewayClient... | danleonard-nj/kube-tools-api | services/kube-tools/tests/test_gateway_clients.py | test_gateway_clients.py | py | 4,621 | python | en | code | 0 | github-code | 1 |
45121110514 | # -*- coding: utf-8 -*-
import sys
import os
import json
import argparse
def print_rank_0(*args, **kwargs):
rank = int(os.getenv("RANK", "0"))
if rank == 0:
print(*args, **kwargs)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("module_name", type=str)
... | Oneflow-Inc/OneAutoTest | eager/AI_Writer/compare_speed_with_pytorch.py | compare_speed_with_pytorch.py | py | 1,978 | python | en | code | 5 | github-code | 1 |
3581412279 | from list_fns import load_words_append as load_words
from inlist import in_bisect
import time
def find_reverse_pairs(t):
pairs = []
for i in range(len(t)):
word = t[i]
reverse_word = word[::-1]
if reverse_word != word and in_bisect(t[i:], reverse_word):
pairs.append(word)
... | jaredparmer/ThinkPythonRepo | reverse_pair.py | reverse_pair.py | py | 716 | python | en | code | 0 | github-code | 1 |
1155231342 | import pygame
class Ship:
def __init__(self, screen):
self.character = pygame.image.load('hw_images/ship_0009.png')
self.character_rect = self.character.get_rect()
self.screen_rect = screen.get_rect()
self.character_rect.center = self.screen_rect.center
self.ship_speed = 1.0... | m251434/alien_invasion | homework/AI_1/rocket.py | rocket.py | py | 2,184 | python | en | code | 0 | github-code | 1 |
11211086355 | from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import glob
import os
import shutil
required_conan_version = ">=1.32.0"
class VulkanValidationLayersConan(ConanFile):
name = "vulkan-validationlayers"
description = "Khronos official Vulkan validation layers for Wi... | SpaceIm/conan-vulkan-validationlayers | conanfile.py | conanfile.py | py | 5,098 | python | en | code | 0 | github-code | 1 |
41977173104 | class Person:
def __init__(self,name,age,gender):
self._name = name
self._age = age
self._gender = gender
@property
def name(self):
return self._name
@name.setter
def name(self,newName):
self._name = newName
if __name__ == "__main__": #... | madirony/python-study | classlec.py | classlec.py | py | 1,238 | python | ko | code | 0 | github-code | 1 |
17316210746 | """
Flask: Using templates
"""
from asyncore import read
from re import M
from turtle import title
from setup_db import select_students, select_courses
import sqlite3
from sqlite3 import Error
from flask import Flask, render_template, request, redirect, url_for, g
app = Flask(__name__)
DATABASE = './database.db'
d... | m92kasem/VueJS-Flask-Full-Stack | assignment-6/app.py | app.py | py | 6,247 | python | en | code | 0 | github-code | 1 |
28852512367 | import tensorflow as tf
import matplotlib.pyplot as plt
cifar10=tf.keras.datasets.cifar10
(x_train,y_train),(x_test,y_test)=cifar10.load_data()
plt.imshow(x_train[0]) #绘制图片
plt.show()
print("x_train[0]:\n",x_train[0])
print(y_train)
print(x_test.shape)
| 1414003104/OldSheep_TensorFLow2.0_note | 13,卷积神经网络/CIfar10数据集.py | CIfar10数据集.py | py | 282 | python | en | code | 1 | github-code | 1 |
44506208794 | import random
from Fight import Fight
from Person import Person
from Warrior import Warrior
from KnightErrant import KnightErrant
class Fighter(Person):
skills_dict = {
"spear": 0,
"unarmed combat": 0,
"mace": 0,
"broadsword": 0
}
def __init__(self, name, age, wealth, spe... | Christinaperr/SBU_HW2 | Fighter.py | Fighter.py | py | 2,074 | python | en | code | 0 | github-code | 1 |
43753374625 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import torch
import rospy
import numpy as np
from std_msgs.msg import Header
from sensor_msgs.msg import Image
from yolov5_ros_msgs.msg import BoundingBox, BoundingBoxes
from yolo_new.msg import Flag,Serial_RT
IsMoving = 0
SingleSortOK = 1
class Yolo_Dect:
... | Anxy02/Refuse-Classification-Machine | src/yolov5_ros/scripts/yolo_v5.py | yolo_v5.py | py | 8,438 | python | en | code | 1 | github-code | 1 |
38785947998 | import cv2
import tensorflow as tf
import numpy as np
import mnist
import mnist_m
import svhn
import synthdigits
class DataInput(object):
def __init__(self, model_params, mnist_type, phase, is_train):
self.batch_size = model_params["batch_size"]
max_data_num = model_params["max_data_num"]
... | hanzhaoml/MDAN | mnist/mnist_data_input.py | mnist_data_input.py | py | 2,986 | python | en | code | 102 | github-code | 1 |
3693138919 | from interfaces.node import Node
from encryptions.ECB import ECB
from encryptions.OFB import OFB
import threading
keys = {
"K1":"1111111111111111",
"K2":"2222222222222222",
"K3":"3333333333333333",
}
key_wanted = None
km = Node("KM")
receive_number = 0
def set_key_wanted(data):
global key_wanted
... | CozmaCatalin/TCP-communication-with-encrypted-messages-ECB-and-OFB- | KM.py | KM.py | py | 1,484 | python | en | code | 0 | github-code | 1 |
36579701554 | #!/usr/bin/env python
# coding: utf-8
# - Edge weight is inferred by GNNExplainer and node importance is given by five Ebay annotators. Not every annotator has annotated each node.
# - Seed is the txn to explain.
# - id is the community id.
import math
from tqdm.auto import tqdm
import random
import pandas as pd
imp... | eBay/xFraud | xfraud/supplement/07Learning_hybrid/ours_learn-grid-A.py | ours_learn-grid-A.py | py | 7,760 | python | en | code | 56 | github-code | 1 |
26443318875 | from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth import get_user_model, login, logout
from django.contrib import messages
from . import forms, models
# Create your views here.
User = get_user_model()
def signup_view(request):
if request.GET.get('va... | jhonas-palad/permit-application-web | system_auth/views.py | views.py | py | 2,659 | python | en | code | 1 | github-code | 1 |
7417220562 | #!/usr/bin/env python3
from pydantic import BaseModel
from pydantic.schema import schema
from typing import Any
class dumClass(BaseModel):
A : str = 'Hello'
B : str = None
C: bool = False
def __init__(self, **data: Any):
print("dumClass was called")
super().__init__(**data)
pr... | GLYCAM-Web/gems | gemsModules/deprecated/Examples/Sample_Pydantic_Usage.py | Sample_Pydantic_Usage.py | py | 956 | python | en | code | 1 | github-code | 1 |
25779195535 | from logigraph.logigraph import logigraph
from logigraph.solver import linear_solver, edge_logic_solver, absurd_solver
log = logigraph()
log.set_from_file('logigraph_inputs/nolinear.txt')
l = linear_solver()
e = edge_logic_solver()
a = absurd_solver()
l.solve(log)
print(log)
log.set_from_file('logigraph_inputs/noline... | AntLrm/logigraph | some_code.py | some_code.py | py | 376 | python | en | code | 0 | github-code | 1 |
33883097505 | '''
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Exam... | niharikakrishnan/May-LeetCoding-Challenge | 3. Ransom Note.py | 3. Ransom Note.py | py | 785 | python | en | code | 1 | github-code | 1 |
70388329635 | # Libraries
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.subplots as sp
# Global Variables
theme_plotly = None # None or streamlit
week_days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday']
# Layout... | Kaizen-Step/The_Whales_of_Near | pages/2_🌌_Transaction.py | 2_🌌_Transaction.py | py | 15,724 | python | en | code | 1 | github-code | 1 |
29655232584 | from rad.rest.client.api.zonemgr_1 import RAD_NAMESPACE
from rad.rest.client.api.rad_interface import RADInterface
from rad.rest.client.api.zonemgr_1.zone_resources import AnetResource, ZoneResourceFactory
class Zone(RADInterface):
RAD_COLLECTION = 'Zone'
def __init__(self, *args, **kwargs):
super().... | guillermomolina/rad-rest-client | rad/rest/client/api/zonemgr_1/zone.py | zone.py | py | 2,621 | python | en | code | 1 | github-code | 1 |
25159320086 | import itertools
input = """
Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2
Sprinkles: capacity -3, durability 3, flavor 0, texture 0, calories 9
Candy: capacity -1, durability 0, flavor 4, texture 0, calories 1
Chocolate: capacity 0, durability 0, flavor -2, texture 2, calories 8
"""
ingredients =... | jonfriskics/advent_of_code2015 | day15.py | day15.py | py | 2,740 | python | en | code | 0 | github-code | 1 |
27463864604 | import os
import argparse
from os.path import join
import cv2
import dlib
from PIL import Image as pil_image
from tqdm import tqdm
import numpy as np
from pathlib import Path
from dataset import image_paths, _find_images
def get_boundingbox(face, width, height, scale=1.3, minsize=None):
x1 = face.lef... | Aayushi0008/Deepfake-Detection | src/process_frames.py | process_frames.py | py | 4,282 | python | en | code | 1 | github-code | 1 |
2995689088 | errors = {
"out":"Вы вышли из системы",
"noaccess":"У вас нет доступа в раздел",
"unknown":"Неизвестная ошибка",
"timeout":"Система долго не отвечает",
"robot":"Ваши действия похожи на робота"
}
def get_error(*args):
err_list = []
for k in args:
err_list.append(errors[k])
retur... | Kikimopa/python_skypro | lesson6-1/main.py | main.py | py | 525 | python | ru | code | 0 | github-code | 1 |
27438269251 | from __future__ import absolute_import
from __future__ import division
import re
from functools import reduce
import wx
import wx.stc
from six.moves import xrange
from graphics.GraphicCommons import ERROR_HIGHLIGHT, SEARCH_RESULT_HIGHLIGHT, REFRESH_HIGHLIGHT_PERIOD
from plcopen.structures import ST_BLOCK_START_KEYWOR... | thiagoralves/OpenPLC_Editor | editor/editors/TextViewer.py | TextViewer.py | py | 45,065 | python | en | code | 307 | github-code | 1 |
18203106433 | import logging
from ..conversions.types import decode_dict
from . import messages
from .. import settings
logger = logging.getLogger(__name__)
READS_QUEUES = ("os2ds_representations",)
WRITES_QUEUES = (
"os2ds_handles",
"os2ds_matches",
"os2ds_checkups",
"os2ds_conversions",)
PROMETHEUS_DESCRIPTION = ... | os2datascanner/os2datascanner | src/os2datascanner/engine2/pipeline/matcher.py | matcher.py | py | 3,213 | python | en | code | 8 | github-code | 1 |
37129892634 | from ..dateparser import DateSearchStatus, AbstractDateParser
from .time_parser import TimeParser
from .after_minutes_parser import AfterMinutesParser
from .after_hours_parser import AfterHoursParser
from .relative_day_parser import RelativeDayParser
from .day_month_parser import DayMonthParser
from .week_day_parser im... | zolateater/reminder-bot | src/bot/dateparser/searcher.py | searcher.py | py | 2,341 | python | ru | code | 0 | github-code | 1 |
70960292193 | import sys
sys.stdin = open("cowqueue.in", "r")
sys.stdout = open("cowqueue.out", "w")
n = int(input())
record = []
for i in range(n):
start, gap = map(int, input().split())
record.append((start,gap))
def by_time(r):
return r[0]
record.sort(key=by_time)
cur_time = 0
for i in range(n):
start, gap = re... | cola0405/usaco | bronze/17-2/3.py | 3.py | py | 416 | python | en | code | 0 | github-code | 1 |
3168586227 | import os
import csv
import glob
import json
import torch
import warnings
import itertools
import torchaudio
import numpy as np
from pathlib import Path
from tqdm import tqdm
from PIL import Image as PILImage
from itertools import cycle, islice, chain
from einops import rearrange, repeat
import multiprocessing as mp
i... | zhaoyanpeng/vipant | cvap/data/image_text.py | image_text.py | py | 6,470 | python | en | code | 19 | github-code | 1 |
15189448225 | from Orange.misc.utils.embedder_utils import EmbedderCache
from Orange.util import dummy_callback
from orangecontrib.imageanalytics.utils.embedder_utils import ImageLoader
class LocalEmbedder:
embedder = None
def __init__(self, model, model_settings):
self.embedder = model_settings["model"]()
... | biolab/orange3-imageanalytics | orangecontrib/imageanalytics/local_embedder.py | local_embedder.py | py | 1,463 | python | en | code | 32 | github-code | 1 |
40826778374 | import datetime
import glob
import os
import subprocess
import numpy as np
import pandas as pd
import pose
import poses
import rosbag
# Forward errors so we can recover failures
# even when running commands through multiprocessing
# pooling
def full_traceback(func):
import functools
import traceback
@fu... | InnovativeDigitalSolution/NASA_astrobee | tools/graph_bag/scripts/utilities.py | utilities.py | py | 7,299 | python | en | code | 0 | github-code | 1 |
74914202912 | import os
import tempfile
print(tempfile.gettempdir())
print(tempfile.gettempprefix())
with tempfile.TemporaryFile("w+") as tfp:
tfp.write("Some temp data")
tfp.seek(0)
print(tfp.read())
with tempfile.TemporaryDirectory() as tdp:
filepath = os.path.join(tdp, "tempfile.txt")
print(filepath)
... | cfleschhut/python-standard-library-essential-training-linkedin | files_and_directories/02_temporary_files_and_directories.py | 02_temporary_files_and_directories.py | py | 449 | python | en | code | 0 | github-code | 1 |
23462163944 | #!/usr/bin/python3
"""Networking with Python.
Similar to the "2-post_email.py" task but with
`requests`.
"""
import sys
import requests
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.exit(1)
email = requests.post(
sys.argv[1],
data={"email": sys.argv[2]},
ti... | brian-ikiara/alx-higher_level_programming | 0x11-python-network_1/6-post_email.py | 6-post_email.py | py | 382 | python | en | code | 0 | github-code | 1 |
19205793084 |
# Code from Chapter 3 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no... | hiryou/ml-ludus | ludus/book_practice/ml_algo_pers/Ch3/pima_bare_ann.py | pima_bare_ann.py | py | 3,774 | python | en | code | 0 | github-code | 1 |
41035568274 | import typing
from sqlalchemy import and_
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import column
from sqlalchemy import DateTime
from sqlalchemy import false
from sqlalchemy import Float
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import or_
from sqlalch... | sqlalchemy/sqlalchemy | test/typing/plain_files/sql/sql_operations.py | sql_operations.py | py | 4,144 | python | en | code | 8,024 | github-code | 1 |
6208541600 | # -*- coding: utf-8 -*-
"""
usage:
$ baseline_taskAB.py gold_file system_file taskName
- gold_file and system_file are tab-separated, UTF-8 encoded files
- taskName is the name of the task (A|B)
"""
import argparse, sys
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.metri... | msang/haspeede | 2020/eval_taskAB.py | eval_taskAB.py | py | 1,742 | python | en | code | 10 | github-code | 1 |
37583544991 | import pygame
import itertools
screen_size = (1920, 1080)
# pastel pink
LOW_COLOR = (255,209,220)
# deep blue
MED_COLOR = (7, 42, 108)
# red
PARTY_COLOR = (255, 0, 0)
color_map = {
'LOW': LOW_COLOR,
'MED': MED_COLOR,
'PARTY': PARTY_COLOR
}
class VibeLight:
def __init__(self):
self.is_on = Fa... | shivenk78/Spotify-Mood-Detector | vibe_light.py | vibe_light.py | py | 556 | python | en | code | 0 | github-code | 1 |
25952493404 | from flask import Flask, render_template,request, redirect, session
app = Flask(__name__)
app.secret_key = 'what sup?'
# our index route will handle rendering our form
@app.route('/')
def index():
return render_template("index.html")
@app.route('/process', methods=['POST'])
def submit_survey():
print("Got Post... | THEWENDI/Dojo-Survey | server.py | server.py | py | 907 | python | en | code | 0 | github-code | 1 |
12945482684 | from model.misinfo_model import *
if __name__ == "__main__":
for i in range(10):
model = MisinfoPy(n_agents=1000)
model(time_tracking=True, belief_update_fn=BeliefUpdate.SIT)
# # all high:
# # mlit_select=1.0, del_t=0.5, rank_t=0.5, rank_punish=-1.0, strikes_t=0.5)
# ... | felicity-reddel/MisinfoPy | exploring_runtimes.py | exploring_runtimes.py | py | 434 | python | en | code | 1 | github-code | 1 |
9512639189 |
"""
The PyRankine: the hybrid steady-state simulator of Rankine Cycle
run:
python rankinesim_spec.py
Author: Cheng Maohua, Email:cmh@seu.edu.cn
"""
from platform import os
from rankine.utils import OutFiles, create_dictcycle_from_jsonfile
from rankine.simrankine import SimRankineCycle
curpath = os.path.abspath(o... | thermalogic/PyRankine | SimRankine/rankinesim_spec.py | rankinesim_spec.py | py | 1,345 | python | en | code | 4 | github-code | 1 |
30188716160 | import datetime
from util.util import CGreeks, CSingleOptHolding
from util.COption import COption
import pandas as pd
class COptHolding(object):
"""期权持仓类"""
def __init__(self, str_logfile_path=None):
"""
初始化持仓数据及持仓汇总希腊字母
class attributes:
holdings: {'code': CSingleOptHolding}
... | rafs/OptVolTrading | util/COptHolding.py | COptHolding.py | py | 18,040 | python | en | code | 8 | github-code | 1 |
11720956852 | # -*- coding: utf-8 -*-
"""
Preppin' Data 2020: Week 9 - C&BS Co: Political Monitoring
https://preppindata.blogspot.com/2020/02/2020-week-9.html
- Input data
- Remove the Average Record for the polls
- Clean up your Dates
- Remove any Null Poll Results
- Form a Rank (modified competition) of the candidates pe... | kelly-gilbert/preppin-data-challenge | 2020/preppin-data-2020-09/preppin-data-2020-09.py | preppin-data-2020-09.py | py | 9,113 | python | en | code | 19 | github-code | 1 |
31983782662 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch3d.ops import knn_points, ball_query
from .logger import logger
def index_points(points, idx):
"""
Input:
points: input points data, [B, N, C]
idx: sample index data, [B, S, [K]]
Return:
... | lixiny/POEM | lib/utils/points_utils.py | points_utils.py | py | 1,345 | python | en | code | 51 | github-code | 1 |
30094361627 |
#### with lru caching method #########
from functools import lru_cache
@lru_cache(maxsize=16)
def fib(n):
if n<=2 :
return 1
return fib(n-1) + fib(n-2)
print(fib(50))
######################### with memoization technique #########
def fib(n,memo):
if (n in memo):
... | HemantJaiman/Dynamic_programming | fibonacci.py | fibonacci.py | py | 474 | python | en | code | 1 | github-code | 1 |
32180876446 | import torch
from .base_model import BaseModel
from .BigGAN_networks import *
from util.util import toggle_grad, loss_hinge_dis, loss_hinge_gen, ortho, default_ortho, toggle_grad, prepare_z_y, \
make_one_hot, to_device, multiple_replace, random_word
import pandas as pd
from .OCR_network import *
from torch.nn impor... | amzn/convolutional-handwriting-gan | models/ScrabbleGAN_baseModel.py | ScrabbleGAN_baseModel.py | py | 25,408 | python | en | code | 235 | github-code | 1 |
74852307232 |
# PYTHONCASEOK is use for case-sensitive match in windows
# urllib2, scrapy, pyquery, BeautifulSoap, etc. for web scrapping
# os, os.path, and shutil. fies related modules
# number, string, tuple, list, dictionary uses as data type in python.
# we use with statment with files open and close and execption hadling..
# ... | flik/python | pip.py | pip.py | py | 1,380 | python | en | code | 0 | github-code | 1 |
1990468444 | from msilib.schema import Error
import matplotlib.pyplot as plt
import numpy as np
import boto3
import os
def draw_chart(result, user_id, practice_id, gender):
w_min_jitter = 1.599
w_max_jitter = 2.310
w_min_shimmer = 7.393
w_max_shimmer = 12.221
m_min_jitter = 2.159
m_max_jitter = 3.023
m... | Sookpeech/django-analysis | sookpeech_analysis/analysis/make_chart.py | make_chart.py | py | 5,246 | python | en | code | 0 | github-code | 1 |
20165490930 | import pytest
import for_mocking
"""
1. Реализовать программу на Python. Программа может содержать любое количество методов и классов (>0), но обязательно должна иметь класс main.
2. Имитировать:
a. Метод созданного класса (метод не должен являться генератором).
b. Параметр внутри метода класса.
c. Класс.... | iwouldnote/travis_codecod_test | test_mocking.py | test_mocking.py | py | 2,227 | python | ru | code | 0 | github-code | 1 |
73865842594 | import asyncio
from supybot import callbacks, httpserver, log
from .helpers import github
# Import files that will hook themself up when imported
from .events import ( # noqa
commit_comment,
discussion,
issue,
pull_request,
push,
tag,
)
from .patches import gidgethub # noqa
from .protocols ... | OpenTTD/DorpsGek | plugins/GitHub/plugin.py | plugin.py | py | 1,760 | python | en | code | 1 | github-code | 1 |
72070540194 | class Node:
'''
Node represents a node in the Binary Search Tree
functions:
addNode(self,value) - adds a node to the BST with data = value
printTree(self, order) - prints the BST,
order = "in" by default, prints BST in inorder form
order = "pre" prints BST in preorder form
order = "post" prints ... | harshasridhar/Semester1 | DSAD/Assignment/PS6/PS6.py | PS6.py | py | 7,589 | python | en | code | 1 | github-code | 1 |
27487883436 | import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(
packages = [], excludes = [],
include_files = ['icon','toc'],
)
name = 'example'
if sys.platform == 'win32':
name = name + '.exe'
base = None
if sys.platform == ... | lugandong/PyQt5Fastboot | setup_cxfreeze.py | setup_cxfreeze.py | py | 638 | python | en | code | 0 | github-code | 1 |
17811262113 | #!/usr/bin/env python3
import numpy as np
import h5py
import argparse
import matplotlib
import matplotlib.pyplot as plt
import csv
import glob
import os
def get_dataset_keys(f):
keys = []
f.visit(lambda key : keys.append(key) if isinstance(f[key], h5py.Dataset) else None)
return keys
def plot(time, dat... | MichaelSt98/milupHPC | postprocessing/PlotMinMaxMean.py | PlotMinMaxMean.py | py | 3,358 | python | en | code | 6 | github-code | 1 |
6488355399 | '''LETTERCASE PERCENTAGE RATIO
Your goal is to find the percentage ratio of lowercase and uppercase letters in
line below.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each line
of input contains a string with uppercase and lowercase letters E.g.:
thisTHIS
AAbbCCDDEE
N
UkJ
OUT... | mgorgei/codeeval | Easy/c147 Lettercase Percentage Ratio.py | c147 Lettercase Percentage Ratio.py | py | 813 | python | en | code | 1 | github-code | 1 |
33794402927 | from django_filters import rest_framework as filters
from mondoir.utilities.api.filters import (
UserDataModelFilterSet,
MultipleValueFilter
)
class EducationFilterSet(UserDataModelFilterSet):
institution_name = filters.CharFilter(
field_name='institution_name',
lookup_expr='icontains',
... | sheracore/interview_backend_mondoir | mondoir/cvs/api/filters/educations.py | educations.py | py | 831 | python | en | code | 0 | github-code | 1 |
2014274942 | from datetime import datetime
from tqdm.auto import tqdm
import torch
import torch.nn as nn
from torch.nn.utils import clip_grad_norm_
from sklearn import metrics
import numpy as np
from model import VLPForTokenClassification, model_config_factory
from dataset import dataset_factory
from training.utils import get_toke... | filipbasara0/visual-language-processing | training/train_token_cls.py | train_token_cls.py | py | 13,267 | python | en | code | 0 | github-code | 1 |
35076946414 | """
Harvester scripts
Currently only supports AVR atdf files
"""
# Python 3 compatibility for Python 2
from __future__ import print_function
import argparse
import textwrap
from xml.etree import ElementTree
from pymcuprog.deviceinfo.memorynames import MemoryNames
from pymcuprog.deviceinfo.deviceinfokeys import Devic... | SpenceKonde/megaTinyCore | megaavr/tools/libs/pymcuprog/deviceinfo/harvest.py | harvest.py | py | 12,647 | python | en | code | 471 | github-code | 1 |
11196016804 | import sys
import pygame
import random
from src import hero
from src import enemy
class Controller:
def __init__(self, width=640, height=480):
"""
Initializes and sets up the game
args: self.width (int) Width (left to right) of the screen
self.height (int) Height (top t... | brianskim27/cs110 | ch-11-lab-brianskim27/src/controller.py | controller.py | py | 4,941 | python | en | code | 0 | github-code | 1 |
35915131671 | # Mathematics > Probability > Sherlock and Probability
# Help Sherlock in finding the probability.
#
# https://www.hackerrank.com/challenges/sherlock-and-probability/problem
# https://www.hackerrank.com/contests/infinitum-jul14/challenges/sherlock-and-probability
# challenge id: 2534
#
from fractions import Fraction
... | rene-d/hackerrank | mathematics/probability/sherlock-and-probability.py | sherlock-and-probability.py | py | 738 | python | en | code | 72 | github-code | 1 |
20745611124 | """REINFORCE for learning an optimization algorithm."""
import time
import tensorflow as tf
from tf_agents.agents.reinforce import reinforce_agent
from tf_agents.drivers import dynamic_episode_driver as dy_ed
from tf_agents.networks import actor_distribution_network as actor_net
from tf_agents.networks import value_n... | moesio-f/sarlopt | experiments/training/reinforce_baseline.py | reinforce_baseline.py | py | 8,710 | python | en | code | 1 | github-code | 1 |
24477230064 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls import patterns, url
from .views import PromoDetail, PromoList, ChannelPromoList
urlpatterns = patterns(
'',
url(
r'^$',
PromoList.as_view(),
name='list_promos'
),
url(
r'^channel/(?P<channel__long_s... | opps/opps-promos | opps/promos/urls.py | urls.py | py | 646 | python | en | code | 5 | github-code | 1 |
41292812898 | import decimal
import io
from nose.tools import assert_equal
import utcdatetime
from os.path import join as pjoin
from snipe import WatchListSnipesParser, parse_datetime
def test_get_snipes():
with io.open(pjoin('sample_data', 'watch_list.html')) as f:
parser = WatchListSnipesParser(f.read())
asser... | fawkesley/ebay-sniper | test_parser.py | test_parser.py | py | 1,241 | python | en | code | 0 | github-code | 1 |
74219528992 | from lyse import *
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
import scipy.constants as constants
import AnalysisSettings
import SrConstants
from Subroutines.FitFunctions import gauss
from scipy import stats
camera = AnalysisSettings.Camera
pixelSize = SrConstants.pixelSiz... | Loki27182/userlib | analysislib/SrII/old_stuff/AnalysisMultishot.py | AnalysisMultishot.py | py | 5,763 | python | en | code | 0 | github-code | 1 |
22525745523 | '''
print out cmds for training and inference
'''
import argparse
import os
from DPR.dpr.utils.tasks import task_map, train_cluster_map, test_cluster_map
import random
import textwrap
from tqdm import tqdm
def wrap(cmd):
'''
wrap cmd
'''
bs = ' \\\n\t '
return bs.join(textwrap.wrap(cmd,break_lon... | microsoft/LMOps | uprise/get_cmds.py | get_cmds.py | py | 14,669 | python | en | code | 2,623 | github-code | 1 |
599638744 | """A version of BAX pore assembly where subunits are added to the growing
complex one at a time (contrast with bax_pore.py). Also implements cargo
transport (Smac).
"""
from __future__ import print_function
from pysb import *
from pysb.macros import assemble_pore_sequential, pore_transport, pore_species
Model()
# s1... | pysb/pysb | pysb/examples/bax_pore_sequential.py | bax_pore_sequential.py | py | 2,205 | python | en | code | 152 | github-code | 1 |
73428873635 | #!/usr/bin/env python
import time
import openstack
NODE_COUNT = 43
def get_connection():
# openstack.enable_logging(debug=True)
conn = openstack.connect()
return conn
def main():
conn = get_connection()
for i in range(NODE_COUNT):
name = "euclid-ral_compute_%d" % i
conn.delete_server... | astrodb/euclid-saas | delete_servers_euclid.py | delete_servers_euclid.py | py | 500 | python | en | code | 2 | github-code | 1 |
15758517730 | from django.urls import path, include
from website.views import home, blog, perfil, login, acessar, cadastrar
urlpatterns = [
path('', home),
path('blog', blog),
path('login', login),
path('acessar', acessar),
path('perfil', perfil),
path('cadastrar', cadastrar),
]
| isadoraperes/projeto-demoday | website/urls.py | urls.py | py | 291 | python | en | code | 0 | github-code | 1 |
41637205602 | import base64
import logging
import sys
from string import digits, ascii_uppercase
import traceback
import time
from ins import *
from disasm import *
import gpu
class Tape:
'''
Tape is just a looped array of instructions.
'''
@classmethod
def from_inss(cls, inss):
'''Create tape from in... | qxxxb/emu | emu.py | emu.py | py | 16,844 | python | en | code | 0 | github-code | 1 |
23938708203 |
# A very simple Flask Hello World app for you to get started with...
import logging, sys
from flask import Flask, request
from CrapBot import Bot
crap_bot = Bot()
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello from Flask!'
@app.route('/bot', methods=['POST', 'GET'])
def bot():
update... | Markcial/CrapBot | flask_app.py | flask_app.py | py | 588 | python | en | code | 1 | github-code | 1 |
10299733014 | import re
pattern = r'gr.y'
if re.match(pattern, "greyyyy"):
print('match1')
if re.match(pattern, 'grayy'):
print('match2')
pattern1 = r'^gr.y$'
if re.match(pattern1, "grey"):
print('match3')
pattern3 = r'[aucf]'
if re.match(pattern3, "ale"):
print('match4')
pattern4 = r'[A-Z][a-z][0-9]'
if re.s... | lusineduryan/ACA_Python | Sololearn/Regular expressions/Metacharacters.py | Metacharacters.py | py | 968 | python | en | code | 1 | github-code | 1 |
33577989736 | import os, sys
import torch
import torchvision as tv
import cv2
import numpy as np
from matplotlib import pyplot as plt
from dataset import coco_labels
def box_cxcywh_to_xyxy(box):
"""
Convert bounding box from center-size to xyxy format.
:param box: bounding box in center-size format
:return: bound... | 11mhg/theia-detr | utils.py | utils.py | py | 2,045 | python | en | code | 0 | github-code | 1 |
35349712508 | '''
Functions used across response processor.
'''
import logging
import asyncio
from copy import deepcopy
async def copy_stock(table_stock):
'''
Copy a list of dictionaries describing the stock servers being tracked while
excluding websocket connection objects.
:param list table_stock: Stock servers ... | jscottbranson/rippled-livenet-monitor | process_responses/common.py | common.py | py | 2,849 | python | en | code | 5 | github-code | 1 |
29637290452 | import re
import types
from docutils import nodes
from sphinx.util.docutils import SphinxDirective
from . import xnodes
class UserRepository:
def __init__(self):
self._data = None
self._env = None
self._fullnames = None
def clear(self):
self._data = None
self._fullname... | h2oai/datatable | docs/_ext/xcontributors.py | xcontributors.py | py | 15,129 | python | en | code | 1,763 | github-code | 1 |
42614393833 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Global variables
csv_file = 'RealtimePlot.csv' # Replace with the path to your CSV file
update_interval = 1000 # Update plot every 1000 milliseconds (1 second)
fig, ax = plt.subplots()
ax2 = ax.twinx()
# Function t... | wendycahya/Yaskawa-Communication | IntegratedSystem/Realtime-Video.py | Realtime-Video.py | py | 1,139 | python | en | code | 3 | github-code | 1 |
40003928986 | import os
user_name = "Klaus"
def hallo_sagen(menu_name):
print("Hallo", user_name)
print("Du befindest dich im", menu_name)
def addieren(x, y):
return x + y
while True:
os.system("cls")
hallo_sagen("Hauptmenü")
print("[1] Zahlen addieren")
print("[2] Untermenü B")
print("[x] Be... | fiaeb23/Islamovic | Python/Aufgaben - Ubung/12_funktionen.py | 12_funktionen.py | py | 876 | python | de | code | 0 | github-code | 1 |
28015752990 | # @time : 2020/7/12 16:35
# @author : HerbLee
# @file : finance.py
from sanic import Blueprint
from sanic.response import text
from models.funddb import FundDb, CurrentFund
fund = Blueprint("fund", url_prefix="/fund")
@fund.route("/get_data")
async def get_v2_data(request):
return text("it is finance")
... | HerbLee/dawning | api/finance/fund.py | fund.py | py | 931 | python | en | code | 0 | github-code | 1 |
32150920427 | from django.db.models import F
from django.contrib.auth.models import User
from lunchclub.models import AccessToken
class TokenBackend(object):
def authenticate(self, token=None):
try:
token = AccessToken.objects.get(token=token)
except AccessToken.DoesNotExist:
return None... | Mortal/django-lunchclub | lunchclub/auth.py | auth.py | py | 523 | python | en | code | 0 | github-code | 1 |
28934086792 | """
переменные:
pet_alive
pet_sleep
pet_wash
pet_play
день:
1 день 1 млн тиков
ночь:
1 ночь 750 тыс тиков
satiety - сытость:
от 0 до 100
при кормлении += 10
при сне -= 0.5
когда бодрствует -= 2
при игре -= 5
кормление зависит от здоровья и возможно от настроения
ВО... | Anonymkus/Virtual_pet-not-finished- | Virtual_pet_on_Python/Virtual_pet_beta.py | Virtual_pet_beta.py | py | 4,368 | python | ru | code | 0 | github-code | 1 |
42113373089 | import os
import PIL
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import ImageGrid
imgs = []
directory = "output/grids"
# for filename in os.listdir(directory):
# print(filename)
# image = PIL.Image.open(os.path.join(directory, filename))
# imgs.append(np.array(image))
f... | benjaminlyons/lear | display_grid.py | display_grid.py | py | 664 | python | en | code | 0 | github-code | 1 |
32434624148 | import logging
import os
import signal
import watchdog.events
import watchdog.observers.polling
import watchdog_gevent
# https://github.com/Bogdanp/dramatiq/blob/master/dramatiq/__main__.py
def setup_file_watcher(path, callback, use_polling=False):
"""Sets up a background thread that watches for source changes a... | geyang/ml_logger | scratch/old/vis_server_gevent_deprecated/file_watcher.py | file_watcher.py | py | 1,341 | python | en | code | 176 | github-code | 1 |
8103678971 | # coding: utf-8
h2s = response.xpath('//h2')
len(h2s)
h2 = h2s[0]
h2.extract()
h2s[1].extract()
h2s[2].extract() # this 3rd element has the first country (Argentina)
h2_args = h2s[2]
# doing this next xpath off h2_args makes the xpath relative to h2_args
country = h2_args.xpath('span[@class="mw-headline"]/text()').extr... | dyoung418/dataviz-python-js | nobel_winners/day-exploration.py | day-exploration.py | py | 747 | python | en | code | 2 | github-code | 1 |
13496238663 | """A module defining toolchain information about the patchelf rules"""
def _patchelf_toolchain_impl(ctx):
"""The implementation of the `patchelf_toolchain` rule
Args:
ctx (ctx): The rule's context object.
Returns:
list: A list containing a ToolchainInfo provider.
"""
return [platf... | summner/patchelf_rules | patchelf/toolchain.bzl | toolchain.bzl | bzl | 710 | python | en | code | 1 | github-code | 1 |
33578016636 | import numpy as np
import os, random
import cv2
import colorsys
from PIL import Image, ImageDraw, ImageFont
from pipeline.bbox import Box
def get_colors_for_classes(num_classes):
if (hasattr(get_colors_for_classes, "colors") and
len(get_colors_for_classes.colors) == num_classes):
return get_colors... | 11mhg/utils | draw/draw.py | draw.py | py | 2,604 | python | en | code | 0 | github-code | 1 |
74736245474 | from flask import Blueprint,flash,url_for,redirect,render_template,request
from flask_login import login_required
from ksk.models import Pizza
from ksk import db
from ksk.pizza.utils import save_img_for_pizza
from ksk.pizza.forms import PizzaForm
pizzas = Blueprint('pizzas',__name__)
########## Pizza Upload #########... | ZiG-Z/KSK-Bakery | ksk/pizza/routes.py | routes.py | py | 1,280 | python | en | code | 0 | github-code | 1 |
37205573004 | # -*- coding: UTF-8 -*-
from construct import *
from network.packet import PacketHeader
from network.handler import PacketHandler
# Create position structure
StructPosition = Struct(
"x" / Int16ul,
"y" / Int16ul
)
# Create item structures
StructItemAffect = Struct(
"index" / Int8ul,
"value" / In... | xBrunoMedeiros/wyd-bot | network/incoming/mobs.py | mobs.py | py | 2,852 | python | en | code | 1 | github-code | 1 |
2819023333 | import pygame
import random
import math
import pygetwindow as gw
pygame.init()
# Configuración de la pantalla
screen_info = pygame.display.Info()
screen_width = screen_info.current_w
screen_height = screen_info.current_h
# Obtener todas las ventanas abiertas
windows = gw.getWindowsWithTitle('')
target_windows = [win... | SicerBrito/Scripts | Etica/bb/f.py | f.py | py | 1,917 | python | en | code | 13 | github-code | 1 |
74584190434 | #-*- coding:utf-8 -*-
from torch.utils.tensorboard import SummaryWriter
from network import Generator, Discriminator
from toolbox import Train_Handler, parse
from dataset import Real_Data_Generator
from torch.utils.data import DataLoader
import torchvision.transforms as T
import torch.optim as optim
import numpy as np... | galaxygliese/Simple-Implementation-of-StyleGAN2-PyTorch | train.py | train.py | py | 3,100 | python | en | code | 1 | github-code | 1 |
43495379593 | def dfs(index):
if leaf[index]:
return node[index]
for i in child[index]:
ans[index] += abs(dfs(i)-1)
node[index] += node[i] - 1
return node[index]
while True:
N = int(input())
if N == 0:
break
node = [0] * (N+1)
parent = [0] * (N+1)
ans = [0] * (N+1)
... | lsdtve/algorithm | Python/4315_나무 위의 구슬.py | 4315_나무 위의 구슬.py | py | 747 | python | en | code | 0 | github-code | 1 |
4947865207 | import time
import unittest
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class ITTroubleshooterSearchTest(unittest.TestCase):
def setUp(self):
caps = {'browserName': os.getenv('firefox', 'firefox')}
self.browser = webdriver.Remote(
command... | kumargaurav522/selenium | test2.py | test2.py | py | 1,003 | python | en | code | 0 | github-code | 1 |
8155719713 | import math
#PY02028
def isPrime(n):
if n < 2: return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0: return False
return True
n = int(input())
a = []
while len(a) < n:
a += [int(i) for i in input().split()]
for i in range(n - 1):
for j in range(i + 1, n):
if isPrime(a[i]) and isPrime(... | nhikiu/PYTHON-PTIT | PY02028_SAP_XEP_NGUYEN_TO.PY | PY02028_SAP_XEP_NGUYEN_TO.PY | py | 382 | python | en | code | 0 | github-code | 1 |
15128538732 | # O(n^2) time | O(n) space, where n is the length of the input array
# not 100% optimal due to sorting the input array, and then the output
def threeNumberSum(array, targetSum):
array.sort()
output = []
for i in range(1, len(array) - 1):
leftPointer = i - 1
rightPointer = i + 1
whi... | mmichalak-swe/Algo_Expert_Python | Three_Number_Sum/attempt_2.py | attempt_2.py | py | 816 | python | en | code | 3 | github-code | 1 |
19031021092 | import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier as RFC
from src.icll import ICLL
X, y = make_classification(n_samples=500, n_features=5, n_informative=3)
X = pd.DataFrame(X)
icll = ICLL(model_l1=RFC(), model_l2=RFC())
icll.fit(X, y)
probs = ic... | vcerqueira/blog | posts/class_imbalance_icll.py | class_imbalance_icll.py | py | 2,808 | python | en | code | 15 | github-code | 1 |
23983252086 | import pygame
from MENU.Application import Application
from CORE.main_junction import core
#this class file served to activate the game with the selected paramters previously
class Play(Application):
def __init__(self, game):
Application.__init__(self, game)
self.player_parameters = [["PLAYER1","S... | SlyLeoX/Cyber-Puck | Cyberpuck_ReleaseDirectory/MENU/Play.py | Play.py | py | 866 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.