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
35658567505
#!/usr/bin/python3 import sys import socket from random import randint if len(sys.argv) < 2: print(sys.argv[0] + ": <start_ip>-<stop_ip>") sys.exit(1) def get_ips(start_ip, stop_ip): ips = [] tmp = [] for i in start_ip.split('.'): tmp.append("%02X" % int(i)) start_dec = int(''.join...
balle/python-network-hacks
reverse-dns-scanner.py
reverse-dns-scanner.py
py
1,470
python
en
code
135
github-code
13
15474913775
str2 = '8 0 0 0 0 0 0 0 1000000000' rectangles_list = list(map(int, str2.split())) stek = [] hi_dict = {} ans = 0 i = -1 for rectangle in rectangles_list: if i == -1: i += 1 continue exit_flag = False while not exit_flag: if stek: if rectangle < stek[-1][0]: ...
ougordeev/Yandex
3_A_14_gistogramm_rectangle.py
3_A_14_gistogramm_rectangle.py
py
955
python
en
code
0
github-code
13
2213068410
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_bcrypt import Bcrypt from flask_login import ( UserMixin, login_user, LoginManager, current_user, logout_user, login_required, ) import os # flask is instantiated as an app. ap...
1809mayur/EmployeeManagement
employee/__init__.py
__init__.py
py
999
python
en
code
0
github-code
13
15496713434
####The Hamming distance between two integers is the number of positions at which the corresponding bits are different. ##Given two integers x and y, calculate the Hamming distance. def hammingDistance( x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count("1") ##binary t...
Jinchili/Leetcode
Hamming_distance.py
Hamming_distance.py
py
1,649
python
en
code
0
github-code
13
70239048018
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Profile # Register your models here. @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'photo', 'company', '...
dawipo-project/dawipo
account/admin.py
admin.py
py
1,375
python
en
code
0
github-code
13
34527131880
from senate_stock_trades import util as u def count_diff(first_senator_name, second_senator_name): # integers for incrementing number of times senator name has appeared first_count_of_transaction = 0 second_count_of_transaction = 0 # Iterate through list elements for i, value in enumerate(u.g...
alyssaKsmith/Python-CourseWork
Python-Coursework/a5/senate_stock_trades/compare.py
compare.py
py
2,579
python
en
code
0
github-code
13
34049966232
import time import colors original_deck = ['\u2665 A', '\u2665 2', '\u2665 3', '\u2665 4', '\u2665 5', '\u2665 6', '\u2665 7', '\u2665 8', '\u2665 9', '\u2665 10', '\u2665 J', '\u2665 Q', '\u2665 K', '\u2666 A', '\u2666 2', '\u2666 3', '\u2666 4', '\u2666 5', '\u2666 6', '\u2666 7', '\u2666 8', '\u266...
simplysudhanshu/Cameo
playa.py
playa.py
py
3,561
python
en
code
0
github-code
13
41872454140
import nltk from nltk import sent_tokenize from nltk import word_tokenize # Link to tutorial: # https://medium.com/towards-artificial-intelligence/natural-language-processing-nlp-with-python-tutorial-for-beginners-1f54e610a1a0#7ec0 print("Please type one sentence.") sentence = input() tokenized_words = word_tokenize(s...
strinh418/quiz-maker
question_generator.py
question_generator.py
py
660
python
en
code
0
github-code
13
72301112338
import pyMeow as pm from configparser import ConfigParser class Aimbot: def __init__(self): self.config = dict() self.region = dict() self.enemy_in_fov = bool() self.paused = bool() self.colors = { "blue": pm.get_color("skyblue"), "red": ...
qb-0/pyMeow-PixelBot
main.py
main.py
py
5,099
python
en
code
2
github-code
13
23052595250
from vector import Vector a = Vector(1, 1, 1) b = Vector(6, 6, 6) k1 = a.addition(b) k2 = a.subtraction(b) k3 = a.length() k4 = a.multiplication(b) k5 = a.angle(b) k1.get() k2.get() print(k3) print(k4) print(k5)
nvovk/python
OOP/4 - Vectors/index.py
index.py
py
214
python
en
code
0
github-code
13
42508905456
from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] # Initialize the list for question in question_data: # loop through the question_data list question_text = question["text"] # text is the key-value pair at text question_answer = question["ans...
Chachenski/100-Days-of-Python
quiz-game-start/main.py
main.py
py
816
python
en
code
0
github-code
13
15409296607
programming_dictionary = { "Bug": "An error in a program that prevents the program from running as expected.", "Function": "A piece of code that you can easily call over and over again.", } # Retrieving items from dictionary. print(programming_dictionary["Bug"]) # Adding new items to dictionary. programming_d...
TylerJEShelton/100_days_of_code_python
day_009/exercises.py
exercises.py
py
3,102
python
en
code
0
github-code
13
37992809518
import AthenaPoolCnvSvc.ReadAthenaPool svcMgr.EventSelector.InputCollections= ["AOD.09897018._000001.pool.root.1"] theApp.EvtMax=100 algseq = CfgMgr.AthSequencer("AthAlgSeq") #gets a handle to the main athsequencer, for adding things to later! algseq += CfgMgr.ThinGeantTruthAlg("ThinGeantTruthAlg") from OutputStreamAt...
rushioda/PIXELVALID_athena
athena/PhysicsAnalysis/AnalysisCommon/ThinningUtils/share/jobOptions.py
jobOptions.py
py
805
python
en
code
1
github-code
13
38009207758
from AthenaCommon.AlgSequence import AlgSequence topSequence = AlgSequence() from AthenaMonitoring.AthenaMonitoringConf import AthenaMonManager def JetMonGetAxisRange(): import math from AthenaCommon.BeamFlags import jobproperties axisranges = {} # mlog.info ("Beam type and energy: %s , %s" %(job...
rushioda/PIXELVALID_athena
athena/Reconstruction/Jet/JetMonitoring/share/JetMonitoring_histoaxis.py
JetMonitoring_histoaxis.py
py
4,164
python
en
code
1
github-code
13
23275254809
import numpy as np import cv2 import socket, threading, json from cv2_utils import find_vidcapture COMMAND_PORT = 9396 DEBUG = False INSTRUCTIONS = \ """ Type Q to quit Type R to report the coordinates Double click on image to set target """ def process_image(image): """ :param image: :return: ma...
yoeriapts/ehb_robotics_delivery
cam_ctrlr.py
cam_ctrlr.py
py
8,319
python
en
code
0
github-code
13
72952739218
from transformers import AutoProcessor, AutoModel import scipy import numpy as np max_lenght = 128 processor = AutoProcessor.from_pretrained( "suno/bark", cache_dir="checkpoints/bark/processor", ) model = AutoModel.from_pretrained( "suno/bark", cache_dir="checkpoints/bark/model", # torch_dtype=torc...
andompesta/pytorch-text-to-speech
bark.py
bark.py
py
1,766
python
en
code
0
github-code
13
7296081656
# -*- coding: utf-8 -*- import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash import pandas as pd from dash.dependencies import Input, Output from django.conf import settings external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP....
JoeLopez333/django_tut2
blog/dash_app.py
dash_app.py
py
2,017
python
en
code
0
github-code
13
73282859859
import os import re import logging import pathlib from multiprocessing.dummy import Pool from PyQt5 import QtCore, QtGui from lector import sorter from lector import database # The following have to be separate try: from lector.parsers.pdf import render_pdf_page except ImportError: pass try: from lector...
BasioMeusPuga/Lector
lector/threaded.py
threaded.py
py
9,711
python
en
code
1,479
github-code
13
45466278006
import pygame as pg from parameters import PARAMS class Widget(pg.sprite.Sprite): ''' General class handling widgets. ''' def __init__(self, x, y, width, height, color, parent=None, name=""): super().__init__() self.parent = super() self.image = pg.Surface([width, height]) self.image.fill(color) self.re...
MaGnaFlo/BlackBoard
widgets.py
widgets.py
py
5,851
python
en
code
0
github-code
13
349888525
name = str(input("please enter your name: ")) score = int(input("Please enter your score: ")) if score > 69 and score <101: print ( "You got an 'A', keep it up") else: if score > 59 and score < 70: print ( "You got a 'B', keep it up") else: if score > 49 and score < 60: ...
ReroSantos/Code-Lagos
Grade system test.py
Grade system test.py
py
965
python
en
code
0
github-code
13
9098015916
import pandas as pd import datetime import smtplib import os from pandas.tseries.offsets import BDay current_path = os.getcwd() print(current_path) os.chdir(current_path) GMAIL_ID = input("Enter your Gmail ID: ") GMAIL_PSWD = input("Enter you Gmail Password: ") def sendEmail(to, sub, msg): print(f"Email to {to}...
MuhammedMusharaf007/Automatic_Birthday_wisher_MM007
wisher.py
wisher.py
py
1,316
python
en
code
2
github-code
13
41024001051
import os import torch import numpy as np import pandas as pd from typing import List from torch_geometric.data import Batch, Data from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from polymerlearn.utils import GraphDataset def get_vector( data: pd.DataFrame, prop: str =...
owencqueen/PolymerGNN
polymerlearn/utils/train_graphs.py
train_graphs.py
py
24,177
python
en
code
7
github-code
13
463785625
# 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 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
sugarlabs/Sugarizehelp
sugarizehelp.py
sugarizehelp.py
py
3,641
python
en
code
0
github-code
13
2302317339
#i/p=[1,2,3,4,5,6] #o/p=[1,2,3,6,5,4] l1=[1,2,3,4,5,6] '''b=input("entre the numbers") l1=[] l1.append(b) print(l1)''' list=[] l=0 u=len(l1) m=int((l+u)/2) for i in range(0,m): a=l1[i] list.append(a) #print(list) i=u while i>m: i=i-1 a=l1[i] list.append(a) print(list)
sneha1sneha/pgms
pROGRAMS/imp2.py
imp2.py
py
281
python
en
code
0
github-code
13
20995689443
from itertools import repeat, product from functools import partial from array import array def mandel_for(re, im, max_dist=2**6, max_iter=255): z_re, z_im = re, im for i in range(max_iter): re_sqr = z_re*z_re im_sqr = z_im*z_im if ((re_sqr + im_sqr) >= max_dist): return i ...
rotaliator/profract
profract/mandel/pure_python.py
pure_python.py
py
1,109
python
en
code
1
github-code
13
12877212948
"""Кофнфиг серверного логгера""" from logger import GetLogger LOGGER = GetLogger(logger_name='server_logger').get_logger() # отладка if __name__ == '__main__': LOGGER.critical('Критическая ошибка') LOGGER.error('Ошибка') LOGGER.debug('Отладочная информация') LOGGER.info('Информационное сообщение')
Roman-R2/telemetron_telegram_bot
services/logging_config.py
logging_config.py
py
414
python
ru
code
0
github-code
13
8048020145
import numpy as np import argparse import associate def align(model, data): """Align two trajectories using the method of Horn (closed-form). Input: model -- first trajectory (3xn) data -- second trajectory (3xn) Output: rot -- rotation matrix (3x3) trans -- translation vector (3x1) t...
Johnemad96/masters
orbslam3_docker/orbslam_modifiedFork/Datasets/evaluate_using_rgbd_paper/associate.py
associate.py
py
3,375
python
en
code
1
github-code
13
3745983738
#!/usr/bin/env python3 # # Check AppStore/GooglePlay metadata # import os import sys import glob import shutil from urllib.parse import urlparse os.chdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..")) # https://support.google.com/googleplay/android-developer/answer/9844778?visit_id=6377403034...
organicmaps/organicmaps
tools/python/check_store_metadata.py
check_store_metadata.py
py
7,989
python
en
code
7,565
github-code
13
33536119847
import matplotlib.pyplot as plt import numpy as np import scipy.ndimage as ndi import pandas as pd import random import segyio np.random.seed(1234) ''' # model tmax = 0.2 tmin = 0 xt = np.arange(0, 200) # impedance range max_guess, min_guess = 4500, 1000 max_imp, min_imp = 3000, 1500 # wavelet parameters f = 50 length ...
Sheng154/impedance_inversion
Synthetic_case_3.py
Synthetic_case_3.py
py
4,662
python
en
code
0
github-code
13
12852349387
import re import threading import pandas as pd from time import sleep from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.remote.webelement import WebElement from src.utils import get_full_path from src.model import aliexpress from s...
mobinalhassan/Aliexpress
src/get_product_description.py
get_product_description.py
py
16,931
python
en
code
0
github-code
13
7275764186
def sum_all(lst): result = 0 sum = 0 for row in range(len(lst)): for col in lst[row]: sum += col if sum == 0: result = sum return sum if __name__ == "__main__": lst = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ...
violaflora/howard-introcs
Homework 3 - Destructive:non-destructive, pass-by-value:pass-by-ref, and others/sum_all.py
sum_all.py
py
345
python
en
code
0
github-code
13
16268993604
#zscore_conflict_analyzer ''' By Collin A. O'Leary, Moss Lab, Iowa State University This script will compare the Zavg values from a final partners file of one ScanFold structure model to the conflict list generated from the ct_compare.py script The conflict list is any nt that had an alternitive structure from two ...
moss-lab/SARS-CoV-2
zscore_conflict_analyzer.py
zscore_conflict_analyzer.py
py
6,935
python
en
code
0
github-code
13
34757124192
import random, functools import numpy as np @functools.cache def targs(q): p = list(q) n = len(p) targets = [] # Loop through players for i in range(n): maxx = 0 target = 0 # Loop through potential targets for j in list(range(i)) + list(range(i+1,n)): ...
DeclanStacy/nPersonDuel
truelGeneralization3.py
truelGeneralization3.py
py
3,117
python
en
code
0
github-code
13
70458223377
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from sklearn.datasets import make_classification def get_synthetic(n_samples, n_features, n_classes, n_informative=None, n_clusters_per_class=None, flip_y=None, class_sep=None): # import numpy as np # data_x = np.zeros((n_samples, 2), dtype="float32") # data...
codeislife99/learning_to_optimize
l2o/dataset.py
dataset.py
py
1,067
python
en
code
1
github-code
13
34165786977
import jinja2 import PyRSS2Gen from aiohttp import web from markupsafe import Markup from datetime import datetime import dateutil.parser import json import settings def RunServ(serve_static = False, serve_storage = False, serve_js = False): app = App() # YanDev code g o app.router.add_get('/', pa...
dkay0670/hidens-website
site_ctrl.py
site_ctrl.py
py
5,640
python
en
code
0
github-code
13
72096934097
""" The experiment_wrapper module creates a level of abstraction between the control of actual instruments and control of the entire experiment as a whole. For example, instead of initializing each instrument on its own and then setting settings like the lock-in reference input, the initialize_instruments() function do...
jc-roth/Microwave-Transmission-Experiment
setup_control/setup_control/experiment_wrapper.py
experiment_wrapper.py
py
16,232
python
en
code
0
github-code
13
40640205301
#!/usr/bin/env python3 """ Provide a list of interferograms to compute the timeseries using the short baseline subset (SBAS) approach, with or without regularization. """ ### IMPORT MODULES --- import os import numpy as np import matplotlib.pyplot as plt from datetime import datetime from osgeo import gdal from v...
EJFielding/InsarToolkit
SBAS/SBASrz.py
SBASrz.py
py
10,332
python
en
code
4
github-code
13
35784935638
import numpy as np from datetime import datetime as dt from backports.datetime_fromisoformat import MonkeyPatch MonkeyPatch.patch_fromisoformat() MAX_PACKET_SIZE = 4096 BYTES_IN_PACKET = 1456 np.set_printoptions(threshold=np.inf,linewidth=325) class Organizer: def __init__(self, all_data, num_chirp_loops, num_rx,...
UCLA-VMG/EquiPleth
nndl/rf/organizer.py
organizer.py
py
7,749
python
en
code
6
github-code
13
17045013064
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenPublicCrowdInnerQueryModel(object): def __init__(self): self._channel = None self._crowd_id = None self._group_id = None @property def channel(self): ...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayOpenPublicCrowdInnerQueryModel.py
AlipayOpenPublicCrowdInnerQueryModel.py
py
1,822
python
en
code
241
github-code
13
73091828498
#-- class란? # ● 데이터와 데이터를 변형하는 함수를 같은 공간으로 작성 # - 메서드(Method) # - 인스턴스(Instance) # - 정보 은닉(Information Hiding) # - 추상화(Abstraction) #-- 클래스와 인스턴스 class Person: # 클래스 정의 Name = 'Default Name' # 멤버 변수 def Print(self): # 멤버 메소드 print('My Name is {0}'.format(self.Name)) p1 = Person() ...
gymcoding/learning-python
docs/#5_class/#1_basic.py
#1_basic.py
py
531
python
ko
code
1
github-code
13
23530842470
import random import json genres = ['rock', 'rap', 'metal', 'jazz', 'pop', 'country'] artists = [ 'The Beatles', 'Led Zeppelin', 'Pink Floyd', 'The Rolling Stones', 'Queen', 'AC/DC', 'Black Sabbath', 'The Who', 'Guns N\' Roses', 'Nirvana', 'Metallica', 'U2', 'The Doo...
mumichians/ner
generateExamples.py
generateExamples.py
py
8,392
python
en
code
0
github-code
13
39191998179
import time repeatInput = input("Type something for me to repeat: ") loopy = True if repeatInput == "bunny": print("You found the easter egg! Therefore, I will not print 'bunny' alot ofr times.") else: delay = input("Now, enter the time gap between repeats: ") delay = float(delay) while loopy: ...
hazlenuts/LiMega
limega.py
limega.py
py
366
python
en
code
0
github-code
13
21096672047
from setuptools import setup, find_packages req_tests = ["pytest"] req_lint = ["flake8", "flake8-docstrings"] req_etc = ["black", "isort"] req_dev = req_tests + req_lint + req_etc with open('requirements.txt', 'r') as f: install_requires = [ s for s in [ line.split('#', 1)[0].strip(' \t\n') fo...
windies21/simple_url_counter
setup.py
setup.py
py
883
python
en
code
0
github-code
13
1398663032
import pandas as pd from matplotlib import pyplot as plt import numpy as np import pandas as pd import pylab import seaborn as sns import pmdarima as pm from pmdarima.model_selection import train_test_split from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score import io from PIL import Image fro...
MomoCyann/math_model_toolkits
math_model_final_battle/第六问/湿度预测画图.py
湿度预测画图.py
py
2,708
python
en
code
0
github-code
13
25568167682
# augmenter.py # Created by abdularis on 26/03/18 import scipy.misc import numpy as np import os import argparse from tqdm import tqdm from keras.preprocessing.image import ImageDataGenerator # augmentasi data citra pada direktori 'image_dir' output ke 'output_dir' # dengan jumlah augmentasi percitra 'augment_per_im...
deepdumbo/DeepLearningCNN
preprocess/augmenter.py
augmenter.py
py
1,880
python
ta
code
0
github-code
13
36945608659
""" Imagine, you are developing a vending machine. You need to keep your vending machine state: which items are presented on which shelves, how much money inside machine to give change, how much money user inserted in current time, which purchases users made etc. You need to create a data structure for that using known...
iaramer/algorithms
python/mipt/mipt_python course/homework/hw1/vending_machine.py
vending_machine.py
py
4,205
python
en
code
0
github-code
13
73282801299
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # flake8: noqa from __future__ import unicode_literals, division, absolute_import, print_function from .compatibility_utils import PY2, text_type, bchr, bord import binascii if PY2: range = xrange from itertools impo...
BasioMeusPuga/Lector
lector/KindleUnpack/mobi_utils.py
mobi_utils.py
py
8,654
python
en
code
1,479
github-code
13
9649659596
from fastapi import HTTPException from httpx import AsyncClient class HTTPXDependency: __slots__ = "_client" def __init__(self, *, client: AsyncClient): self._client = client async def __call__(self): try: await self._client.get("https://google.com") except Exception ...
victoraugustolls/httpx-timeout
app/dependencies/httpx/dependency.py
dependency.py
py
418
python
en
code
0
github-code
13
74288237456
import numpy as np import matplotlib.pyplot as plt def canicas(coefbooleanos, estinicial): # Dimensión de la matriz n = len(coefbooleanos) # Verificación para saber si la matriz es cuadrada for fila in coefbooleanos: if len(fila) != n: print("La matriz no es cuadrad...
Cristian5124/EstadosCuanticos
EstadosCuanticos.py
EstadosCuanticos.py
py
2,401
python
es
code
1
github-code
13
38862319740
import numpy as np import torch import sys import pandas as pd import os from sklearn import preprocessing # from keras_preprocessing.text import Tokenizer import gc gene_map = { 'A': [1, 0, 0, 0], 'C': [0, 1, 0, 0], 'G': [0, 0, 1, 0], 'T': [0, 0, 0, 1], 'N': [0, 0, 0, 0], } f = p...
ZhangLab312/GHTNet
read_data.py
read_data.py
py
8,296
python
en
code
0
github-code
13
10341083646
import pandas as pd import requests import datetime # base data now = datetime.datetime.now() base_url = "https://en.wikipedia.org/wiki/Comparison_of_smartphones" data = pd.DataFrame(columns=["Model", "Brand", "SoC/Processor", "CPU Spec", "GPU", "Storage", "Removable storage", "RAM", "OS", "Custom Launcher", "Dimen...
tschaefermedia/SmartphoneDataWikipedia
src/main.py
main.py
py
1,842
python
en
code
0
github-code
13
14812856358
from flask_app import app from flask import render_template, redirect, request, session, flash from flask_app.models import order, user # Once they pay they are taken to this screen, it's their receipt. # Need to feed to the front a list of all the order items. # Takes in guest email if still not logged in @app.route(...
Sal-Nunez/marketplace_schema
flask_app/controllers/orders.py
orders.py
py
841
python
en
code
1
github-code
13
3047194371
import hashlib import random import core.tree as tree import os import core.users as users import logging import core.acl as acl from utils.utils import getMimeType, get_user_id, log_func_entry, dec_entry_log from utils.fileutils import importFile, getImportDir, importFileIntoDir from contenttypes.image import makeThum...
hibozzy/mediatum
web/edit/modules/files.py
files.py
py
12,075
python
en
code
null
github-code
13
22798976861
# -*- coding: UTF-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from core.metrics import l2_norm class BasicBlock(nn.Module): """Basic Block for resnet 18 and resnet 34 """ expansion = 1 def __init__(self, in_channels, out_channels, stride=1): super(BasicBlock, self)...
factzero/pytorch_jaguarface_examples
recognitionFace/core/resnet.py
resnet.py
py
3,323
python
en
code
2
github-code
13
4998367230
# Build the top-open-subtitles-sentences repository import os import shutil import time import zipfile import gzip import re import itertools from collections import Counter import pandas as pd import requests ############################################################################### # Settings # languages (se...
orgtre/top-open-subtitles-sentences
src/top_open_subtitles_sentences.py
top_open_subtitles_sentences.py
py
26,644
python
en
code
10
github-code
13
19905709517
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # nums.sort() #O(n)time O(1)space #trace index i = j = 0 for k in xrange(len(nums)): ...
littleliona/leetcode
medium/75.sort_colors.py
75.sort_colors.py
py
597
python
en
code
0
github-code
13
40698551405
#!/usr/bin/python # -*- coding:utf-8 -*- # python3环境 # 界面演示示例实现 安装rancher基础环境 import os import json import time import shutil import re # import io import sys # reload(sys) # sys.setdefaultencoding("utf-8") # 使用linux系统交互输入信息时, # 会出现backspace无法删除乱码的情况; # 导入readline模块可以消除这种乱码情况。 # 需要取消注释即可 # import readline # 选择项 x...
sheldon-lu/Python_all
small_tools/terminal_GUI/baseEnv.py
baseEnv.py
py
13,641
python
en
code
1
github-code
13
38197941046
#!/usr/bin/env python # coding: utf-8 # # shivani tiwari 03 # In[ ]: import matplotlib.pyplot as plt import pandas as pd import numpy as np # In[5]: df=pd.read_csv('D:/shivani tiwari/bml/placement.csv') # In[6]: df.head() plt.scatter(df['cgpa'],df['package']) # In[17]: import seaborn as sns corr=df.corr...
shivani926/ML
practical2.py
practical2.py
py
1,033
python
en
code
0
github-code
13
41642418795
# Method: Use Dynamic Programming (2D) with 1 extra row and col # TC: O(n * m) # SC: O(n * m) from typing import List class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: n, m = len(nums1), len(nums2) dp = [[float('-inf')] * (m + 1) for _ in range(n + 1)] ...
ibatulanandjp/Leetcode
#1458_MaxDotProductOfTwoSubsequences/solution1.py
solution1.py
py
696
python
en
code
1
github-code
13
21278163650
import os import sys import glob import shutil import numpy as np import scipy as sp from scipy import * import scipy.spatial import numpy.linalg as LA from numpy import cross, eye, dot from scipy.linalg import expm, norm import pandas as pd import itertools import re import time import argparse from Bio.PDB imp...
ejp-lab/EJPLab_Computational_Projects
AbInitioVO-and-FastFloppyTail/Demo_fast/PolymerDsspAnalysis.py
PolymerDsspAnalysis.py
py
22,239
python
en
code
9
github-code
13
12061449123
import math def merge_sort(srcList, sl_idx, sr_idx): if sr_idx > sl_idx: middle = (sl_idx + sr_idx) // 2 merge_sort(srcList, sl_idx, middle) merge_sort(srcList, middle + 1, sr_idx) merge(srcList, sl_idx, middle, sr_idx) def merge(srcList, l_idx, middle, r_idx): r_len = (middle ...
MurylloEx/Data-Structures-and-Algorithms
Week_3/merge_sort.py
merge_sort.py
py
648
python
en
code
0
github-code
13
23988844369
"""Este programa reliza la resta algebraica de dos imagenes, cuidando de que no haya saturación. Luego la compara con la resta obtenida por openCV.""" #se importan librerias import numpy as np import cv2 #se lee y almacena las imagenes img1 = cv2.imread("imagen1.jpg") img2 = cv2.imread("imagen2.jpg") #Se limita el ...
Atrabilis/UACH
Vision artificial/Tarea 2/P3b.py
P3b.py
py
1,571
python
es
code
1
github-code
13
11008776610
# Задание 3 # Улучшаем задачу 2. # Добавьте возможность запуска функции “угадайки” из модуля в командной строке терминала. # Строка должна принимать от 1 до 3 аргументов: параметры вызова функции. # Для преобразования строковых аргументов командной строки в числовые параметры используйте генераторное выражение. from ...
Vladimirs77nt/Python_diving
Task_06/Task_06_3.py
Task_06_3.py
py
961
python
ru
code
0
github-code
13
41977756792
import sys from typing import * import collections input=sys.stdin.readline N=int(input()) queue:Deque=collections.deque() for _ in range(N): cmd=input().split() if cmd[0]=='push': queue.append(int(cmd[1])) elif cmd[0]=='front': if len(queue)==0: print(-1) else: ...
honghyeong/python-problem-solving
BOJ/step18_queue&deque/18258.py
18258.py
py
744
python
en
code
0
github-code
13
71497023059
# 언어 : Python # 날짜 : 2021.08.24 # 문제 : BOJ > A→B(https://www.acmicpc.net/problem/16953) # 티어 : 실버 1 # ====================================================================== import heapq def solution(): queue = [[A, 1]] count = 0 while queue: node = heapq.heappop(queue) cur_num = node[0] ...
eunseo-kim/Algorithm
BOJ/최고빈출 DFS, BFS 기본문제/06_A→B.py
06_A→B.py
py
703
python
en
code
1
github-code
13
3720558050
# 내 풀이 N = int(input()) a,b = 1,1 for i in range(1,N): a,b = b,a+b print(a) ''' for문 방법 1 N = int(input()) li = [ 0 for _ in range(N) ] li[0],li[1] = 1,1 for i in range(2,N): li[i] = li[i-1] + li[i-2] print(li[N-1]) ''' ''' 재귀적 방법 - 메모이제이션 추가 활용 N = int(input()) memo = [ -1 for _ in range(N+1) ] ...
JaeEon-Ryu/Coding_test
LeeBrosCode/DP/1_ subproblem을 그대로 합치면 되는 DP/1) 피보나치 수.py
1) 피보나치 수.py
py
556
python
en
code
1
github-code
13
37914603148
import AthenaCommon.Constants as Lvl from AthenaCommon.Configurable import * from AthenaCommon import CfgMgr ### class PyComponents(object): """@c PyComponents is a placeholder where all factories for the python components will be collected and stored for easy look-up and call from the C++ side. The @...
rushioda/PIXELVALID_athena
athena/Control/AthenaPython/python/Configurables.py
Configurables.py
py
12,878
python
en
code
1
github-code
13
74844271056
import math t = int(input()) #t = 1 def reverse(n): s = 0 while(n > 0): s = s*10 + n%10 n //= 10 return s def isPrime(n): if(n < 2): return False i = 2 while(i*i <= n): if(n%i == 0): return False i += 1 return True def sumDigit(n): s...
DucAnhNg2002/SourceCode
Codeptit - Python/PY01057 - VỊ TRÍ NGUYÊN TỐ.py
PY01057 - VỊ TRÍ NGUYÊN TỐ.py
py
847
python
en
code
1
github-code
13
19975348424
from time import sleep from kivy.lib import osc from kivy.logger import Logger from service.cacher import Cacher from service.androidwrap import AndroidWrap from service.comms import Comms from jnius import autoclass from jnius import cast import os import copy # Activity related classes. JPythonActivity = autoclas...
nodegraph/youmacro
service/main.py
main.py
py
8,559
python
en
code
0
github-code
13
7318551416
import swapper from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from openwisp_users.api.mixins import FilterSerializerByOrgManaged from openwisp_utils.api.serializers import ValidatedModelSerializer from ..swapper import l...
openwisp/openwisp-firmware-upgrader
openwisp_firmware_upgrader/api/serializers.py
serializers.py
py
3,843
python
en
code
40
github-code
13
38352618546
from django.shortcuts import render from rest_framework import generics from rest_framework.views import APIView from .serializers import * from .models import * from rest_framework.decorators import api_view from django.http.response import JsonResponse # Create your views here. class CampaignView: @api_view(['...
GoyalAnuj973/Target-Marketing-Tool
TargetMarketingTools-backend/Tmarket/campaigns/views.py
views.py
py
3,865
python
en
code
0
github-code
13
3128766035
import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QVBoxLayout, QHBoxLayout, QTextEdit, QInputDialog, QMessageBox, QDialog, QDialogButtonBox, QFileDialog,QAbstractItemView, QScrollArea, QComboBox from PyQt6.QtGui impo...
mahdi-mahmoudkhani/Encyclopedia-of-Animal-Species
GUI.py
GUI.py
py
15,559
python
en
code
1
github-code
13
35296154458
from collections import defaultdict n = int(input()) a = list(map(int, input().split())) d = defaultdict(int) for i in a: d[i] += 1 d2 = sorted(d.items(), reverse=True) h = [] # 2本以上ある辺を2つ取得(大きいものから) h2 = [] # 4本以上ある(正方形を作れる)ものを1つ取得(大きいものから) for i in d2: if (len(h)==2) and (len(h)==1): break ...
nozomuorita/atcoder-workspace-python
abc/abc071/c.py
c.py
py
653
python
en
code
0
github-code
13
20097369424
#AULA 1: CONDICIONAIS IF, IDENTAÇÃO E COMO FUNCIONA IF DENTRO DE IF meta = 50000 qtde_vendas = 150000 rendimento = 0.5 preco = 1500 custo = qtde_vendas*rendimento*preco faturamento = qtde_vendas*preco if(qtde_vendas > 5*meta) | (rendimento < 0.7): print('A meta foi batida, quantidade vendida {} {}' .for...
vitoryago/Python_Studies
Aula_01_condicionais.py
Aula_01_condicionais.py
py
3,308
python
pt
code
0
github-code
13
74718340816
import inspect from dataclasses import dataclass, field from typing import Optional, Type from boto3.dynamodb.types import TypeDeserializer from marshy import ExternalType, get_default_context from marshy.marshaller.marshaller_abc import MarshallerABC from marshy.marshaller_context import MarshallerContext from marshy...
tofarr/persisty
persisty/trigger/dynamodb_post_process_event_handler.py
dynamodb_post_process_event_handler.py
py
3,122
python
en
code
1
github-code
13
6609284409
from training import get_data import networkx as nx from node2vec import Node2Vec import numpy as np import os data_dict = get_data('ml-100k') n_items = data_dict['n_items'] train_data = data_dict['train_data'] vad_data_tr = data_dict['vad_data_tr'] vad_data_te = data_dict['vad_data_te'] user_info = data_di...
e406hsy/ConditionalRaCT
setup_side_data.py
setup_side_data.py
py
2,796
python
en
code
0
github-code
13
39852694349
#!/usr/bin/env python3 """ celcius_conversion version 1.4 Python 3.7 """ def to_fahrenheit(): """Convert Celsius to Fahrenheit.""" degree_sign = "\N{DEGREE SIGN}" try: fahrenheit_convert = int(input("Enter temperature in Fahrenheit. ")) except ValueError: print("Please...
mcmxl22/Weather
celsius_conversion.py
celsius_conversion.py
py
618
python
en
code
0
github-code
13
22195268040
# Uses Python3 import time import numpy as np # The fastest O(1) def fibonacci_formula(n): phi = 0.5 * (np.sqrt(5) + 1) psi = 1 - phi #fn = round((phi**n - psi**n)/sqrt(5)) fn = int(np.round(phi ** n / np.sqrt(5))) return fn # Fastest O(n) def fibonacci_iterative(n): if n in [0,1]: return n ...
sandeeppalakkal/Algorithmic_Toolbox_UCSD_Coursera
Programming_Challenges_Solutions/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py
fibonacci.py
py
1,466
python
en
code
0
github-code
13
27970074153
import datetime import logging from .client import LumberjackClient _TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" # Logstash/Golang parsable class LumberjackHandler(logging.Handler): """ Logging handler for pushing log events Logstash """ def __init__(self, host, port): logging.Handler.__init__(self) ...
jackric/pylumberbeats
pylumberbeats/handlers.py
handlers.py
py
1,089
python
en
code
0
github-code
13
19348427692
# -*- coding: utf-8 -*- """ Created on Tue Oct 31 17:57:07 2017 @author: Julian """ from selenium import webdriver import matplotlib.pyplot as plt import re from nltk.corpus import stopwords import os import pysentiment as ps #from wordcloud import WordCloud #path_direct = os.getcwd() #os.chdir(path_direct + '/pyni...
PQJHU/DEDA_2017
DEDA_Projects/DEDA_WebScrapingAndWordFrequency/DEDA_WebScrapingAndWordFrequency.py
DEDA_WebScrapingAndWordFrequency.py
py
4,967
python
en
code
3
github-code
13
33220060986
# -*- encoding:utf-8 -*- import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def update_position(num, data, plts): x1, y1, n = data theta = np.arange(2* num *np.pi,2* (num+1)*n*np.pi,np.pi/50) x2=x1[num]+1/n * np.cos(theta * n) y2=y1[num]+1/n * np.sin(...
aarongis/pythondev
Python-learn/matplotlab/test-plot3.py
test-plot3.py
py
1,184
python
en
code
0
github-code
13
8343887866
fees = [180, 5000, 10, 600] records = ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] import math parking = [] car = [[] for _ in range(10000)] def solution(fees, records): time = dict() for i in...
rohujin97/Algorithm_Study
test/0911/PM/3.py
3.py
py
1,444
python
en
code
0
github-code
13
71083961939
prices_list = [ # before or on 15th december / after 15th december [24, 28.70], # Cake [6.66, 9.80], # Souffle [12.60, 16.98] # Baklava ] # prices are lv./pc sweet_type = input() n_sweets = int(input()) day_number = int(input()) # day in december sweet_price = 0 if sweet_type == "Cake": prices =...
bobsan42/SoftUni-Learning-42
ProgrammingBasics/17myexam/03pastryshop.py
03pastryshop.py
py
765
python
en
code
0
github-code
13
6948676324
from typing import * class Solution: def maxProfit(self, prices: List[int]) -> int: res=0 for i in range(1,len(prices)): #只要第二天比第一天多,就加上,可以买卖无数次 if prices[i]>prices[i-1]: res+=(prices[i]-prices[i-1]) return res if __name__ == '__main__': sol=Solut...
Xiaoctw/LeetCode1_python
数组/买卖股票的最佳时机2_122.py
买卖股票的最佳时机2_122.py
py
422
python
en
code
0
github-code
13
23265043575
import argparse import numpy as np import torch from detectron2 import model_zoo from detectron2.config import get_cfg from datasets.register_coco import register_coco_dataset from datasets.register_out_of_context import register_out_of_context_dataset from tasks import task_a, task_b, task_c, task_d, task_e def _p...
Atenrev/M5-Visual-Recognition
week3/main.py
main.py
py
3,112
python
en
code
0
github-code
13
559886064
import pygame from constants import * from utils import * from stack import Stack from card import Card from random import shuffle from assetloader import AssetLoader from difficulty import Difficulty class Board: instance: "Board" = None board_top = None board_main = None def quality(self): ...
quasar098/kabufuda-solitaire
board.py
board.py
py
7,992
python
en
code
2
github-code
13
20500016597
''' Quiz) 표준 체중을 구하는 프로그램을 작성하시오 *표준 체중 : 각 개인의 키에 적당한 체중 (성별에 따른 공식) 남자 : 키(m)^2 X 22 여자 : 키(m)^2 X 21 조건1 : 표준 체중은 별도의 함수 내에서 계산 *함수명 : std_weight *전달값 : 키(height), 성별(gender) 조건2 : 표준 체중은 소수점 둘째자리까지 표시 (출력 예제) 키 175cm 남자의 표준 체중은 67.38kg 입니다. ''' # 현재 BMI 지수 출력하기 # 남자와 여자 표준체중 구할...
PKTOSE/2022_1PG
HW3/source4.py
source4.py
py
1,163
python
ko
code
0
github-code
13
21553939869
from typing import List from ariadne import QueryType from resolvers.directives import AuthDirective from classes import Error QUERY = QueryType() @QUERY.field("checkMacaroon") async def r_macaroon_check(_, info, caveats: List[str]): def extract_macaroon(info): auth = info.context["request"].headers["Aut...
FeatherLightApp/FeatherLight-API
server/featherlight/resolvers/query/check_macaroon.py
check_macaroon.py
py
656
python
en
code
3
github-code
13
16755991395
"""Brauer states.""" import numpy as np from toqito.matrix_ops import tensor from toqito.perms import perfect_matchings, permute_systems from toqito.states import max_entangled def brauer(dim: int, p_val: int) -> np.ndarray: r""" Produce all Brauer states [WikBrauer]_. Produce a matrix whose columns are...
vprusso/toqito
toqito/states/brauer.py
brauer.py
py
2,375
python
en
code
118
github-code
13
72087528978
from typing import Callable import jax import jax.numpy as jnp from jax.flatten_util import ravel_pytree from newton_smoothers.base import MVNStandard, FunctionalModel from newton_smoothers.batch.utils import ( log_posterior_cost, residual_vector, block_diag_matrix, line_search_update, ) def _gauss_...
hanyas/second-order-smoothers
newton_smoothers/batch/ls_gauss_newton.py
ls_gauss_newton.py
py
2,237
python
en
code
3
github-code
13
10136003424
# encoding: utf-8 from PIL import ImageGrab import os import time import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders def screenGrab(): '''截屏保存为jpg文件''' im = ImageGrab.grab() filename = 'Screenshot_' + time.strftime('%Y%m%d...
linys1987/mycode
src/screengrab/screengrab.py
screengrab.py
py
1,145
python
en
code
0
github-code
13
25713274252
import numpy as np class DepolarizationInducedSuppressionOfExcitation_DSE: def __init__(self, num_neurons, initial_connectivity=None, excitatory_strength=0.5, depolarization_threshold=0.7, suppression_factor=0.5, min_strength=0, max_strength=1): self.num_neurons = num_neurons self.excitatory_streng...
RickysChocolateBox/artificial_brain
Neural Networks/Base Neuron Classes/Parent Neuron template Class/Inhibitory Synapse Functions/DepolarizationInducedSuppressionOfExcitation_DSE.py
DepolarizationInducedSuppressionOfExcitation_DSE.py
py
2,111
python
en
code
0
github-code
13
16048443192
from django.shortcuts import render, redirect from django.http import HttpResponse from scipy.io.wavfile import read from deepspeech import Model from django.conf import settings from django.http import JsonResponse import pandas as pd import json import io import os # paths BASE_DIR = settings.BASE_DIR DATA_DIR = se...
taufik-adinugraha/ai-quran
ayat_recog/views.py
views.py
py
3,476
python
en
code
3
github-code
13
12343818235
# program for finding maximum number of characters between two same chars # IDEA: logic is to maintain a temporary array (i don't know why i always name it as 'count') , and then initialize it as -1 so that we know we haven't seen thay char yet and the index are based on the ASCII values. Now we traverse and we check i...
souravs17031999/100dayscodingchallenge
arrays/maximum_character_between_two_same_chars.py
maximum_character_between_two_same_chars.py
py
1,609
python
en
code
43
github-code
13
1885490974
from sklearn.model_selection import cross_val_score from sklearn.metrics import accuracy_score, f1_score from joblib import dump, load from pathlib import Path import os class Model: status_completed = 'Completed' status_pending = 'Pending' status_training_model = 'Training - Fitting Model' status_training...
shinmyung0/netsec-crying-crypto
mlcode/src/model.py
model.py
py
2,966
python
en
code
0
github-code
13
21616796994
with open('demo.txt', mode='w') as f: # f.write('Add this content!\n') # file_content = f. readlines() # f.close() #user_input = input('Please enter input: ') # print(file_content) # for line in file_content: # print(line[:-1]) # line = f.readline() # while line: # prin...
javendano585/PyBlockchain
files.py
files.py
py
458
python
en
code
0
github-code
13
9248766207
import asyncio async def hello_world(): print("hello world!") await asyncio.sleep(1) return 1 async def hello_python(): print("hello Python!") await asyncio.sleep(2) return 2 event_loop = asyncio.get_event_loop() try: result = event_loop.run_until_complete(asyncio.gather( hello_py...
fuadaghazada/scaling-python
event-loops/sleep_and_gather.py
sleep_and_gather.py
py
407
python
en
code
0
github-code
13
29041474060
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = r...
javon27/sorts_analysis
heap.py
heap.py
py
1,163
python
en
code
0
github-code
13
72922406097
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ unit tests for the snp-pileup-wrapper.cwl file """ import os import sys import unittest from pluto import ( CWLFile, PlutoTestCase, OFile ) class TestConcatWithCommentsCWL(PlutoTestCase): cwl_file = CWLFile('concat_with_comments.cwl') def tes...
mskcc/pluto-cwl
tests/test_concat_with_comments_cwl.py
test_concat_with_comments_cwl.py
py
4,419
python
en
code
1
github-code
13
71076140497
import os import sys import errno import numpy as np import shutil import os.path as osp import matplotlib.pyplot as plt import scipy.io as sio import torch def mkdir_if_missing(directory): if not osp.exists(directory): try: os.makedirs(directory) except OSError as e: ...
majidseydgar/Res-CP
3-Classifications/utils.py
utils.py
py
10,219
python
en
code
40
github-code
13