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
37063009817
import cinn import numpy as np import time from cinn import runtime # from PIL import Image # def getimg(fname): # image=Image.open(fname) # image= np.array(image) # return image # print(getimg("/root/RemoteWorking/huazhibin.webp")) def randomImgNCHW(w,h,c=3,n=1): return np.random.randint(0,2...
qlogcn/CINN
tutorials/resize_dev.py
resize_dev.py
py
1,668
python
en
code
null
github-code
6
33942211702
import uvicorn import datetime from loguru import logger from fastapi import FastAPI from sqlalchemy import select from fastapi.middleware.cors import CORSMiddleware from SAGIRIBOT.ORM.AsyncORM import orm from SAGIRIBOT.Core.AppCore import AppCore from SAGIRIBOT.command_parse.Commands import * from SAGIRIBOT.ORM.Async...
m310n/sagiri-bot
WebManager/web_manager.py
web_manager.py
py
3,231
python
en
code
null
github-code
6
40224803539
import sys from PyQt6.QtWidgets import QApplication, QWidget, QLabel from PyQt6.QtGui import QPixmap, QFont class MainWindow(QWidget): def __init__(self): """constructor for Empty windows """ super().__init__() self.initializeUI() def initializeUI(self): """Set up the applicati...
grant-Gan/programing_learn
pyqt6_learn/ch2-Building_a_simple_GUI/user_profile.py
user_profile.py
py
2,148
python
en
code
0
github-code
6
29582028401
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, models, _ _logger = logging.getLogger(__name__) class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_auto_open(self): return_item = super(AccountInvoice, self).a...
OdooNodrizaTech/slack
slack_sale_orders_generate_invoice/models/account_invoice.py
account_invoice.py
py
2,180
python
en
code
0
github-code
6
36092775168
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Sources of authentication from the request. Each source is a :func:`callable`. The source is called with the request and returns ``None`` if it cannot extract informations or a dict with the values it has got. The first source returning a non ``None`` value is used fo...
napix/NapixServer
napixd/auth/sources.py
sources.py
py
2,197
python
en
code
1
github-code
6
30477193038
""" Sample Input: Enter rotational copies: 5 Enter sides per polygon: 4 Enter edge pixel length: 100 Enter row range start: -200 Enter row range end: 200 Enter row range increment: 400 Enter col range start: -250 Enter col range end: 250 Enter col range increment: 250 """ import turtle import random def draw_polygon(...
CedarCollins/Introduction-to-Computer-Programming
Turtle Polygon Rotations Grid.py
Turtle Polygon Rotations Grid.py
py
3,011
python
en
code
0
github-code
6
7571022590
import numpy as np import logging import sys import pkg_resources import pytz import datetime import os import re from numpy import cos,sin # Get the version version_file = pkg_resources.resource_filename('pynortek','VERSION') # Setup logging module logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) logger =...
MarineDataTools/pynortek
pynortek/pynortek.py
pynortek.py
py
17,352
python
en
code
4
github-code
6
72407617147
def parens(num, the_str='()'): the_set = set() if num == 1: return [the_str] else: for i in range(len(the_str) + 1): the_set.add(the_str[:i] + '()' + the_str[i:]) for i in the_set: temp_list = parens(num - 1, i) if type(temp_list) == set: ...
endere/code-katas
parens/parens.py
parens.py
py
609
python
en
code
0
github-code
6
15915660899
"""initial Revision ID: 977a56225963 Revises: None Create Date: 2016-09-24 22:05:55.701455 """ # revision identifiers, used by Alembic. revision = '977a56225963' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### o...
cloudiirain/Website
migrations/versions/977a56225963_.py
977a56225963_.py
py
1,139
python
en
code
null
github-code
6
8655579477
from torch import nn import torch import utils import cv2 import numpy as np import supervisely_lib as sly def inference(model: nn.Module, input_height, input_width, image_path, device=None): with torch.no_grad(): model.eval() image = sly.image.read(image_path) # RGB input = utils.prepare_image_i...
supervisely-ecosystem/unet
custom_net/inference.py
inference.py
py
1,728
python
en
code
2
github-code
6
1856720220
"""Unit test is expected to be here, while I use some usage cases instead.""" from name_analyzer.name_analysis import Name_analysis if __name__ == '__main__': # query = 'Martin Reynolds British' # query = 'Martin Reynolds Maynard' # query = 'Darry Holliday University of Holy Cross' # query = 'Caron An...
LinZhihaozlin22/textual_name_analyzer
tests/test.py
test.py
py
704
python
en
code
1
github-code
6
40056110993
#https://docs.python.org/3/library/heapq.html #https://www.programiz.com/python-programming/methods/dictionary/get #Link: https://leetcode.com/problems/top-k-frequent-elements/ # Name: Top K Frequent Elements # Difficulty: Medium # Topic: Min Heap #Time: O(n log k) since we update the root a maximum of n times, each u...
Shivaansh/AlgoExpert-LeetCode-Solutions
LeetCode Problems/Python/TopKFrequentElements.py
TopKFrequentElements.py
py
749
python
en
code
2
github-code
6
72532362749
import logging from asyncio import CancelledError, Task, create_task from collections.abc import AsyncGenerator from contextlib import asynccontextmanager, suppress from fastapi import FastAPI from servicelib.logging_utils import log_context from watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT from ._context i...
ITISFoundation/osparc-simcore
services/dynamic-sidecar/src/simcore_service_dynamic_sidecar/modules/outputs/_watcher.py
_watcher.py
py
4,081
python
en
code
35
github-code
6
32347991199
import cv2 as cv import numpy as np def nothing(x): pass cap= cv.VideoCapture('pranay1.avi') fourcc= cv.VideoWriter_fourcc('X', 'V', 'I', 'D') out= cv.VideoWriter('final1.avi', fourcc, 20.0, (640,480) ) #cv.namedWindow('Tracking') #cv.createTrackbar('l_h', 'Tracking', 0, 255, nothing) #cv.createTrackbar('l_s', 'Tr...
pranayvarmas/Virtual-Keyboard
Mini-Projects/Invisible Cloak.py
Invisible Cloak.py
py
1,721
python
en
code
0
github-code
6
11160464439
from django.db import models from book_archive.models import Genre from config.models import User class BookRequest(models.Model): title = models.CharField('Наименование', max_length=128) author = models.CharField('Автор', max_length=128, null=True, blank=True) genre = models.ForeignKey(Genre, on_delete=...
SliceOfMind/thesombot_web
book_request/models.py
models.py
py
989
python
en
code
0
github-code
6
37349408
"""See `TestSet` for an example.""" from typing import Type, MutableSet from tests.collection_testing import unordered_equal class MutableSetTests: mutable_set: Type = None @classmethod def create_mutable_set(cls) -> MutableSet: return cls.mutable_set() @staticmethod def get_element(i):...
BlackHC/mamo
tests/collection_testing/test_mutable_set.py
test_mutable_set.py
py
2,179
python
en
code
0
github-code
6
10230332445
""" This file defines the recorder classes which log eval results in different ways, such as to a local JSON file or to a remote Snowflake database. If you would like to implement a custom recorder, you can see how the `LocalRecorder` and `Recorder` classes inherit from the `RecorderBase` class and override certain me...
openai/evals
evals/record.py
record.py
py
23,030
python
en
code
12,495
github-code
6
16013407471
import cv2 import numpy as np import matplotlib.pyplot as plt img=cv2.imread('/home/hasantha/Desktop/repos/old-yolov4-deepsort-master/data/download2.png' ,0) #img=img[423:998,806:1408] ret, bw_img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY) #165 kernel = np.ones((1,1),np.uint8) #erosion = cv2.erode(img,kernel,i...
hasantha-nirmal/Traffic_Violation_Detection_Yolov4_Deep-Sort
lane_line_extract3.py
lane_line_extract3.py
py
850
python
en
code
23
github-code
6
1160957146
#!/bin/python3 import math import os import random import re import sys def getMaxStreaks(toss): result = [0,0] for num in range(len(toss)-1): repeat = 0 if toss[num] == "Heads": for t in toss[num:]: if t == "Heads": repeat += 1...
ryanstang/Interaction-Simulation
simulton.py
simulton.py
py
914
python
en
code
0
github-code
6
810151506
# Add Binary - https://leetcode.com/problems/add-binary/ '''Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101"''' class Solution: def addBinary(self, a: str, b: str) -> str: m...
Saima-Chaity/Leetcode
Array_String/Add Binary.py
Add Binary.py
py
823
python
en
code
0
github-code
6
20497360293
import random from datetime import datetime ALPHABET = 'abcdefghijklmnopqrstuvwxyz' conteudo = 'There are many variations of passages of Lorem Ipsum available, but the ' \ 'majority have suffered alteration in some form, by injected humour, or randomised ' \ 'words which look even slightly believ...
Adriano1976/Curso-de-Python
Secao11-Django-com-Python-Projetos/Projeto-Blog/posts-generator.py
posts-generator.py
py
1,787
python
pt
code
0
github-code
6
33787246110
from itertools import chain import os import pytest @pytest.fixture(scope="module") def organization_id(): """Get Organization ID from the environment variable """ return os.environ["GCLOUD_ORGANIZATION"] @pytest.fixture(scope="module") def source_name(organization_id): from google.cloud import security...
silverdev/google-cloud-python
securitycenter/docs/snippets_findings.py
snippets_findings.py
py
20,863
python
en
code
0
github-code
6
15826998547
import random from hackgen import TestInputFormat, TestGenerator, Language class ClockDelayInputFormat(TestInputFormat): """ Input format of Clock Delay challenge. https://www.hackerrank.com/contests/hourrank-28/challenges/clock-delay """ # difficulty levels with test file number # difficult...
renuka-fernando/hackgen
examples/clockdelay/clock_delay.py
clock_delay.py
py
1,236
python
en
code
11
github-code
6
5033798447
import random import operator RULE = "What is the result of the expression?" def creating_quiestion_and_answer(): number1 = random.randint(1, 10) number2 = random.randint(1, 10) operation, function = random.choice([ ('+', operator.add), ('-', operator.sub), ('*', operator.mul), ...
xegrassa/python-project-lvl1
brain_games/games/brain_calc.py
brain_calc.py
py
437
python
en
code
0
github-code
6
72532676669
# pylint: disable=protected-access # pylint: disable=redefined-outer-name # pylint: disable=unused-argument import urllib.parse from pathlib import Path from random import choice from typing import Awaitable, Callable import pytest from aiohttp import web from aiohttp.test_utils import TestClient from faker import F...
ITISFoundation/osparc-simcore
services/storage/tests/unit/test_handlers_files_metadata.py
test_handlers_files_metadata.py
py
5,239
python
en
code
35
github-code
6
74131098748
# coding:utf8 from app.game.core.Room import Room from app.game.action import change from app.util.common import func from app.util.defines import dbname, status, games, origins, rule from app.util.driver import dbexecute class RoomPoker(Room): def __init__(self): super(RoomPoker, self).__init__() ...
alex-my/game-poker-server
app/game/core/RoomPoker.py
RoomPoker.py
py
5,616
python
en
code
0
github-code
6
39459918108
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='index'), # url(r'^games/(?P<steamid>[0-9]+)$', views.games, name='games'), url(r'^home/$', views.home, name='home'), url(r'^games/', views.games, name='games'), url(r'^friends/', views.friends, name=...
ryanchesler/allauth_django
core/urls.py
urls.py
py
401
python
en
code
0
github-code
6
34303995178
from tkinter import * root = Tk() root.title("Hello GUI") # 제목 설정 root.geometry("700x500+350+150") # 가로크기 * 세로크기 + x좌표 + y좌표 root.resizable(False, False) # x,y 크기 조정 가능 여부 listbox = Listbox(root, selectmode="extended", height=3) # height가 0이면 모든 요소가 다 보임 listbox.insert(0, "루저 걸") listbox.insert(1, "저승으로 가는 버스에 타고 안녕"...
Penguin-God/Python_GUI_Programming
1_Basic/5_listbox.py
5_listbox.py
py
1,099
python
ko
code
0
github-code
6
27250989956
import torch.nn.functional as F import torch.nn as nn import torch filters = torch.tensor([[[[2, 0, 0], [1, 0, 1], [0, 3, 0]], [[1, 0, 1], [0, 0, 0], [1, 1, 0]], [[0...
moon-hotel/DeepLearningWithMe
Archived/02_ConvolutionalNN/01_CNNOP/01_CnnOpSingleFilter.py
01_CnnOpSingleFilter.py
py
1,225
python
en
code
116
github-code
6
33671678331
from __future__ import annotations from datetime import datetime from datetime import timedelta from unittest.mock import MagicMock import pytest from common.reddit_client import RedditClient from prawcore.exceptions import Forbidden from requests import Response @pytest.fixture def reddit_client(): return Redd...
kelvinou01/university-subreddits
tests/unit/test_reddit_client.py
test_reddit_client.py
py
2,642
python
en
code
0
github-code
6
30188434989
import bluetooth class Alpha1S: """ Class to control the Ubtech Alpha 1S robot """ def __init__(self, name="ALPHA 1S"): self.__bt = self.Alpha1S_bluetooth(name) def battery(self): """ Get battery information. Returns: dict: Dictionary with fields: ...
alvaroferran/Alpha1S
alpha1s/__init__.py
__init__.py
py
7,677
python
en
code
6
github-code
6
70809071868
# ------------------------------------------------------------------# # AMPBA - 2021 Winter :: Data Collection assignment - PART2 # # Group Id : 3 # # Authors: # # Nishant Jalasutram - PG I...
deepkamal/DC_AMPBA_W2021
3_matchDetails.py
3_matchDetails.py
py
11,760
python
en
code
0
github-code
6
50777891
from typing import List class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: ans = [0] * len(temperatures) stack = [0] for i in range(1, len(temperatures)): if temperatures[i] <= temperatures[stack[-1]]: # if temp is not larger, jus...
code-cp/leetcode
solutions/739/main.py
main.py
py
802
python
en
code
0
github-code
6
25008129901
from osv import fields, osv import time import netsvc class mrp_reversed_bom(osv.osv_memory): _name = "mrp.reversed.bom" _description = "Reversed Bom" _columns = { } def do_reverse(self, cr, uid, ids, context={}): """ To check the product type @param self: The object pointer. ...
factorlibre/openerp-extra-6.1
reverse_bom/wizard/mrp_bom_reverted.py
mrp_bom_reverted.py
py
3,177
python
en
code
9
github-code
6
6313183972
from django.urls import path, include from django.conf.urls import url from mysite import views urlpatterns = [ path('search/', views.search_view, name='search'), url(r'^request/(?P<record_id>[-\w]+)/$', views.send_req_view, name='request'), path('requests/', views.req_view, name='requests'), path('...
abpopal/sehat.af
mysite/urls.py
urls.py
py
1,044
python
en
code
0
github-code
6
21344672699
import csv import html import pickle from util import md5sum """ Loader class for turning a Twitter Archive into a list of tweets to be used later on. Source file is expected at ./tweets.csv , which any twitter user can download as their Twitter Archive. """ class TweetLoader: """ Constructor. Arguments...
kymagic/yaebooks-twitter
ebooks/tweetloader.py
tweetloader.py
py
5,625
python
en
code
0
github-code
6
7998920894
import random from . import users from flask import request import json ##### Hier kommt code, den ich einfach von Tina so übernommen habe. Wenn er schlecht ist ist Tina schuld ############ import os from dotenv import load_dotenv from flask import jsonify, Response import pymongo import hashlib # Die brauchen wir fü...
rosemaxio/flauraBackend
users/Api.py
Api.py
py
10,619
python
de
code
0
github-code
6
3835462701
#coding: utf-8 import urllib import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import webbrowser import os from threading import Timer import base64 from ui import Image import console import sys import io sys.stderr = io.StringIO() console.show_activity('Creating images…') imagefilenames ...
0942v8653/pythonista-homescreen-icon
chooseicon.py
chooseicon.py
py
2,087
python
en
code
9
github-code
6
39399855904
import datetime import decimal import logging import os import re from kensu.psycopg2.pghelpers import get_table_schema, get_current_db_info, pg_query_as_dicts from kensu.utils.kensu_provider import KensuProvider from kensu.utils.kensu import KensuDatasourceAndSchema from kensu.utils.dsl.extractors.external_lineage_dto...
Fundamentals-of-Data-Observability/handson
python_environment/volume/week2/dbt/dbt-do/dbt-ast/kensu_postgres.py
kensu_postgres.py
py
12,258
python
en
code
8
github-code
6
30338109347
from collections import deque n, k = map(int, input().split()) graph = [[] * (k+1) for _ in range(k+1)] gmap = [[] * (n+1) for _ in range(n+1)] for i in range(1, n+1): arr = list(map(int, input().split())) gmap[i] = arr for j, m in zip(arr, range(1, n+1)): if j != 0: graph[j].append((i, ...
minju7346/CordingTest
bfs3.py
bfs3.py
py
944
python
en
code
0
github-code
6
24985299915
#Imprting libraries from dash import Dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from random import randint import plotly.express as px # Creating dash environment app = Dash(__name__) # Constructing the layout app.layout = html.Div([ # T...
Miautawn/simple-DashBoard-with-Dash
random_plotter.py
random_plotter.py
py
2,553
python
en
code
0
github-code
6
38751132701
import os import util import config scanned_files = 0 for directory, _, files_list in os.walk(config.td): #directory looks like "c:\user\box\...\phonexx\images" for ea_filename in files_list: #ea_filename looks like "ADX-....jpg" file_path = (directory+"\\"+ea_filename) #file_path ...
maravis05/EyeCup-File-Scanner
move_pxl.py
move_pxl.py
py
1,001
python
en
code
0
github-code
6
17202898458
#!/usr/bin/env python import robot import time from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import json import logging def send_json(data): msg = {'action':data} msg = json.dumps(msg) return (msg) def action(client, userdata, message): data = message.payload.decode() data = json.loads(data) data = da...
mkyle1121/gopigo
web/robot_sock_client2.py
robot_sock_client2.py
py
2,084
python
en
code
0
github-code
6
8207780556
import base64 from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.cache import never_cache from stolen_wiki_game.models import Article # Create your views here. def index(request): return render(request, 'stolen_wiki_game/index.html', {}) @never_cache def arti...
Jack-Naughton/homepage
stolen_wiki_game/views.py
views.py
py
596
python
en
code
0
github-code
6
1443436731
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Camera class CameraAddForm(forms.ModelForm): class Meta: model = Camera fields = ['title', 'ip'] labels = { 'title': _('Titel'), 'ip': _('Adresse') ...
Thorium0/Security-terminal
Terminal/camera/forms.py
forms.py
py
324
python
en
code
0
github-code
6
12492560506
#!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import print_function import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import classification_report from sklearn import metrics from sklearn import tree import warnings warnings.filterwarni...
Panktibhatt08/Machine-Learning
Machine Learning Final Project.py
Machine Learning Final Project.py
py
14,506
python
en
code
0
github-code
6
15366599622
from .File import File, WrongFormatError, BrokenFormatError, FileNotFoundError, EmptyFileError from .FileFormats import FileFormat # User defined formats from .FASTInFile import FASTInFile from .FASTOutFile import FASTOutFile from .FASTWndFile import FASTWndFile from .CSVFile import CSVFile from .HAWC2PCFile ...
rhaghi/welib
welib/weio/__init__.py
__init__.py
py
2,069
python
en
code
null
github-code
6
6214826810
from json import loads from bot_core.utils.redis_topics import CMD_COLL_NAME from bot_core.utils.action_tools import cmd_analysis, pub_sub def main(): pub_sub.subscripe(CMD_COLL_NAME) while (True): msg_data = pub_sub.get_message().get("data", None) if msg_data: cmd_analysis( ...
KTOALE/tel_bot_coro
bot_core/src/main_core.py
main_core.py
py
401
python
en
code
0
github-code
6
38763808043
import spotipy from model import * from enum import Enum class EmotionsMood(Enum): """Creating constants to assign to different moods""" Calm = 1 #Calm Energetic = 2 happy = 2 sad = 0 def get_songs_features(sp,ids): """Get features of songs to identify tyoe of music""" meta = sp.track(id...
nagarro-hackathon-2023/python_ml
spotify.py
spotify.py
py
3,947
python
en
code
0
github-code
6
16320688822
#!/usr/bin/python from tkinter import * # mebuat kolom window root =Tk() root.geometry('250x250') root.title('Cantatan mede in yusuf') # membuat text box text = Text(root, font=('haveltical 15 bold'), bd=2) text.focus() text.pack() # membuat fungsi untuk perintah cut # pilihan texs def cut_text(): text.even...
dulimpul/dulimpul
main.py
main.py
py
1,088
python
id
code
0
github-code
6
29899432213
import numpy as np from absl import app, flags HEADER_SIZE = 10 RECORD_SIZE = 100 FLAGS = flags.FLAGS flags.DEFINE_string( "input_file", None, "Path to binary data file.", short_name="i", ) flags.DEFINE_string( "output_file", None, "Path to output file (optional).", short_name="o", ) ...
exoshuffle/raysort
scripts/misc/decode.py
decode.py
py
1,340
python
en
code
14
github-code
6
31086494290
import unittest from midiutil import MIDIFile from services.midi_creator import MidiCreator from entities.shaku_part import ShakuPart from entities.shaku_note import ShakuNote class TestMidiCreator(unittest.TestCase): def setUp(self): self.creator = MidiCreator() def test_generate_midi_raises_error_if...
ElectricShakuhachi/shakunotator
src/tests/midi_creator_test.py
midi_creator_test.py
py
883
python
en
code
0
github-code
6
21508477562
def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False return pri...
hmharshit/hacktoberfest
Solutions/summation_of_primes.py
summation_of_primes.py
py
618
python
en
code
12
github-code
6
21320836605
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import SAGEConv from torch_geometric.nn import aggr from src.utils import make_diff_matrix, triu_vector class Model(nn.Module): NUM_NODE_FEATURES = 140 NUM_OPCODES = 120 def __init__(sel...
Obs01ete/kaggle_latenciaga
src/model.py
model.py
py
7,190
python
en
code
1
github-code
6
70749170429
#Server dependencies #from gevent.pywsgi import WSGIServer from threading import Thread from flask import Flask, request, send_from_directory from flask_mobility import Mobility import os #Apis used from assistant import sendToAssistant #File management #from bs4 import BeautifulSoup import codecs #import re import j...
Creativity-Hub/chatbot_template
main.py
main.py
py
2,540
python
en
code
1
github-code
6
12066432298
import tensorflow as tf import numpy as np import pandas as pd import ast import pickle class TetrisAgent: def __init__(self): nx = 3400 ny = 34 self.X = tf.placeholder(dtype=tf.float32, shape=(None, nx + 1), name="X") theta = tf.Variable(tf.random_uniform([nx + 1, 34], -1.0, 1.0)...
smlgorta/dltetris
tetris_agent.py
tetris_agent.py
py
1,069
python
en
code
0
github-code
6
2799425380
import os.path import random import torchvision.transforms as transforms import torch from data.base_dataset import BaseDataset, get_params, get_transform, normalize from data.image_folder import make_dataset from PIL import Image import numpy as np class AlignedDataset(BaseDataset): def initialize(self, opt): ...
carolineec/EverybodyDanceNow
data/aligned_dataset.py
aligned_dataset.py
py
3,566
python
en
code
639
github-code
6
7774997291
# state_list : uma matriz de duas colunas, onde a primeira representa a # matriz estado,e a segunda se ela ainda possui movimentos # inexplorados. # Função Move : Recebe um estado, e tenta mover uma peça da coluna X # para a coluna Y. Se não for possível, ou se X = Y, # ...
LucasEduardoGiovanini/AI-Implementations
Hanoi_Tower_Searches.py
Hanoi_Tower_Searches.py
py
11,949
python
pt
code
0
github-code
6
6251031632
import matplotlib.pyplot as plt import eel eel.init("web") userid = [] @eel.expose def login(uid,upass): get = open("data.txt", "r") temp = get.readlines() udata = [] for i in range(len(temp)): if temp[i].startswith(uid): udata = temp[i].split("|") ...
vish0290/Polling-System-File-Structures
main.py
main.py
py
17,483
python
en
code
0
github-code
6
36312680043
import pandas as pd from xml.etree import ElementTree as ET import requests from datetime import datetime import matplotlib.pyplot as plt q_range = {'Range': 1} q_resp_group = {'ResponseGroup': 'History'} q_url_WHO = {'https://www.who.int/'} q_date = datetime.date(datetime.now()) url = "https://awis.api.alexa.com/api...
alanalien/covid_19_circumstantial_evidences
data_processing_funs/click_ratio_data.py
click_ratio_data.py
py
1,858
python
en
code
0
github-code
6
7653898910
import random from math import exp, floor, log from hypergraphx import Hypergraph import numpy as np def find_intersection(x, func): num = floor((x / func[0]) ** (1 / func[1])) return num def non_linear_distribution(infected_nodes, param, len_edge): # TODO: define the non-linear distribu...
francescoboldrin/noise_lib
m_contagion.py
m_contagion.py
py
8,449
python
en
code
2
github-code
6
2726023308
n = int(input()) for _ in range(n): p = input() if len(p) == 3: counter = 0 x = 'one' for i in range(3): if p[i] != x[i]: counter += 1 if counter <= 1: print(1) else: print(2) else: print(3)
wolney-fo/beecrowd
3-STRINGS/python/beecrowd_1332.py
beecrowd_1332.py
py
302
python
en
code
1
github-code
6
27082695603
import pytest from httpx import AsyncClient from fastapi1.main import app menu_id = '' def assert_menu_properties(response_json): if not response_json: return assert 'id' in response_json assert 'title' in response_json assert 'description' in response_json @pytest.mark.anyio async def tes...
puplishe/testproject
tests/test_menu.py
test_menu.py
py
3,056
python
en
code
0
github-code
6
12050674214
"""Define settings for the window""" from data.options import CUSTOM_SETTINGS_FILENAME import json from logger import logger from os import path DEFAULT_SETTINGS = { "width": 1024, "height": 768 } def get(_type, data): """Used to get value for the settings file Args: _type (string) ...
Barbapapazes/dungeons-dragons
config/window.py
window.py
py
779
python
en
code
1
github-code
6
36078929738
import requests from sqlalchemy import or_ from flask import Blueprint from flask_login import current_user from flask import redirect, request, render_template, url_for, jsonify from models import User, MealRequest, Proposal from dbSession import session from loginAPIKeyDecorator import require_api_key f...
NaPiZip/Online-course-notes
Designing_RESTful_APIs/Exercices/L5/appEndpoints.py
appEndpoints.py
py
7,871
python
en
code
0
github-code
6
74606056828
from __future__ import unicode_literals import errno import json import logging import os __author__ = 'Jakub Plichta <jakub.plichta@gmail.com>' logger = logging.getLogger(__name__) class DashboardExporter(object): def process_dashboard(self, project_name, dashboard_name, dashboard_data): pass clas...
jakubplichta/grafana-dashboard-builder
grafana_dashboards/exporter.py
exporter.py
py
2,430
python
en
code
141
github-code
6
12940641997
import os import csv #Load file path csvpath = os.path.join('Resources','election.csv') #Placeholders for votes and candidates total_votes = 0 vote_total = [] candidates_name = [] each_vote = [] percent_of_vote = [] #open file and read in results with open(csvpath) as election_csv: csvreader = csv.rea...
Anastefanski/Python_Challenge
PyPoll/main.py
main.py
py
2,398
python
en
code
0
github-code
6
19654989478
""" 练习1:百分制成绩转换为等级制成绩。 要求:如果输入的成绩在90分以上(含90分)输出A; 80分-90分(不含90分)输出B; 70分-80分(不含80分)输出C; 60分-70分(不含70分)输出D; 60分以下输出E。 """ score = float(input("请输入百分制成绩:")) if (score >= 90): print("A") elif (score >= 80): print("B") elif (score >= 70): print("C") elif (score >= 60): print("D") else: print("E") """ 输...
StreamAzure/PythonPractice
0x01-basic/practices2.py
practices2.py
py
850
python
zh
code
0
github-code
6
9379980340
# 2022.05.02 # 풀이 시간 분 초 # 채점 결과: 시간 초과 # 시간복잡도: O(N) # 문제 링크: https://www.acmicpc.net/problem/3955 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): k, c = map(int, input().split()) possible = False people = 0 for i in range(int(1e9)): if (k * i + 1) % c == 0: ...
Source-Machine-Ent/Algorithm-class
ningpop/3955.py
3955.py
py
519
python
ko
code
2
github-code
6
9199268826
from imageai.Detection import VideoObjectDetection import os execution_path = os.getcwd() detector = VideoObjectDetection() detector.setModelTypeAsRetinaNet() detector.setModelPath(os.path.join(execution_path, "resnet50_coco_best_v2.1.0.h5")) detector.loadModel() detections = detector.detectObjectsFromVideo(input_file...
cegepmatane/projet-graphique-ai-tracking
poc/tensorflow_video/demo.py
demo.py
py
577
python
en
code
0
github-code
6
12866551280
import random array = [random.randint(0,50) for i in range (9) ] print (array) def quickSort(arr): if len(arr) < 1: return arr pivot_index = random.randint(0, len(arr) - 1) left = [] mid = [arr[pivot_index]] right = [] for i in range(len(arr)): if i != pivot_index: if...
tyao117/AlgorithmPractice
QuickSort.py
QuickSort.py
py
595
python
en
code
0
github-code
6
18992770732
""" 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入:strs = ["flower","flow","flight"] 输出:"fl" 示例 2: 输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。 """ import typing class Solution: def longestCommonPrefix(self, strs)->str: l = len(strs) if l <= 0: return "" ...
coolzyz/leetcode
14.py
14.py
py
988
python
en
code
0
github-code
6
10888914316
import random from django.template.loader import render_to_string from .naver import 블로그_검색, 상한가_크롤링, 테마별_시세_크롤링 def search(search_engine, keyword): if search_engine == '네이버 블로그': post_list = 블로그_검색(keyword) response_text = render_to_string('dialogflow/naver_blog_search_result.txt', { ...
allieus-archives/demo-20180805-startup-dev
dialogflow/actions.py
actions.py
py
937
python
ko
code
16
github-code
6
74199623228
from tkinter import messagebox from PyPDF2 import PdfReader, PdfWriter import os class TrabajarPDF: def divide_pdf(self, rutaPDF, rutaGuardar, num_pages): pdf_reader = PdfReader(rutaPDF) total_pages = len(pdf_reader.pages) for i in range(0, total_pages, num_pages): pdf_writer =...
JhostinR/emergia_projects
dividir_unir_pdf/controller/dividir_functions.py
dividir_functions.py
py
753
python
en
code
0
github-code
6
24428391900
#!/usr/bin/python3 """ sends a post request to the URL and displays the body """ import requests from sys import argv if __name__ == "__main__": url = argv[1] r = requests.get(url) if r.status_code == 200: print(r.text) else: print("Error code: {}".format(r.status_code))
Isaiah-peter/alx-higher_level_programming
0x11-python-network_1/7-error_code.py
7-error_code.py
py
305
python
en
code
0
github-code
6
70508505789
import os import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms from matplotlib import pyplot as plt from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader # progress bar from tqdm.auto import tqdm # ...
WangShengqing122090536/CSC1004-image-classification-modified
main.py
main.py
py
5,477
python
en
code
0
github-code
6
27682702748
######################################################################## # BF3Events # # There should be a class in here for every possible event in the log: # PlayerKilled # PlayerJoin # PlayerLeave # PlayerSuicide # PlayerSwitchedTeams # PlayerSwitchedSquads ###################...
Luigi30/WookParser
BF3Events.py
BF3Events.py
py
7,284
python
en
code
1
github-code
6
44399481784
import gym from collections import deque import numpy as np import time import torch torch.manual_seed(0) # set random seed import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Categorical from policy import Policy from gym.wrappers.monitoring.video_recorder...
david-wb/acrobot-v1
train.py
train.py
py
1,870
python
en
code
2
github-code
6
855819574
#!/usr/bin/env python # # This example creates a polygonal model of a cone, and then renders it to # the screen. It will rotate the cone 360 degrees and then exit. The basic # setup of source -> mapper -> actor -> renderer -> renderwindow is # typical of most VTK programs. # # # First we include the VTK Python packag...
VisTrails/VisTrails
examples/vtk_examples/Tutorial/Step1/Cone.py
Cone.py
py
2,362
python
en
code
100
github-code
6
24502025231
# Handle options """ Use the concept of optionspec from bup. Get a optionspec from subcmd, use it to parse a string of options An example of optionspec: 'scrive cmd [ -o ] --- o,option=: description ,no_short: no short name ' """ import getopt from libscrive.helpers import log class OptDict: """ options = ...
wenxin-wang/scrive
libscrive/options.py
options.py
py
3,293
python
en
code
0
github-code
6
43721480783
import numpy as np from config import * from KnowledgeSent import KnowledgeSentence from transformers import BertTokenizer, BertModel import torch hops = FLAGS.hops string_year = str(FLAGS.year) number = 0 start = FLAGS.start end = FLAGS.end if string_year == '2015': number = 3864 elif string_year == ...
Felix0161/KnowledgeEnhancedABSA
Embeddings.py
Embeddings.py
py
4,594
python
en
code
0
github-code
6
4715617180
from square.configuration import Configuration from square.client import Client from django.contrib.auth.models import User from django.conf import settings import datetime from pytz import utc as utc from django.utils import timezone from dateutil.relativedelta import relativedelta import uuid ACCESS_TOKEN = settin...
BryceTant/LabLineup
LLenv/LabLineup/app/Payment.py
Payment.py
py
4,739
python
en
code
0
github-code
6
35031048423
from celery import Celery from celery.schedules import crontab app = Celery( "vivaldi", broker_url="redis://localhost:6379/0", result_backend="redis://localhost:6379/0", imports=["tasks"], task_serializer="json", result_serializer="json", accept_content=["json"], timezone="Europe/Lisbon...
miccaldas/celery_and_friends
celery_and_friends/vivaldi/__init__.py
__init__.py
py
525
python
en
code
0
github-code
6
22457592991
import torch from transformers import BertTokenizer, BertModel, BertConfig, AdamW, BertForMaskedLM from tokenizers import ByteLevelBPETokenizer from tokenizers.implementations import ByteLevelBPETokenizer from tokenizers.processors import BertProcessing from sumerian_data import SumerianDataset from typing import...
sethbassetti/sumerian_embeddings
src/BERTmodel.py
BERTmodel.py
py
7,800
python
en
code
0
github-code
6
34712009040
# Coding Math Episode 9b # Add the acceleration and observe how it impacts velocity (speed + direction) # on the fireworks __author__ = "piquesel" import pygame import math import random from ep7 import Vector as Vector class Particle: 'Represents a particle defined by its position, velocity and direction' ...
piquesel/coding-math
ep9b.py
ep9b.py
py
1,954
python
en
code
0
github-code
6
4546238710
import cv2 from matplotlib.pyplot import contour import numpy as np import matplotlib.pyplot as plt from random import randint import matplotlib.pyplot as plt def DetectPositionMaxSkin(filename,x, y, w, h, lower, upper): #y=y+50 Image = cv2.VideoCapture(filename) #Image = cv2.VideoCaptu...
raquelpantojo/Detectskin
DetectNail.py
DetectNail.py
py
6,004
python
en
code
1
github-code
6
27828726752
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import re import arcpy import sys import traceback import tempfile import os __author__ = "Coen Jonker" class ColumnParser(object): def __init__(self): self.non_alpha_pattern = re.compile(r'[^A-Za-z0-9_]') self.ending = re.compile(r'...
wagem007/asset-management-geo
tactisch_plan_xlsx_to_feature_class.py
tactisch_plan_xlsx_to_feature_class.py
py
3,474
python
en
code
0
github-code
6
71775260987
""" Leia um valor inteiro em segundos e imprima-o em horas, minutos e segundos. """ t = int(input('Digite uma quantidade de segundos: ')) h = t / 3600 resto = t % 3600 m = resto / 60 s = resto % 60 print(f'{h} horas, {m} minutos e {s} seguntos.')
Hugolimaslv/guppe
guppe/Seção 04/48.py
48.py
py
258
python
pt
code
0
github-code
6
30353259361
from os import path import os import sys from os.path import join, dirname # Enthought library imports. from pyface.action.api import Action from traitsui.api import auto_close_message # Local imports import mayavi.api from mayavi.core.common import error from mayavi.preferences.api import preference_manager # To fi...
enthought/mayavi
mayavi/action/help.py
help.py
py
2,807
python
en
code
1,177
github-code
6
37005580941
#coding: utf-8 import tornado.web from basehandler import BaseHandler from lib.lrclib import LrcLib from lib.songinfo import SongInfo from models import MusicModel, UserModel import json import re import logging log = logging.getLogger("index") log.setLevel(logging.DEBUG) rm_regex = r"/(\([^\)]*\))|(\[[^\]]*\])|(([^)...
mgbaozi/ruankusb
handlers/index.py
index.py
py
3,525
python
en
code
0
github-code
6
15697493759
import cv2 as cv # Cargamos la imagen y transformamos en blanco y negro img_original = cv.imread("imgs/Cuadrados.jpg") img_bnw = cv.cvtColor(img_original, cv.COLOR_BGR2GRAY) # Aplicamos la funcion de deteccion de esquinas maxCorners = 20 esquinas = cv.goodFeaturesToTrack(img_bnw, maxCorners, 0.01, 10) # Definimos el...
FadedGuy/Universidad
L3/visionComputador/tp5/cuestiones/8.py
8.py
py
816
python
es
code
2
github-code
6
39425077344
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # -*- coding: utf-8 -*- # # Last modified: Fri, 14 Oct 2022 02:22:56 +0900 import numpy as np import pandas as pd import os from .measurePhenotypes import measurePhenotypes from ..util.isNotebook import isnotebook if isnotebook(): from tqdm.notebook import tq...
funalab/pyCellLineage
lineageIO/annotateLineageIdx.py
annotateLineageIdx.py
py
12,848
python
en
code
1
github-code
6
30087901686
#importing tkinter module from tkinter import * from tkinter import ttk #Creating object - root of Tk() root = Tk() #this will make a screen size root.geometry("500x500") root.configure(background="lightgreen") #Providing title to the form root.title('Registration form') #this creates 'Label' widget for...
nithish19bcs064/Best_Enlist_Assignments
day3.py
day3.py
py
2,132
python
en
code
1
github-code
6
3177305776
from flipperzero_cli import CONFIG, load_config, show_config, \ read_until_prompt, print_until_prompt, check_file_presence, \ flipper_init, main, \ storage_read, save_file, download_from_flipper, \ upload_to_flipper, check_local_md5, compare_md5 import builtins import pytest from unittest.mock import ...
nledez/flipperzero-cli
tests/test_cli.py
test_cli.py
py
14,895
python
en
code
6
github-code
6
10031616812
from PyQt4 import QtCore, QtGui from ui_fwabar import Ui_Fwabar_Dialog # create the dialog class fwabarDialog(QtGui.QDialog): def __init__(self, parent): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Fwabar_Dialog() self.ui.setupUi(self)
IGNF/SIGOPT
sigopt-mecadepi/flood_waste_assessment/tools/fwabardialog.py
fwabardialog.py
py
260
python
en
code
1
github-code
6
37314756203
import pandas as pd import sklearn import matplotlib.pyplot as plt import seaborn import load_data train = load_data.get_data()[0] testX = load_data.get_data()[1] inv_labels = load_data.get_inverted_labels() trainX = train.drop(['SalePrice'], axis = 1) trainY = train['SalePrice'] def info_discrete(column): scatt...
jantar44/reg_house_prices
house_prices/house_prices.py
house_prices.py
py
1,771
python
en
code
0
github-code
6
14790213249
# Given the head of a sorted linked list, delete all duplicates such that each element : # appears only once. Return the linked list sorted as well. # input: head = [1,1,2] # output = [1,2] class ListNode: def __init__(self, val, next): self.val = val self.next = next listNode4 = ListNode(4, None) l...
SonMichael/algorithm
linked_list_remove_duplicate_from_sorted_list.py
linked_list_remove_duplicate_from_sorted_list.py
py
807
python
en
code
0
github-code
6
17541028772
#/usr/bin/env python from pwn import * from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Cipher import AES import hashlib import os import base64 from gmpy2 import is_prime class Rng: def __init__(self, seed): self.seed = seed self.generated = b"" self.num = 0 def more_bytes(self...
cybernatedwizards/CybernatedWizardsCTF
2020/DragonCTF_2020/bitflip1/sol.py
sol.py
py
3,818
python
en
code
0
github-code
6
30543622706
import matplotlib.pyplot as plt import numpy as np plt.ion() plt.rcParams['axes.labelsize'] = 18 plt.rcParams['axes.titlesize'] = 20 plt.rcParams['font.size'] = 16 plt.rcParams['lines.linewidth'] = 2.0 plt.rcParams['lines.markersize'] = 8 plt.rcParams['legend.fontsize'] = 14 class Simulator: eps = 1e-16 def _...
liminal-learner/Chaos
Simulator.py
Simulator.py
py
14,112
python
en
code
0
github-code
6
32822098386
# coding:utf-8 from flask import request from flask import Flask, render_template from controller import search, getPage, get_suggestion import sys import json # reload(sys) # sys.setdefaultencoding('utf-8') app = Flask(__name__) @app.route('/') def index(): return "the server is running!" # return render_t...
QimingZheng/WSM-Project-WikiSearch
app/index.py
index.py
py
1,221
python
en
code
4
github-code
6