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
28256315705
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox, QListWidgetItem from PyQt5.QtCore import pyqtSlot, QDir, Qt, QSettings, QFileInfo from SettingsDialog import SettingsDialog from ui_MainWindow import Ui_MainWindow import math import Settings def areaOfPolygon(vertices): verti...
claudiomattera/graph-extractor
MainWindow.py
MainWindow.py
py
6,147
python
en
code
1
github-code
6
25002494348
#author Duc Trung Nguyen #2018-01-06 #Shopify Back End Challenge from Menu import Menu import json def parse_menu(menu, py_menus): this_id = menu['id'] this_data = menu['data'] this_child = menu['child_ids'] if not 'parent_id' in menu: py_menus.append(Menu(this_id, this_data...
suphuvn/Shopify-Back-End-Challenge
Shopify Back End Challenge.py
Shopify Back End Challenge.py
py
1,426
python
en
code
0
github-code
6
20546896703
from typing import Tuple from PIL import ImageColor from PIL.ImageDraw import ImageDraw from PIL.ImageFont import FreeTypeFont from PIL import ImageFont def wrap_text(text: str, width: int, font: FreeTypeFont) -> Tuple[str, int, int]: text_lines = [] text_line = [] words = text.split() line_height =...
realmayus/imbot
image/manipulation_helper.py
manipulation_helper.py
py
3,154
python
en
code
0
github-code
6
29673725009
import flask import flask_login from flask_dance.contrib.google import make_google_blueprint, google from flask_dance.consumer import oauth_authorized import iou.config as config from iou.models import User google_blueprint = make_google_blueprint( scope=["email"], **config.googleAuth ) login_manager = flask...
komackaj/flask-iou
iou/login.py
login.py
py
1,382
python
en
code
0
github-code
6
36146924870
from PIL import Image from DiamondDash.screenshot import Capturer from DiamondDash.mouse import Mouse import time import random colors = {} C = Capturer(1048, 341) M = Mouse(1048, 341) def get_color(RGB): if all(val < 60 for val in RGB): return "B" elif RGB in colors: return colors[RGB] ...
rndczn/DiamondDashBot
brain.py
brain.py
py
5,654
python
en
code
0
github-code
6
22857897162
#!/usr/bin/env python """ Parses information from aql and outputs them to one JSON input: stdin: json aql output e.g. aql -c "SHOW SETS" -o json | head -n -3 return: JSON string [[{...], {...}]] - for each server list of stats (e.g for each set) """ import sys import json data = [] json_in...
tivvit/aerospike-tools-parsers
parse_aql.py
parse_aql.py
py
598
python
en
code
0
github-code
6
9062401747
def matrixplot(start_date,end_date,type,term,flag=True): # Configure plotting in Jupyter from matplotlib import pyplot as plt # get_ipython().run_line_magic('matplotlib', 'inline') # plt.rcParams.update({ # 'figure.figsize': (26, 15), # 'axes.spines.right': False, # 'axes.spines.left...
ljiaqi1994/Pledge-Repo
质押式回购_类别矩阵_删减mysql.py
质押式回购_类别矩阵_删减mysql.py
py
6,632
python
en
code
0
github-code
6
10543642062
from redis.commands.search.field import GeoField, NumericField, TextField, VectorField REDIS_INDEX_NAME = "benchmark" REDIS_PORT = 6380 H5_COLUMN_TYPES_MAPPING = { "int": NumericField, "int32": NumericField, "keyword": TextField, "text": TextField, "string": TextField, "str": TextField, "...
myscale/vector-db-benchmark
engine/clients/redis/config.py
config.py
py
687
python
en
code
13
github-code
6
30052420632
import csv f = open('datafromamazon.csv') csv_file = csv.reader(f) URLarray = [] for row in csv_file: URLarray.append(row[0]) filename = "urlfile.csv" f = open(filename, "w") for URL in URLarray: f.write("ProductName" + "," + "Grade" + "," + "PercentageScore" + "," + "Users" + "," + URL + "\n") f.cl...
ABoiNamedKoi/VCU-CMSC-412
csvamazonscrape.py
csvamazonscrape.py
py
327
python
en
code
0
github-code
6
24370435806
from setuptools import setup, find_packages VERSION = "0.1" DESCRIPTION = "A Lagrangian Particle Tracking package" LONG_DESCRIPTION = "Includes a set of tools for Lagrangian Particle Tracking like search, interpolation, etc." # Setting up setup( # name must match the folder name name="project-arrakis", ve...
kalagotla/project-arrakis
setup.py
setup.py
py
946
python
en
code
1
github-code
6
2831089261
import threading from time import time from time import sleep import asyncio import tornado.web import tracemalloc from hoverbotpy.controllers.constants import PORT from hoverbotpy.drivers.driver_dummy import DummyHovercraftDriver from hoverbotpy.drivers.threading_dummy import ThreadingDummy from hoverbotpy.drivers....
olincollege/hoverbois
hoverbotpy/src/hoverbotpy/controllers/web_controller.py
web_controller.py
py
5,781
python
en
code
0
github-code
6
35914573545
class Solution: def reverse(self, x: int) -> int: twoPwr31=2147483648 while x%10==0 and x!=0: x=x//10 if x==0 or x>=twoPwr31 or x<=-twoPwr31: return 0 if x<0: output = str(x)[-1:0:-1] if -int(output)<=(twoPwr31*-1): retu...
azbluem/LeetCode-Solutions
solutions/7.rev-int.py
7.rev-int.py
py
548
python
en
code
0
github-code
6
74078752188
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but ...
lalamax3d/FloorPlanCreator
__init__.py
__init__.py
py
2,177
python
en
code
0
github-code
6
39180507921
# File operation with reading each line and writing each line . ''' #First file creation and writting . fo = open ( "first31.txt ", "w") #fo=open("first.txt","r+") seq= [ "First Line \n ", "Second Line \n" , "Third Line \n" ,"Fourth Line \n " ] #,"Fifth line \n "\n,"sixth line "\n , "seventh line \n"] f...
sameerCoder/pycc_codes
file_readline_writeline.py
file_readline_writeline.py
py
719
python
en
code
2
github-code
6
170910713
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from firefox_puppeteer.base import BaseLib class ErrorTriggerer(BaseLib): def _notify_observers(self, topic, data...
RequestPolicyContinued/requestpolicy
tests/marionette/rp_puppeteer/api/error_triggerer.py
error_triggerer.py
py
743
python
en
code
253
github-code
6
40276526905
import cv2 import random import numpy as np from PIL import Image from compel import Compel import torch from diffusers import StableDiffusionInpaintPipeline, StableDiffusionUpscalePipeline from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation def seed_everything(seed): random.seed(seed) np...
Anears/SHIFT
models/shift.py
shift.py
py
4,678
python
en
code
0
github-code
6
38460841413
import pygame pygame.init() font = pygame.font.Font(pygame.font.get_default_font(), 18) class Components: def __init__(self, window: pygame.Surface) -> None: self.window = window self.buttons = list() def Button(self, name: str): text = font.render(name, False, (0, 0, 0)) rec...
legit-programmer/bit-texture
ui.py
ui.py
py
1,642
python
en
code
0
github-code
6
35161911497
from dhooks import Webhook from dhooks import Embed from datetime import date,datetime import json embed=Embed( title="Sucessful Checout!", url="https://twitter.com/_thecodingbunny?lang=en", color=65280, timestamp="now" ) hook=Webhook("https://discordapp.com/api/webhooks/715950160185786399...
1mperfectiON/TCB-Project1
fake_bot_webhook.py
fake_bot_webhook.py
py
1,445
python
en
code
0
github-code
6
4927702164
# -*- coding: utf-8 -*- import json import pickle import numpy as np import random def preprocess_train_data(): """ Convert JSON train data to pkl :param filename: :return: """ f = open('train.json', 'r') raw_data = json.load(f) f.close() def get_record(x): band_image...
wondervictor/KaggleIceberg
data/data_process.py
data_process.py
py
2,431
python
en
code
0
github-code
6
41776384713
# An ETL Reads and processes files from song_data and log_data and loads them into dimensional and fact tables #=========================================================== #Importing Libraries import os import glob import psycopg2 import pandas as pd from sql_queries import * #========================================...
Marvykalu/DataEngineering
data-modeling-postgresql/etl.py
etl.py
py
6,006
python
en
code
0
github-code
6
37983159283
from fastapi import FastAPI, Response, status,HTTPException from fastapi.params import Body from pydantic import BaseModel from typing import Optional from random import randrange app = FastAPI() class Post(BaseModel): title: str content: str published: bool = True rating: Optional[int] = None m...
RahimUllah001/FastAPI_PROJECT
main.py
main.py
py
2,278
python
en
code
0
github-code
6
40205691019
# -*- coding: utf-8 -*- import numpy as np __all__ = ["shift_cnt", ] def shift_cnt(np_arr, shift_h=None, shift_w=None): """ Shift the position of contour. Parameters ------- np_arr : np.array contour with standard numpy 2d array format shift_h : int or float shift distance in ver...
PingjunChen/pycontour
pycontour/transform/shift.py
shift.py
py
781
python
en
code
6
github-code
6
17838892540
import numpy as np import cv2 # import ipdb import opts def computeH(x1, x2): #Q2.2.1 #Compute the homography between two sets of points num_of_points = x1.shape[0] # Construct A matrix from x1 and x2 A = np.empty((2*num_of_points,9)) for i in range(num_of_points): # Form A Ai = np.array([[-x2[i,0], -x2[i,...
blakerbuchanan/computer_vision
augmented_reality/code/planarH.py
planarH.py
py
5,340
python
en
code
0
github-code
6
18659097750
from tkinter import * from tkinter import ttk from numpy import * import random root = Tk() root.title('Minesweeper') mainframe = ttk.Frame(root, padding='3 3 12 12') mainframe.grid(column=0, row=0, sticky=(N, E, W, S)) root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) difficulty = StringVa...
awero-manaxiy/minesweeper_pong
minesweeper.py
minesweeper.py
py
5,347
python
en
code
0
github-code
6
17499920257
#TODO practice mode for the ones that required 10+, or 20+ s previously #TODO prorgam to train two digits additions and subtractions from random import random from random import randint import datetime from matplotlib import pyplot as plt import pandas as pd # import numpy as np import os import mplcursors # need to in...
kouichi-c-nakamura/anzan_training
anzan.py
anzan.py
py
13,926
python
en
code
0
github-code
6
16989855842
class Occupancy: def __init__(self, occupancy_id, beginning_date_time, ending_date_time, goal, classroom, user, semester, the_class): self.id = occupancy_id self.beginning_time = beginning_date_time self.ending_time = ending_date_time self.goal = goal self.classroom = classro...
PORTUNO-SMD/portuno-api
entities/Ocupancy.py
Ocupancy.py
py
416
python
en
code
0
github-code
6
26273782966
import dataiku from birgitta import context from birgitta.dataiku.dataset import manage as dataset_manage from birgitta.dataiku.dataset.manage import schema from birgitta.dataiku.recipe import manage as recipe_manage from birgitta.recipetest import validate def test_recipe(spark_session, scenario, ...
telia-oss/birgitta
birgitta/dataiku/recipetest/scenariotest.py
scenariotest.py
py
5,911
python
en
code
13
github-code
6
8592665762
from django.urls import path from App import views from django.urls import path from django.contrib.auth import views as g urlpatterns = [ path('',views.home,name="hm"), path('abt/',views.about,name="ab"), path('ap/',views.products,name="pro"), path('vege/',views.vegetables,name="veg"), path('fru/',views.fruits,n...
TataTejaswini/Django-Project
App/urls.py
urls.py
py
831
python
en
code
0
github-code
6
74557703866
from django.shortcuts import render, redirect, get_object_or_404 from board.models import Post, Comment from board.forms import PostForm, SignupForm, CommentForm from django.http import HttpResponse from django.contrib.auth.models import User from django.views.generic import TemplateView, ListView from django.utils i...
Xiorc/Concofreeboard
board/views.py
views.py
py
3,289
python
en
code
0
github-code
6
14550843664
import pytest from single_number import Solution from typing import List @pytest.mark.parametrize( 'nums, expected', [ ([2, 2, 1], 1), ([4, 1, 2, 1, 2], 4), ([1], 1), ] ) def test_single_number(nums: List[int], expected: int): solution = Solution() assert expected == soluti...
franciscoalface/leet-code
src/136.single_number/test_single_number.py
test_single_number.py
py
343
python
en
code
0
github-code
6
74118711867
#!/usr/bin/env python3 """ test_utils.py contains the tests for the functions in the utils.py file defined in the current directory """ from parameterized import parameterized from utils import access_nested_map, get_json, memoize from unittest.mock import patch, Mock import unittest class TestAccessNestedMap(unitte...
PC-Ngumoha/alx-backend-python
0x03-Unittests_and_integration_tests/test_utils.py
test_utils.py
py
2,308
python
en
code
0
github-code
6
29195553298
""" Title: Explicit finger tapping sequence learning task [replication of Walker et al. 2002] Author: Julia Wood, the University of Queensland, Australia Code adapted from Tom Hardwicke's finger tapping task code: https://github.com/TomHardwicke/finger-tapping-task Developed in Psychopy v2022.1.1 See my GitHub for furt...
jrwood21/sleep_tacs_study_jw_gh
finger_tapping_task_jw.py
finger_tapping_task_jw.py
py
36,526
python
en
code
1
github-code
6
74492658106
import random import string ALVO = "H0000" CARACTERES = string.ascii_letters + string.digits + " !@#$%^&*()_+-=[]{}|;:,.<>?/" # Conjunto ampliado TAMANHO_POPULACAO = 2000 TAXA_MUTACAO = 0.01 # Adjust the mutation rate as needed LIMITE_GERACOES = 6000 TAMANHO_TORNEIO = 1 # Tamanho do torneio para a seleção...
Parish71/Genetic
tournament.test.py
tournament.test.py
py
2,417
python
pt
code
0
github-code
6
30414879190
"""SQLAlchemy models for quiz and quiz questions""" from datetime import datetime from models.model import db from models.quiz_attempt import QuestionAttempt import sys sys.path.append('../') from generator.generator import create_quiz def search_slug(context): """Turns the plant slug into a string suitable for ...
lauramoon/capstone-1
models/quiz.py
quiz.py
py
3,101
python
en
code
0
github-code
6
3709153796
# # @lc app=leetcode.cn id=155 lang=python3 # # [155] 最小栈 # class MinStack: #漫画最小栈 https://zhuanlan.zhihu.com/p/31958400 def __init__(self): """ initialize your data structure here. """ self.stack=[] #按顺序记录最小栈中最小元素,备胎。配合完成取最小值时间复杂度为O(1) self.tmp=[] self.i...
chinasilva/MY_LEET_CODE
155.最小栈.py
155.最小栈.py
py
1,585
python
en
code
0
github-code
6
30953530170
import os def euclide_etendu(e, phi_n): global d d = 1 temp = (e*d)%phiden while temp != 1 : d = d + 1 temp = (e*d)%phiden return d def pgcd(a,b): # L'algo PGCD while a != b: if a > b: a = a - b else: b = b - a ...
MrGaming15/decrypt
index1.py
index1.py
py
3,380
python
fr
code
0
github-code
6
35126198992
from unittest.mock import patch from uuid import UUID, uuid4 import pytest from pasqal_cloud import SDK, Workload from pasqal_cloud.errors import ( WorkloadCancellingError, WorkloadCreationError, WorkloadFetchingError, WorkloadResultsDecodeError, ) from tests.test_doubles.authentication import FakeAut...
pasqal-io/pasqal-cloud
tests/test_workload.py
test_workload.py
py
6,862
python
en
code
11
github-code
6
37136495284
from keras.engine.saving import load_model from argparse import ArgumentParser import utils def build_parser(): par = ArgumentParser() par.add_argument('--word_features_path', type=str, dest='word_features_path', help='filepath to save/load word features', default='feature_word') par...
cindyyao/image_search
index.py
index.py
py
2,983
python
en
code
0
github-code
6
71191637947
# Copyright (c) 2012 Marc-Andre Decoste. All rights reserved. # Use of this source code is governed by an Appache 2.0 license that can be # found in the LICENSE file. import base import entities # The Birth event marks the begining of the life of a Person at its birth place. class Birth(base.Events): def...
madecoste/livesovertime
src/models/events.py
events.py
py
2,837
python
en
code
0
github-code
6
75113975226
from timeit import default_timer as timer directions = { "^": (0,1), "v": (0,-1), ">": (1,0), "<": (-1,0) } def add(a, b): return (a[0] + b[0], a[1] + b[1]) start = timer() file = open('input.txt') seen = {(0,0)} santa = (0,0) robo = (0,0) flip = False result = 1 for move in file.readlines()[0]: direction = d...
kmckenna525/advent-of-code
2015/day03/part2.py
part2.py
py
636
python
en
code
2
github-code
6
14582545322
# Visualisation of Parkes beam pattern: Shows position of beams for a given HDF file # Input: fname (location of HDF dataset) # V.A. Moss (vmoss.astro@gmail.com) __author__ = "V.A. Moss" __date__ = "$18-sep-2018 17:00:00$" __version__ = "0.1" import os import sys import tables as tb import numpy as np from matplotli...
cosmicpudding/ParkesBeamPattern
plot_beampattern.py
plot_beampattern.py
py
4,867
python
en
code
0
github-code
6
29999440972
class Config: def __init__(self): self.name='' self.description='' self.options=[] self.persistent=False self.config_file='' self.config_directory='' class Option: def __init__(self): self.name='' self.description='' self.default_value=''...
userwiths/file-tagger
core/config.py
config.py
py
894
python
en
code
0
github-code
6
2908163256
from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List, Union from supertokens_python.normalised_url_path import NormalisedURLPath from supertokens_python.querier import Querier if TYPE_CHECKING: from .utils import JWTConfig from .interfaces import CreateJwtResult from super...
starbillion/supertokens_python
supertokens_python/recipe/jwt/recipe_implementation.py
recipe_implementation.py
py
2,016
python
en
code
0
github-code
6
75341512506
"""Script to run antsBrainExtraction on meningioma T1-contrast data. """ import os.path as op from nipype import Node, Workflow, DataGrabber, DataSink, MapNode from nipype.interfaces import ants # Node to grab data. grab = Node(DataGrabber(outfields=['t1c']), name='grabber') grab.inputs.base_directory = op.abspath('da...
kaczmarj/meningioma
scripts/run_ants_brainextraction.py
run_ants_brainextraction.py
py
1,750
python
en
code
1
github-code
6
5423305185
''' @author:KongWeiKun @file: follower_crawler.py @time: 18-2-13 下午3:57 @contact: 836242657@qq.com ''' from multiprocessing import Pool,cpu_count,Lock,Manager import pandas as pd import threading import csv import requests from bs4 import BeautifulSoup import re try: from functools import namedtuple except: fro...
Winniekun/spider
github/follower_crawler.py
follower_crawler.py
py
4,422
python
en
code
139
github-code
6
38046142992
from cffi import FFI as _FFI import numpy as _np import glob as _glob import os as _os __all__ = ['BloscWrapper'] class BloscWrapper: def __init__(self, plugin_file=""): this_module_dir = _os.path.dirname(_os.path.realpath(__file__)) # find the C library by climbing the directory tree ...
ActivisionGameScience/ags_example_py_wrapper
ags_py_blosc_wrapper.py
ags_py_blosc_wrapper.py
py
4,277
python
en
code
3
github-code
6
69958393149
import typing as T import asyncio import logging import inspect from functools import lru_cache from . import types from . import transport as _transport from . import errors from . import stub from . import utils from . import spec logger = logging.getLogger('pjrpc.server') class Service: """Receive request, r...
magiskboy/pjrpc
pjrpc/core.py
core.py
py
4,436
python
en
code
0
github-code
6
70767464828
"""empty message Revision ID: 4fa0d71e3598 Revises: bdcfc99aeebf Create Date: 2021-07-31 23:47:02.420096 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '4fa0d71e3598' down_revision = 'bdcfc99aeebf' branch_labels = None...
AbundantSalmon/judo-techniques-bot
judo_techniques_bot/migrations/versions/2021-07-31_4fa0d71e3598_.py
2021-07-31_4fa0d71e3598_.py
py
891
python
en
code
8
github-code
6
22656887021
import os import sys import pandas as pd def programName(): return os.path.basename(sys.argv[0]) if len(sys.argv) == 1: pileup = sys.stdin elif len(sys.argv) == 2: pileup = open(sys.argv[1], "rt") else: exit(f"{programName()} [pileup file]\n") # THE COLUMNS IN THE MPILEUP OUTPUT ARE AS FOLLOWS # ...
ReddyLab/bird-workflow
01_mpileups/ref_counts/ref_counts.py
ref_counts.py
py
1,466
python
en
code
0
github-code
6
17012330786
from flask import Flask, render_template, request, redirect, url_for from pymongo import MongoClient client = MongoClient( "<mongo db cluter url>") NameListDatabase = client.NameListDatabase CollectionList = NameListDatabase.CollectionList app = Flask(__name__) def getallnames(): namelist = [] names = C...
smartkeerthi/Python-MongoDB-Flask-Projects
Flask and pymongo/main.py
main.py
py
953
python
en
code
0
github-code
6
24370481536
import unittest class TestDataIO(unittest.TestCase): def test_dataio(self): from src.io.dataio import DataIO from src.io.plot3dio import GridIO, FlowIO # grid object grid = GridIO('../data/shocks/shock_test.sb.sp.x') grid.read_grid() grid.compute_metrics() ...
kalagotla/project-arrakis
test/test_dataio.py
test_dataio.py
py
940
python
en
code
1
github-code
6
37446552709
from metux.util.task import Task from os import environ from copy import copy from subprocess import call """build for apt (docker-buildpackage)""" class PkgBuildAptTask(Task): """[private]""" def __init__(self, param): Task.__init__(self, param) self.target = param['target'] self.co...
LibreZimbra/librezimbra
deb_autopkg/tasks/pkg_build_apt.py
pkg_build_apt.py
py
1,455
python
en
code
4
github-code
6
24506022571
from mock import Mock, patch, ANY, sentinel from nose.tools import ok_, eq_, raises, timed from noderunner.client import Client, Context, Handle from noderunner.connection import Connection from noderunner.protocol import Protocol class TestClient(object): @patch("noderunner.client.get_sockets") @patch("node...
williamhogman/noderunner
tests/test_client.py
test_client.py
py
5,456
python
en
code
6
github-code
6
44648575716
from flask_restful import Resource, reqparse from flask_jwt import jwt_required from models.item import ItemModel class Item(Resource): parser = reqparse.RequestParser() # Just to get required key values (so that they cannot change name) parser.add_argument('price', type=float, required=True, help="This fie...
kgunda2493/test-api
resources/item.py
item.py
py
2,774
python
en
code
0
github-code
6
36229561780
from typing import List ''' 452. 用最少数量的箭引爆气球 https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/ 每一箭射穿的气球满足:最左边的气球右端在最右边气球左端的右面。 可以贪心,按照气球右端排序 记录新开的一箭的气球的右端点end,一旦有一个气球的左端点在end右面,则这一箭已经射不到这个气球了,需要新的一箭。 ''' class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: poi...
z-w-wang/Leetcode-Problemlist
CS-Notes/Greedy/452.py
452.py
py
806
python
zh
code
3
github-code
6
73706384186
#https://en.wikipedia.org/wiki/UPGMA#Working_example def findMinValue(matrix): min = float('inf') node1 = 0 node2 = 0 n = len(matrix) for i in range(n-1): for j in range(i+1,n): if min > matrix[i][j]: min = matrix[i][j] node1 = i ...
haozeyu24/pythonCodeExamples
UPGMA.py
UPGMA.py
py
4,249
python
en
code
0
github-code
6
72489561467
import pdb import sys sys.path.append( '..' ) from copy import copy, deepcopy import kivy.graphics as kg from kivy.lang import Builder from kivy.properties import * from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label #KV Lang files from pkg_resources import resource_filename path = resource_fil...
curzel-it/kivy-material-ui
material_ui/flatui/labels.py
labels.py
py
4,448
python
en
code
67
github-code
6
13502913819
import random import time import asyncio def timer(func): def _wrapper(*args): print(time.ctime()) func(*args) print(time.ctime()) return _wrapper @timer def insert_sort(sequence): i = 1 while i < len(sequence): if sequence[i] < sequence[i-1]: d = sequence[...
owhz/SimpleDataStructure
sort.py
sort.py
py
2,564
python
en
code
0
github-code
6
13295958598
import vtk import numpy as np import struct # def save_vf(self, filename): # """ Write the vector field as .vf file format to disk. """ # if not np.unique(self.resolution).size == 1: # raise ValueError("Vectorfield resolution must be the same for X, Y, Z when exporting to Unity3D.") # ...
maysie0110/COSC6344-FinalProject
write_raw_file.py
write_raw_file.py
py
2,862
python
en
code
0
github-code
6
12061356200
import tweepy from textblob import TextBlob consumer_key = 'EjXTChxrOmEWULyuuJ8iDXdyQ' consumer_secret = 'NrtHvELXi0i6dtue39icLkrT3rrrUVHKWOlHWWGJm46LQGell5' access_token = '1425159876-T5yoGiyxFk2sAdsZNjGVLRa94988APPcV4TI7R6' access_token_secret = 'JsCnvZPbnn93qefEM187dPnUcdCn5pby220IiU3D1aKam' auth =tweepy.OAuthHan...
HirdyaNegi/Senti2weet
test.py
test.py
py
803
python
en
code
0
github-code
6
32907694123
# 1 Add the usual reports from sklearn.metrics import classification_report y_true = [1, 0, 0, 2, 1, 0, 3, 3, 3] y_pred = [1, 1, 0, 2, 1, 0, 1, 3, 3] target_names = ['Class-0', 'Class-1', 'Class-2', 'Class-3'] print(classification_report(y_true, y_pred, target_names=target_names)) # 2 Run the code and see # Instead of...
IbrahimOued/Python-Machine-Learning-cookbook
2 Constructing a Classifier/performance_report.py
performance_report.py
py
447
python
en
code
0
github-code
6
41550521554
""" Send a restart signal to a BiblioPixel process running on this machine. DEPRECATED: use .. code-block:: bash $ kill -hup `bpa-pid` """ DESCRIPTION = """ Example: ``$ bp restart`` """ from .. util.signal_handler import make_command add_arguments, run = make_command('SIGHUP', ' Default SIGHUP restarts bp....
ManiacalLabs/BiblioPixel
bibliopixel/commands/restart.py
restart.py
py
323
python
en
code
263
github-code
6
74337793468
# Name : Jiazhao Li Unique name: jiazhaol import numpy as np from sklearn import preprocessing import sys from sklearn import tree def load_train_data(filename): SBD_traindata_list = [] with open(filename, 'r') as f: for line in f: line = line.strip('\n') word = line.split(' '...
JiazhaoLi/Assignment
EECS595/Assignment1/hw1/SBD.py
SBD.py
py
5,015
python
en
code
0
github-code
6
39399051547
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd import numpy as np '''create DataFrame DataFrame 数据桢,数据表,;类似于excel 特点: 1. 他是Series的集合 2. 与Series的区别: 2.1 series吧通过自定义index,当做标记,实现行,一维列表 2.2 DataFrame通过在'吧自定义index当做标记实现行'上与Series是一致, 2.3 DataFrame 除了行以外,还提供了columns(列), 每一列都是一个Series,所以Dat...
xiongliyu/practice_python
pandas/create_dateframe.py
create_dateframe.py
py
1,599
python
zh
code
0
github-code
6
3361019377
""" 222. 完全二叉树的节点个数 给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。 完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。 输入:root = [1,2,3,4,5,6] 输出:6 """ # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = lef...
ustcjiajing/python_test
count_nodes.py
count_nodes.py
py
1,198
python
zh
code
0
github-code
6
15551833066
''' Given two strings s and t, check if s is a subsequence of t. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec"...
ojhaanshu87/LeetCode
392_is_subseqence.py
392_is_subseqence.py
py
1,014
python
en
code
1
github-code
6
27035685049
"""Json module""" import json def handler(event, _context): """ Lambda Handler Parameters ---------- event : dict An event Returns ------- dict The response object """ print(f"request: {json.dumps(event)}") return { "statusCode": 200, "heade...
jhonrocha/aws-cdk-explorations
lambda/play-py/main.py
main.py
py
464
python
en
code
0
github-code
6
30848964562
import math n=int(input("")) ar = list(map(int, input().strip().split(' '))) ar.sort() ar.reverse() s4=0 s3=0 s2=0 s1=0 taxi =0 for i in ar: if(i==4): s4=s4+1 elif(i==3): s3=s3+1 elif(i==2): s2=s2+1 else: s1=s1+1 taxi = taxi+s4 if(s2%2 == 0): taxi=taxi + s...
YashTelkhade/Codeforces-solution
Taxi.py
Taxi.py
py
502
python
en
code
1
github-code
6
32927804563
#!/usr/bin/python # -*- coding: utf-8 -*- """ Construct templates and categories for Tekniska museet data. """ from collections import OrderedDict import os.path import csv import pywikibot import batchupload.listscraper as listscraper import batchupload.common as common import batchupload.helpers as helpers from bat...
Vesihiisi/TEKM-import
info_tekniska.py
info_tekniska.py
py
8,639
python
en
code
0
github-code
6
73041455547
from queue import Queue class AdjacentMatrixGraph: def __init__(self, edges, vertexList=None): self.edges = edges self.vertexList = vertexList def eachVertexesMinDist(self): size = len(self.edges) dist = [[float('inf') for i in range(0, size)] for j in range(0,size)] ...
diojin/doodles-python
src/algorithm/data_structure/graph.py
graph.py
py
10,178
python
en
code
0
github-code
6
41766786793
from collections import deque s = input().split() n = int(s[0]) m = int(s[1]) a = list(map(int, input().split())) result = ['0']*m d = {} for i in range(m): c = None if a[i] in d: c = d[a[i]] else: c = deque() d[a[i]] = c c.append(i) while True: found = ...
gautambp/codeforces
1100-B/1100-B-48361896.py
1100-B-48361896.py
py
626
python
en
code
0
github-code
6
12198804557
from iskanje_v_sirino import Graph import collections import winsound duration = 3000 freq = 440 ''' NxP_start = [ ['', '', '', '', ''], ['', '', '', '', ''], ['B', '', '', '', ''], ['A', 'C', 'D', 'E', 'F'] ] NxP_end = [ ['', 'C', '', '', ''], ['', 'E', '', '', ''], ['F', 'D', '', '', ''...
martin0b101/UI
robotizirano_skladisce.py
robotizirano_skladisce.py
py
3,070
python
en
code
0
github-code
6
72066928509
from flask import Flask, flash, redirect, render_template from form import LoginForm app = Flask(__name__) app.config['SECRET_KEY'] = "secret" @app.route("/home") def home(): return "Hello Mines ParisTech" @app.route("/", methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submi...
basileMarchand/ProgrammeCooperants
flask_demo/demo5/app.py
app.py
py
754
python
en
code
1
github-code
6
37583094466
import pyvista as pv axes = pv.Axes() axes.origin # Expected: ## (0.0, 0.0, 0.0) # # Set the origin of the camera. # axes.origin = (2.0, 1.0, 1.0) axes.origin # Expected: ## (2.0, 1.0, 1.0)
pyvista/pyvista-docs
version/dev/api/plotting/_autosummary/pyvista-Axes-origin-1.py
pyvista-Axes-origin-1.py
py
190
python
en
code
1
github-code
6
6923445505
def solve(data, rope): v = [[0, 0] for _ in range(rope)] st = set() for line in data.splitlines(): act, step = line.split(' ') for _ in range(int(step)): if act == "D": v[0][1] += 1 elif act == "U": v[0][1] -= 1 elif act == ...
eglantine-shell/adventofcode
2022/py/day9.py
day9.py
py
1,058
python
en
code
0
github-code
6
11317226884
import pathlib from setuptools import find_packages, setup import codecs import os.path def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), 'r') as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlin...
nlp-uoregon/trankit
setup.py
setup.py
py
2,223
python
en
code
693
github-code
6
27317069924
import os import re file_list = [] check = os.listdir('G:/flag/flag/') ret = r'((flag|key|ctf){.*})' for i in check: with open('G:/flag/flag/'+i,'r',encoding='utf-8') as f: a = f.read() res = re.findall(ret,a) if res: print('*'*66) print('[+]file_name: '+i)...
vFREE-1/timu_py
海量的TXT.py
海量的TXT.py
py
580
python
en
code
0
github-code
6
17763553641
#from given set of change coint{} of size m, find minimum coins required to pay amount n import sys def getMinCoins(coins,m,n): #create array of 1D to store minimum count of coins for sum 0 to n and initialize with max value table = [sys.maxsize] * (n+1) #for sum 0, 0 coins required therefore assign ...
aparna0/competitive-programs
14coin change probems/2find minimum coins.py
2find minimum coins.py
py
1,101
python
en
code
0
github-code
6
33561062837
""" moving_avg_demo.py """ import numpy as np import scipy as sp import scipy.signal import plot import signal_generator def moving_average_builder(length): filt = np.array([1.0/length]*length) return filt def moving_average_demo1(): filt = moving_average_builder(5) sig = signal_generator.sinusoid(1...
Chris93Hall/filtering_presentation
moving_avg_demo.py
moving_avg_demo.py
py
730
python
en
code
0
github-code
6
42818754446
from tkinter import * from PIL import ImageTk, Image import string import random root = Tk() root.title("Я люблю BRAWL STARS") root.geometry("1200x675") def clicked(): exit = "" for j in range(3): n = 5 letters = 0 integers = 0 for i in range(n): if ...
nelyuboov/Lab-4
main (2).py
main (2).py
py
1,483
python
en
code
null
github-code
6
70128470908
# 1.парсим; headers берём из бразуера консоли разработчика (Network->Request) # 2.сохраняем локально в файл # 3.работаем с локальными данными import json import requests from bs4 import BeautifulSoup import csv from time import sleep import random import local_properties as lp url = lp.HEALTH_DIET_URL headers = { ...
ildar2244/EdScraping
health_diet.py
health_diet.py
py
6,067
python
en
code
0
github-code
6
27615694777
""" Get information about how many adult movies/series etc. there are per region. Get the top 100 of them from the region with the biggest count to the region with the smallest one. Получите информацию о том, сколько фильмов/сериалов для взрослых и т. д. есть на область, край. Получите 100 лучших из них из региона с н...
Tetyana83/spark
task5.py
task5.py
py
4,199
python
en
code
0
github-code
6
28315455311
from typing import Union, Tuple import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np from gym import Env from gym.spaces import Box from ..agent import Agent from . import ReplayBuffer from .actor import Actor from .critic import Critic from .polyak_update ...
schobbejak/QMIX-Active-Wake-Control
agent/deep/td3.py
td3.py
py
6,983
python
en
code
1
github-code
6
41086983441
import sys max = 1000001 N = int(sys.stdin.readline()) dp = [1000000000] * max dp[1] = 0 for i in range(1, N): dp[i+1] = min(dp[i+1], dp[i]+1) if(i*2 < max): dp[i*2] = min(dp[i*2], dp[i]+1) if(i*3 < max): dp[i*3] = min(dp[i*3], dp[i]+1) print(dp[N])
Ahyun0326/Algorithm_study
dp/1로 만들기.py
1로 만들기.py
py
281
python
en
code
0
github-code
6
5390280053
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None preOrder = [1,2,4,7,3,5,6,8] midOrder = [4,7,2,1,5,3,8,6] def BuildTree(preOrder,midOrder): if len(preOrder) != len(midOrder) or len(preOrder) == 0: return if len(preOrder) == len...
JarvisFei/leetcode
剑指offer代码/数据结构/面试题7:重建二叉树.py
面试题7:重建二叉树.py
py
1,406
python
en
code
0
github-code
6
26436874912
#mandelbrot by KB for CS550 #inspired by work done with wikipedia example code from PIL import Image import random from PIL import ImageFilter #set image size imgx = 500 imgy = 500 xa, xb = -0.75029467235117, -0.7478726919928045 ya, yb = 0.06084172052354717, 0.06326370066585434 image = Image.new("RGB",(imgx,imgy)) ...
gbroady19/CS550
mandelbrot2.py
mandelbrot2.py
py
1,058
python
en
code
0
github-code
6
10543655506
from datetime import datetime, time, timedelta import iso8601 import logging import pytz import requests import sys from django.conf import settings from django.core.cache import cache from django.shortcuts import render logger = logging.getLogger(__name__) uk_tz = pytz.timezone('Europe/London') utc_tz = pytz.utc ...
SmartCambridge/tfc_web
tfc_web/smartpanel/views/widgets/rss_reader.py
rss_reader.py
py
2,242
python
en
code
3
github-code
6
14493893608
# -*- coding: utf-8 -*- # ''' -------------------------------------------------------------------------- # File Name: PATH_ROOT/train.py # Author: JunJie Ren # Version: v1.0 # Created: 2021/06/14 # Description: — — — — — — — — — — — — — — — — — — — — — — — — — — — ...
jjRen-xd/PyOneDark_Qt_GUI
app/train.py
train.py
py
9,258
python
en
code
2
github-code
6
6178538714
""" Implement class ``SkyDictionary``, useful for marginalizing over sky location. """ import collections import itertools import numpy as np import scipy.signal from scipy.stats import qmc from cogwheel import gw_utils from cogwheel import utils class SkyDictionary(utils.JSONMixin): """ Given a network of d...
2lambda123/cogwheel1
cogwheel/likelihood/marginalization/skydict.py
skydict.py
py
7,143
python
en
code
0
github-code
6
20823393672
from flask import Flask, render_template, request, redirect, session, flash from mysqlconnection import MySQLConnector import re, md5 app = Flask(__name__) app.secret_key = "MySessionSecretKey1" mysql = MySQLConnector( app, "the_wall") email_regex = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.rou...
ruslanvs/The_Wall
server.py
server.py
py
5,933
python
en
code
0
github-code
6
43370134393
""" Tests for :module:`statics.markdown`.""" import unittest __all__ = ["TestMarkdownItem"] class TestMarkdownItem(unittest.TestCase): def createFile(self, content): import tempfile f = tempfile.NamedTemporaryFile() f.write(content) f.flush() return f def test_it(se...
andreypopp/statics
statics/tests/test_markdown.py
test_markdown.py
py
1,089
python
en
code
2
github-code
6
44844122583
import torch import numpy as np class KBinsDiscretizer: # simplified and modified version of KBinsDiscretizer from sklearn, see: # https://github.com/scikit-learn/scikit-learn/blob/7e1e6d09b/sklearn/preprocessing/_discretization.py#L21 def __init__(self, dataset, num_bins=100, strategy="uniform"): ...
Howuhh/faster-trajectory-transformer
trajectory/utils/discretization.py
discretization.py
py
3,344
python
en
code
90
github-code
6
70994868668
from django import template register = template.Library() #background: -webkit-gradient(linear, 0% 0%, 0% 100%, from({{ COLOR_H1_BACK_STOP }}), to({{ COLOR_H1_BACK_START }})); #background: -webkit-linear-gradient(top, {{ COLOR_H1_BACK_START }}, {{ COLOR_H1_BACK_STOP }}); #background: -moz-linear-gradient(top, {{ CO...
chiara-paci/santaclara-css
santaclara_css/templatetags/css_tags.py
css_tags.py
py
3,207
python
en
code
0
github-code
6
27924886180
#код с регуляркой, присваивающий 0/1 в зависимости от динамики эпидемситуации import re import json import os dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'Covid_dict.json') countgooddyn = 0 countbaddyn = 0 sample_json = '' with open("data1.json", "r", encoding="utf-8") as file: ...
stefikh/map_COVID
code/4_dynamic_good_or_bad.py
4_dynamic_good_or_bad.py
py
1,709
python
ru
code
1
github-code
6
25170385254
# Django imports from django.shortcuts import render, get_object_or_404 from django.db.models import Q # Folder imports from .utils.sky import quick_flight_search from .models import * from apps.authentication.models import Profile from apps.trips.models import * # Other imports from datetime import datetime, date, tim...
sc19jwh/COMP3931
apps/flights/views.py
views.py
py
6,392
python
en
code
0
github-code
6
73831992187
import os os.environ['OPENCV_IO_MAX_IMAGE_PIXELS'] = pow(2, 40).__str__() import sys import copy from pathlib import Path from collections import Counter import numpy as np import pandas as pd import cv2 import bioformats.formatreader import cellprofiler_core.pipeline import cellprofiler_core.preferences import cell...
BGI-Qingdao/4D-BioReconX
Preprocess/cellsegmentation/objseg.py
objseg.py
py
19,716
python
en
code
4
github-code
6
17815024172
#!/usr/bin/env python3 """Tool to update Conan dependencies to the latest""" import argparse import json import os import re import subprocess def main(): """ Read Conan dependencies, look for updates, and update the conanfile.py with updates """ parser = argparse.ArgumentParser() parser.add_arg...
ssrobins/tools
update_conan_packages.py
update_conan_packages.py
py
2,066
python
en
code
0
github-code
6
25125596863
# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». # В рамках класса реализовать два метода. Первый, с декоратором @classmethod. Он должен извлекать число, месяц, год и # преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, долже...
RombosK/GB_1824
Kopanev_Roman_DZ_11/dz_11_1.py
dz_11_1.py
py
1,983
python
ru
code
0
github-code
6
41533682153
class Solution: def minStartValue(self, nums: List[int]) -> int: for i in range(1,len(nums)): nums[i]=nums[i] +nums[i-1] if min(nums)<0: startValue=-1*(min(nums)) +1 return startValue else: return 1
dani7514/Competitive-Programming-
1413-minimum-value-to-get-positive-step-by-step-sum/1413-minimum-value-to-get-positive-step-by-step-sum.py
1413-minimum-value-to-get-positive-step-by-step-sum.py
py
283
python
en
code
0
github-code
6
6501962901
from flask import request from mobile_endpoint.backends.manager import get_dao from mobile_endpoint.case.case_processing import process_cases_in_form from mobile_endpoint.extensions import requires_auth from mobile_endpoint.form.form_processing import create_xform, get_instance_and_attachments, get_request_metadata f...
dimagi/mobile-endpoint
prototype/mobile_endpoint/views/receiver.py
receiver.py
py
1,434
python
en
code
0
github-code
6