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
12258827784
import pprint grid = [ [1, 0, 0, 0, 4, 0, 0, 0, 0], [0, 9, 2, 6, 0, 0, 3, 0, 0], [3, 0, 0, 0, 0, 5, 1, 0, 0], [0, 7, 0, 1, 0, 0, 0, 0, 4], [0, 0, 4, 0, 5, 0, 6, 0, 0], [2, 0, 0, 0, 0, 4, 0, 8, 0], [0, 0, 9, 4, 0, 0, 0, 0, 1], [0, 0, 8, 0, 0, 6, 5, 2, 0], [0, 0, 0, 0, 1, 0, 0, 0, 6] ] def find_next_empty_el(smth): ...
MilezNoles/sudokuSolver
main.py
main.py
py
1,197
python
en
code
0
github-code
13
2250752729
"""Wrapper to record rendered video frames from an environment.""" import pathlib from typing import Any, Dict, Optional, SupportsFloat, Tuple import gymnasium as gym from gymnasium.core import WrapperActType, WrapperObsType from gymnasium.wrappers.monitoring import video_recorder class VideoWrapper(gym.Wrapper): ...
HumanCompatibleAI/imitation
src/imitation/util/video_wrapper.py
video_wrapper.py
py
3,138
python
en
code
1,004
github-code
13
31692283560
budget = int(input()) season = input() amount_fisherman = int(input()) price = 0 if season == "Spring": price = 3000 if season == "Summer" or season == "Autumn": price = 4200 if season == "Winter": price = 2600 if amount_fisherman <= 6: price = price * 0.9 elif 7 <= amount_fisherman <= 11: pric...
DPrandzhev/Python-SoftUni
Programming_Basics-SoftUni-Python/ConditionalStatements - Advanced/fishing_boat.py
fishing_boat.py
py
651
python
en
code
0
github-code
13
27241396001
# Import Statements import math from math import radians, cos, sin, atan, sqrt #Functions def header(): print(" Welcome to my Geo Calculator.") def get_location(): lat = float(input('Please enter a latitude in decimal degrees: ')) lon = float(input('Please enter a longitude in decimal degrees:...
kyrstid/P6-Two-Geographic-Points
P6-Two-Geographic-Points.py
P6-Two-Geographic-Points.py
py
1,208
python
en
code
0
github-code
13
15743612492
from itertools import combinations def solution(m, weights): answer = 0 for num_candies in range(1, len(weights) + 1): combi_list = combinations(weights, num_candies) for combi_set in combi_list: if sum(combi_set) == m: answer += 1 return answer
ssooynn/algorithm_python
프로그래머스/사탕담기.py
사탕담기.py
py
307
python
en
code
0
github-code
13
33163587213
#Lesson 74: Listbox # https://www.youtube.com/watch?v=xiUTqnI6xk8 #listbox = a listing of slectable text items within its own container from tkinter import * window = Tk() def submit(): food=[] for index in listbox.curselection(): food.insert(index,listbox.get(index)) print("You have ordered: ") ...
Bill-Corkery/BroCode-PythonFullCourse
74-Listbox.py
74-Listbox.py
py
1,343
python
en
code
1
github-code
13
39777328729
import decimal import json from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.core.exceptions import ValidationError fr...
Pack144/packman
packman/campaigns/views.py
views.py
py
14,422
python
en
code
1
github-code
13
72840760977
from __future__ import print_function import sys import requests from requests.exceptions import Timeout from lxml import html # python 2 compabilaty if sys.version_info.major == 2: input = raw_input reload(sys) sys.setdefaultencoding('utf8') TIMEOUT_TIME = 5 BVG_URL = 'http://mobil.bvg.de/Fahrinfo/bi...
behrtam/bvg-cli
bvg_cli.py
bvg_cli.py
py
6,643
python
en
code
7
github-code
13
17154372327
## Import necessary packages import numpy as np import pandas as pd from statistics import mean from statistics import pstdev from scipy import stats import csv import re import matplotlib.pyplot as plt import matplotlib.patches as mpatches ### This section of code extracts and normalizes mutability scores from ### ###...
sayoeweje/Cas9-StructuralNetworkAnalysis
src/Mutational_Network_Analysis.py
Mutational_Network_Analysis.py
py
13,068
python
en
code
0
github-code
13
19599883602
""" Aula 19 Metaclasses EM PYTHON TUDO É OBJETO: incluindo classes Metaclasses são as "classes" que criam classes. type é um metaclesse """ class Meta(type): def __new__(mcs, name, bases, namespace): if name == 'A': return type.__new__(mcs, name, bases, namespace) if 'b_fala' not i...
joaoo-vittor/estudo-python
OrientacaoObjeto/aula19.py
aula19.py
py
947
python
pt
code
0
github-code
13
5477179080
import requests, pandas, boto3, os, configparser, datetime, logging from io import BytesIO, StringIO from zipfile import ZipFile from airflow.contrib.hooks.aws_hook import AwsHook def get_aws_config(conn_id): aws_hook = AwsHook(conn_id) credentials = aws_hook.get_credentials() return credentials def get_aws_confi...
gurjarprateek/bixi-data-repository
airflow/dags/lib/helpers.py
helpers.py
py
5,065
python
en
code
0
github-code
13
10087198856
# Given a binary tree, flatten it to a linked list in-place. # For example, # Given # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ ...
xiaochenai/leetCode
Python/Flatten Binary Tree to Linked List.py
Flatten Binary Tree to Linked List.py
py
1,072
python
en
code
0
github-code
13
33454599295
from distutils.core import setup import os import glob import re ##First, get version from Ungribwrapper/_version.py. Don't import here #as doing this in the setup.py can be problematic VERSION_FILE='./mp3tools/_version.py' matched = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", open(VERSION_FI...
corzneffect/mp3-tools
setup.py
setup.py
py
896
python
en
code
0
github-code
13
13775183478
from peewee import * from settings import * db = MySQLDatabase(DB_NAME, user=DB_USER) if DB_PASS == 'NO-PASS' else MySQLDatabase(DB_NAME, user=DB_USER, passwd=DB_PASS) class BaseModel(Model): def to_dict(self): return self.__data__ class Meta: database = db auto_increment = True cla...
ajaaibu/greenhouse-tools
models.py
models.py
py
755
python
en
code
1
github-code
13
2448830777
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: dummy = ListNode(0) dummy2 = ListNod...
asnakeassefa/A2SV_programming
0092-reverse-linked-list-ii/0092-reverse-linked-list-ii.py
0092-reverse-linked-list-ii.py
py
937
python
en
code
1
github-code
13
12135496563
''' 边沿检测 ''' import cv2 img = cv2.imread('../data/lily.png',0) cv2.imshow('img',img) #Sobel sobel = cv2.Sobel(img, cv2.CV_64F,#图像的深度 dx=1,dy=1,#水平和垂直方向的滤波计算 ksize=5)#滤波器大小 cv2.imshow('sobel',sobel) #Laplacain lap = cv2.Laplacian(img,cv2.CV_64F,ksize=5) cv2.imshow('...
15149295552/Code
Month08/day14/09_edge.py
09_edge.py
py
529
python
en
code
1
github-code
13
9582175458
import discord from tools.constants import Constants class Arcade(): @staticmethod def show_arcade_options(): embed = discord.Embed(title="TamoBot Arcade", color=0xffa500) embed.set_thumbnail(url='https://raw.githubusercontent.com/TamoStudy/TamoBot/main/README%20Assets/TamoBot.png') emb...
TamoStudy/TamoBot
apps/arcade/arcade.py
arcade.py
py
686
python
en
code
11
github-code
13
6858945996
""" train embedding with CenterLoss Author: LucasX """ import copy import os import sys import time import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from sklearn.metrics import confusion_matrix from torch.optim import lr_scheduler fro...
stevenliu1375/XCloud
research/cbir/train_with_centerloss.py
train_with_centerloss.py
py
13,478
python
en
code
null
github-code
13
27979123309
# Daniel Perez A. # CSCI Big Data: Project One import re from typing import Dict import pandas as pd import hetnetpy.hetnet from neo4j import GraphDatabase from pprint import pprint import json import networkx as nx import matplotlib.pyplot as plt from neo4j import GraphDatabase import sys from nltk.tokenize import...
halaway/graph-net-project
projectBD.py
projectBD.py
py
3,471
python
en
code
1
github-code
13
41019124082
# create a template file of setting file import json def create_setting_file(): setting = {} setting["ip"] = "192.168.124.1" setting["port"] = "22" setting["username"] = "admin" setting["password"] = "asus#1234" setting["file_path"] = "/tmp/syslog.log" with open("setting.j...
louischouasus/LogDetector
create_setting.py
create_setting.py
py
2,035
python
en
code
0
github-code
13
14834828171
class rv_decoder: def __init__(self, inst:int): self.opcode = inst & 0x7f self.funct3 = (inst >> 12) & 0x07 self.funct7 = (inst >> 25) & 0x7f self.rd = (inst >> 7) & 0x1f self.rs1 = (inst >> 15) & 0x1f self.rs2 = (inst >> 20) & 0x1f self.u_...
WenbinTeng/tone
interpreter/rv_decoder.py
rv_decoder.py
py
1,098
python
en
code
0
github-code
13
27226410119
class Coche: #Constructor def __init__(self, marca, kilometraje, color): self.__marca = marca self.__kilometraje = kilometraje self.color = color def arrancar(self, arrancamos): self.arrancamos = arrancamos if(self.arrancamos): return 'El Coche esta ...
andresdino/usco2023
Prog2/POO/Encapculamiento.py
Encapculamiento.py
py
678
python
es
code
1
github-code
13
776681234
#!/usr/bin/env python # coding: utf-8 # # On-the-fly statistics # # [This note-book is in oceantracker/tutorials_how_to/] # # Scaling up particle numbers to millions will create large volumes of # particle track data. Storing and analyzing these tracks is slow and # rapidly becomes overwhelming. For example, buildin...
oceantracker/oceantracker
tutorials_how_to/G_onthefly_statistics.py
G_onthefly_statistics.py
py
12,763
python
en
code
10
github-code
13
4791183238
#!/usr/bin/python # -*- coding: utf-8 -*- import math def demo2(a, b, strs): # 排列 for index, ele in enumerate(strs): b += ele if index == a - 1: strs = strs[index + 1:] return b, strs def demo(strs: str, numRows: int) -> str: strs = list(strs.uppe...
LeroyK111/BasicAlgorithmSet
代码实现算法/ZigzagConversion.py
ZigzagConversion.py
py
1,003
python
en
code
1
github-code
13
15825364375
import pandas as pd import plotly.graph_objects as go import plotly.express as px def candle_gen(): df = pd.read_csv('symbols.csv') fig = go.Figure(data=go.Candlestick( x=df['date'], open=df['open'], high=df['high'], low=df['low'], close=df['close'])) return fig def ohlc_gen(): df = pd.read_...
AmeyaKulkarni2001/OHCL-Engine
graph_gen.py
graph_gen.py
py
1,172
python
en
code
1
github-code
13
22869053962
import io import aiofiles import pytest from aresponses import ResponsesMockServer from aiogram import Bot from aiogram.api.client.session.aiohttp import AiohttpSession from aiogram.api.methods import GetFile, GetMe from aiogram.api.types import File, PhotoSize from tests.mocked_bot import MockedBot try: from as...
Abdo-Asil/abogram
tests/test_api/test_client/test_bot.py
test_bot.py
py
4,506
python
en
code
0
github-code
13
39761879952
import socket from threading import Thread from typing import Dict from . import logger msgFromServer = "Hello UDP Client" bytesToSend = str.encode(msgFromServer) class UdpServerException(Exception): pass class UdpServer(Thread): def __init__(self, config: Dict, receiver): super(UdpServer, self)._...
ecmwf/aviso
aviso-server/monitoring/aviso_monitoring/udp_server.py
udp_server.py
py
1,916
python
en
code
9
github-code
13
2534340493
""" Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE Inp...
fizzywonda/CodingInterview
linkedlist/Loopdetection.py
Loopdetection.py
py
988
python
en
code
0
github-code
13
16980697769
import requests import csv from bs4 import BeautifulSoup import dateutil.parser as parser ## Funktion til at skrabe hvert enkelt objekt i itemlist def item_scraper(item): title = item.find(class_="title").get_text().strip() subtitle = item.find(class_="dek").get_text().strip() date = item.find(class_="date...
Oeyaas/smaating
as.py
as.py
py
1,700
python
en
code
0
github-code
13
2200164677
#!/usr/bin/env python # -*- coding: utf-8 -*- def coef(p,q): tmp = len([val for val in p if val in q]) return 2.0*tmp/(len(p)+len(q)) def simatt(q,Pu,alpha = 0.5): cc = [] for p in Pu: cc.append(coef(p,q)) cc = sorted(cc) for i in range(1,len(cc)): cc[i] = alpha * cc[i] + (1-al...
aaeviru/pythonlib
attack.py
attack.py
py
479
python
en
code
0
github-code
13
25321524274
def toLower(s): lowers = "" for c in s: c = c.lower() lowers += c return lowers # print(toLower("GFgggftYBXjiIIOlh")) def isPalindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPalindrome(s[1:-1]) print(isPalindrome("qwerytrewq"))
fedpanoz/Python_Guttag
isPalindrome.py
isPalindrome.py
py
310
python
en
code
0
github-code
13
6953410626
with open('input', 'r') as f: lines = [] for line in f: lines.append(line) currPos = 0 count = 0 a = True while a: currMove = lines[currPos] lines[currPos] = 1 + int(lines[currPos]) currPos = currPos + int(currMove) count = count + 1 if(currPos > ...
schneiderl/problems-solved
AOC2017/day5/day_5_puzzle_1.py
day_5_puzzle_1.py
py
389
python
en
code
0
github-code
13
5960935316
import shutil import time from typing import Optional import zipfile import torch from cog import BasePredictor, ConcatenateIterator, Input, Path from config import DEFAULT_MODEL_NAME, load_tokenizer, load_tensorizer, pull_gcp_file from subclass import YieldingLlama from peft import PeftModel import os class Predic...
replicate/cog-llama
predict.py
predict.py
py
6,540
python
en
code
58
github-code
13
4928416383
from torchvision.transforms import RandomApply, Compose, ColorJitter, RandomGrayscale, RandomRotation, \ RandomResizedCrop, ToTensor from utils.base_dataset import BaseDatasetHDF from PIL.Image import fromarray import torch import h5py class KatherHDF(BaseDatasetHDF): def __init__(self, hdf5_filepath, phase, ...
stegmuel/DANN_py3
utils/kather_dataset.py
kather_dataset.py
py
3,348
python
en
code
null
github-code
13
23476246043
"""init db Revision ID: 65d821058a5e Revises: None Create Date: 2016-08-26 14:16:32.166923 """ # revision identifiers, used by Alembic. revision = '65d821058a5e' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### o...
Moxikai/Salary_info
migrations/versions/65d821058a5e_init_db.py
65d821058a5e_init_db.py
py
1,113
python
en
code
0
github-code
13
3988920436
import json import traceback from datetime import datetime from typing import Callable, Dict, List import websockets from .homeplus.models import Item, Store from .state import State, state class Client: host: str listeners: Dict[str, List[Callable]] = {} def __init__(self, host: str) -> None: ...
solo5star/dangdangrun
dangdangrun/client.py
client.py
py
3,538
python
en
code
2
github-code
13
27802952519
"""This module is a thing""" import json from pprint import pprint import logging import urllib.parse from collections import defaultdict from io import BytesIO import time from orm import * import datetime import twitterpost import facebookutils import pycurlutil import os.path import configparser import sys page_acc...
MattLud/FacebookFilterTracker
FacebookTracker.py
FacebookTracker.py
py
5,835
python
en
code
3
github-code
13
41858925944
""" Time formatter utility """ from datetime import timedelta from settings import langs def format_time( lang_code: str, time: timedelta, depth: int = 1) -> str: """Formats timedelta into a readable format Example ---------- >>> format_time('en', timedelta(days=2, hours=9, m...
cubicbyte/dteubot
bot/utils/timeformatter.py
timeformatter.py
py
1,336
python
en
code
2
github-code
13
20411445844
"""This module defines all the routes for the Daily AI assistant server.""" import json import sys import traceback from os.path import join, dirname, abspath from quart.cli import load_dotenv from quart_cors import cors from quart import Quart, jsonify, Response, request from server.call.errors import DailyPermission...
daily-demos/ai-meeting-assistant
server/main.py
main.py
py
4,242
python
en
code
0
github-code
13
37630235372
import time import logging import datetime from status_level import STATUS_CODE_TO_STR, OK from jira_utils import (post_issue, PROJECT_ID_P_S3, ISSUE_TYPE_ID_BUG) from sb_param_utils import get_license_plate_number def generate_crash_description(exc_str, module="Fail-safe"): dt = datetime.datetime.fromtimestamp(t...
wasn-lab/Taillight_Recognition_with_VGG16-WaveNet
src/utilities/fail_safe/src/issue_reporter.py
issue_reporter.py
py
2,928
python
en
code
2
github-code
13
2950900443
import tensorflow as tf class SemanticSegmentationModelFactory: def initialize_cost(self, load_existing_model, model, labels_one_hot, graph): tensor_cost = None if load_existing_model == False: labels_one_hot_float = tf.to_float(labels_one_hot) #tensor_cost = tf.reduce_mean...
klillas/TensorFlowLearning
ConvNets/SemanticSegmentation/SemanticSegmentationModelFactory.py
SemanticSegmentationModelFactory.py
py
5,239
python
en
code
0
github-code
13
5001460540
from tkinter import Tk, Button import tkinter.messagebox as msg if __name__ == '__main__': tk : Tk = Tk() tk.title("Tic-Tac-Toe") xTurn: bool = True moves: int = 0 def save(msg): with open("results.txt", "a") as f: f.write(msg+"\n") def reset(): global xTu...
AbhiShake1/Tic-Tac-Toe
TicTacToe.py
TicTacToe.py
py
3,587
python
en
code
0
github-code
13
22943023484
import env_examples # Modifies path, DO NOT REMOVE from sympy import Symbol, Pow, Add, atan, Mul import numpy as np from src import Circuit, CoordinateSystem, VoltageSource, Wire, World if __name__ == "__main__": WORLD_SHAPE = (101, 101) BATTERY_VOLTAGE = 1.0 HIGH_WIRE_RESISTANCE = 1.0 LOW_WIRE_RES...
AlexandreBeliveau/Devoir-electromag
examples/circuitC.py
circuitC.py
py
2,013
python
en
code
0
github-code
13
24616628689
from scipy.optimize import root import numpy as np import cmath def convert_to_wavevector(H, x, t_inc, omega, kp, bool=True, shift=0): A = np.zeros(len(H), dtype=complex) print(len(A)) for t in range(0, len(H)): A[t] = H[t] * cmath.exp(+1j * (kp * x - omega * t * t_inc+shift)) if bool == Fa...
svenjahlrs/Stusti_PINN
libs/wave_tools.py
wave_tools.py
py
3,683
python
en
code
0
github-code
13
28441800433
# -*- coding: utf-8 -*- """ @Time : 2022/7/25 15:51 @Auth : 罗忠建 """ import os import sys import xlrd from xlutils.copy import copy import xlwt class ExcelApp: dataDir = "" fileName = "" sheetsName = ["Sheet1"] def __init__(self, fileName, sheetsName): self.fileName = fileName se...
luozhongjian/UIAutoTest
SaaS_Auto_Test/com/HT/SaaS/SaaSmgmt/library/excelstand.py
excelstand.py
py
4,328
python
en
code
0
github-code
13
72346172178
from rhino_io import RhinoIO from mesh import FEMMesh import os def main(): mesh = FEMMesh.polygon(1, 5) mesh.subdivide_faces(2) mesh.shrink_buffers() mesh = RhinoIO.convert_to_rhino(mesh) print(mesh.Encode()) # output_path = os.path.realpath(".\\tests\\test_output\\debug_output.3dm") ...
DerLando/FEMMeshPy
src/debug.py
debug.py
py
424
python
en
code
0
github-code
13
35028265540
# 최대공약수와 최소공배수 n1, n2 = list(map(int,input().split())) # 두 수를 받음 GCM = 0 # 최대공약수 if n1>= n2: # 1부터 작은수까지 for i in range(1,n2+1): if n1%i == 0 and n2%i == 0: # 모두 나눠떨어지는 최대수를 대입 GCM = i else: for i in range(1,n1+1): if n1%i == 0 and n2%i == 0: GCM = i print(G...
Jehyung-dev/Algorithm
백준/Bronze/2609. 최대공약수와 최소공배수/최대공약수와 최소공배수.py
최대공약수와 최소공배수.py
py
552
python
ko
code
0
github-code
13
13158627492
''' Created on 11/7/2015 @author: ksi ''' import threading import sys from socket import * from PyQt4.QtGui import * from PyQt4 import QtCore from PyQt4.QtCore import * from Tkinter import Widget from PyQt4.QtCore import QObject, pyqtSignal, pyqtSlot import quopri class QWid(QWidget): def __init__(self): ...
robertofocke/chatpyqt1
Clientes.py
Clientes.py
py
3,786
python
en
code
0
github-code
13
5441499002
""" Simple CNN model for the CIFAR-10 Dataset @author: Adam Santos """ import numpy from keras.constraints import maxnorm from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, Convolution2D import tensorflow as tf from keras.utils ...
Addrick/DL4ARP
Models/mnist_modelfn.py
mnist_modelfn.py
py
3,836
python
en
code
1
github-code
13
12402818003
from flask import Flask, request, Response, abort import os import requests import logging import json import dotdictify from time import sleep import base64 import cherrypy app = Flask(__name__) logger = None format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logger = logging.getLogger('cvpartne...
sesam-community/cvpartner-rest
service/cvpartner.py
cvpartner.py
py
13,114
python
en
code
0
github-code
13
1969241541
import logging import os import sys from models import SimpleCNN, calc_accuracy import torch from torch.utils.data import DataLoader from torch import optim import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as datasets from transformers import ( HfArgumentParser, T...
VadyusikhLTD/prjctr-ML-in-Prod
week3/image_classification/image_classification/fashion_mnist.py
fashion_mnist.py
py
5,878
python
en
code
0
github-code
13
28379594179
from distutils.core import setup import os from os.path import join from distutils.extension import Extension from Cython.Build import cythonize import numpy from numpy.distutils.system_info import get_info from numpy.distutils.misc_util import Configuration def get_blas_info(): def atlas_not_found(blas_info_): ...
ASzot/ClusterCNN
custom_kmeans/setup.py
setup.py
py
1,740
python
en
code
10
github-code
13
73493586257
# Sorteio de uma ordem from random import shuffle nome1 = str(input('Primeiro grupo: ')) nome2 = str(input('Segundo grupo: ')) nome3 = str(input('Terceiro grupo: ')) nome4 = str(input('Quarto grupo: ')) lista = [nome1, nome2, nome3, nome4] shuffle(lista) print('A ordem de apresentação das bandas é') print(...
damiati-a/CURSO-DE-PYTHON
Mundo 1/ex020.py
ex020.py
py
333
python
pt
code
0
github-code
13
17592801884
# longest_common_subsequence is function to find lcs between 2 arrays or strings def longest_common_subsequence(self,s1,s2): if len(s1)==0 or len(s2)==0: return 0 x=len(s1) y=len(s2) mm=[[0 for k in range(y+1)] for l in range(x+1)] for i in range(1,len(mm)): for j in rang...
Mukesh-kanna/python-content-repo
longest_common_subsequence.py
longest_common_subsequence.py
py
541
python
en
code
0
github-code
13
70707345618
import scrapy import re from itlaoqi.service.CatalogueService import CatalogueService class ChapterSpider(scrapy.Spider): name = "chapter" custom_settings = {'ITEM_PIPELINES': { 'itlaoqi.pipeline.RabbitPipeline.RabbitPipeline': 300, }} def start_requests(self): result = CatalogueServ...
himcs/itlaoqi-spider
itlaoqi/spiders/ChapterSpider.py
ChapterSpider.py
py
1,267
python
en
code
0
github-code
13
19472573972
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 20:24:49 2020 @author: leokt """ #import modules import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #import data fileloc = "J:\Depot - dDAVP-time course - Kirby\Analysis\\201110_Total_Protein.xlsx" df_cntl = ...
krbyktl/Kidneys
110320_dDAVP_MedianNorm.py
110320_dDAVP_MedianNorm.py
py
9,792
python
en
code
0
github-code
13
39614247474
import argparse import pandas as pd from sklearn.feature_selection import SelectKBest, chi2, f_classif, mutual_info_classif import numpy as np from sklearn.preprocessing import MinMaxScaler if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input_filepath", help="CSV input filepa...
danielgibert/fusing_feature_engineering_and_deep_learning_a_case_study_for_malware_classification
src/preprocessing/select_K_best_features.py
select_K_best_features.py
py
2,864
python
en
code
6
github-code
13
38777611639
import execute import queries import logging import get_token from create_xml import createXML from create_xml_apli import createXMLA from create_xml_otros import createXMLO from create_xml_saldo import createXMLS from create_xml_cacre import createXMLC from create_xml_mova import createXMLM def main():...
mariomtzjr/dsLinqPublic
main.py
main.py
py
2,222
python
es
code
0
github-code
13
12400733359
import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate # only applies at low intensity, ie, I << Isat f87 = (384.230484468-0.002563006+0.000193741)*1e12 # Hz, Rb87 D2 F=2->F'=3 f85 = (384.230406373-0.001264889+0.000100205)*1e12 # Hz, Rb85 D2 F=3->F'=4 isotope_shift = f85-f87 # Hz h ...
qw372/Lab-essential-calculation
Rb-vapor-pressure/absorptionRb.py
absorptionRb.py
py
2,878
python
en
code
0
github-code
13
18770744709
# 수식 최대화 # N : len(expression) # 시간 복잡도 : O(N) 공간 복잡도 : O(N) import itertools # op 들의 모음 operations = [] # 초기화 def init(expression: str): for op in '*+-': if op in expression: operations.append(op) # 연산을 해주는 함수 def operation(operator1: int, operator2: int, op: str) -> int: if op == '*': ...
galug/2023-algorithm-study
level_2/maximum_expression.py
maximum_expression.py
py
1,939
python
en
code
null
github-code
13
42857448558
import pickle as pkl import networkx as nx import numpy as np import scipy.sparse as sp import torch from sklearn.metrics import roc_auc_score, average_precision_score def sample_mask(idx, l): """Create mask.""" mask = np.zeros(l) mask[idx] = 1 return np.array(mask, dtype=np.bool) def load_data(dat...
juexinwang/scGNN
gae/utils.py
utils.py
py
8,312
python
en
code
112
github-code
13
14324551309
import reportlab from reportlab.graphics.shapes import Drawing from book import Book, BookPage import math from reportlab.pdfgen import canvas from reportlab.lib.colors import Color import reportlab.rl_config reportlab.rl_config.warnOnMissingFontGlyphs = 0 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbas...
cjrosen/at-the-catastrophy-point
src/book/pdf_renderer.py
pdf_renderer.py
py
6,422
python
en
code
0
github-code
13
39982481664
# -*- coding: utf-8 -*- import codecs import os import sys reload(sys) sys.setdefaultencoding('GBK') #1.读取文件 def readfile(filepath): f = codecs.open(filepath, 'r', "utf-8") #打开文件 lines = f.readlines() word_list = [] for line in lines: line = line.strip() words = line.split(" ") #用空格分...
lonelyKSA/Deep-Learning
pre_task/pretask.py
pretask.py
py
1,801
python
en
code
0
github-code
13
16825931304
"""Tests for the database interface.""" from typing import List from pytest import mark from hyrisecockpit.api.app.database.interface import ( AvailableWorkloadTablesInterface, DatabaseInterface, DetailedDatabaseInterface, WorkloadTablesInterface, ) from hyrisecockpit.api.app.database.model import ( ...
hyrise/Cockpit
tests/api/database/test_interface.py
test_interface.py
py
2,938
python
en
code
14
github-code
13
24622299214
from datetime import datetime, timedelta import logging from io import BytesIO from functools import lru_cache from contextlib import contextmanager from dateutil.parser import parse import boto3 from ocs_archive.input.file import DataFile from ocs_archive.storage.filestore import FileStore, FileStoreConnectionError ...
observatorycontrolsystem/ocs_archive
ocs_archive/storage/s3store.py
s3store.py
py
4,723
python
en
code
0
github-code
13
73134522576
import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from scipy.spatial import distance_matrix from sklearn.mixture import GaussianMixture def removeKNearest(coordinates,K): N = coordinates.shape[0] updated_coordinates = np.copy(coordinates) for k in range(K): ...
cwseitz/miniSMLM
miniSMLM/utils/correct.py
correct.py
py
2,024
python
en
code
0
github-code
13
35300931898
from collections import deque, defaultdict t = int(input()) for _ in range(t): n, m = map(int, input().split()) c = list(map(int, input().split())) g = [[] for _ in range(n)] for i in range(m): u, v = map(lambda x: x-1, map(int, input().split())) g[u].append(v) g[v].append(u) ...
nozomuorita/atcoder-workspace-python
abc/abc289/e.py
e.py
py
839
python
en
code
0
github-code
13
70078642579
from discord import Message, Member, TextChannel, Guild, Embed, Client, User from datetime import datetime from database.select import Report from utilities import util, secret from system import permission, appearance from system.moderation import moderation from database import insert, select async def report_cmd(...
FynnFromme/fryselBot
system/moderation/report.py
report.py
py
3,741
python
en
code
1
github-code
13
3499321610
def solution(board, moves): answer = 0 besket = [] for i in moves: for j in range(0, len(board)): if(board[j][i-1] != 0): pick = board[j][i-1] # print(pick) board[j][i-1] = 0 if(len(besket) > 0 and besket[-1] == pick): ...
wizard9582/Algo
Programmers/Python/q64061_Programmers_크레인인형뽑기게임.py
q64061_Programmers_크레인인형뽑기게임.py
py
623
python
en
code
2
github-code
13
28743166510
import re import requests from bs4 import BeautifulSoup from collections import Counter user_input = input("Введите URL статьи или вставьте скопированный текст: ") if user_input.startswith("http"): url = user_input response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') text = ...
Vitariuss/Hometasks2
NewLesson3/hw2.py
hw2.py
py
723
python
en
code
0
github-code
13
31189374608
from lib.action import PyraxBaseAction from lib.formatters import to_server_dict __all__ = [ 'ListVMImagesAction' ] class ListVMImagesAction(PyraxBaseAction): def run(self): cs = self.pyrax.cloudservers imgs = cs.images.list() result = {} for img in imgs: result[im...
gtmanfred/st2contrib
packs/rackspace/actions/list_vm_images.py
list_vm_images.py
py
360
python
en
code
null
github-code
13
13741781833
# # Figure # plt.rc('font', family='Helvetica', size=14) # To later reset to default font settings: plt.rcdefaults() fig = plt.figure(figsize=(12, 6)) ax = plt.subplot() plt.plot( x_values, ldc, lw=1.5, label='Load duration curve' ) plt.plot( x_values, coal, lw=1.5, label='Coal generation' )...
htw-pv3/weather-data
python/tutorial/vis-tutorial-master/01-ex01-example.py
01-ex01-example.py
py
695
python
en
code
9
github-code
13
32834097093
import requests, json import argparse,os def url(link): params = {'apikey': 'api_key', 'url': link} response = requests.post('https://www.virustotal.com/vtapi/v2/url/scan', data=params) results = response.json() print("REPORT") params2 = {'apikey': 'api_key', 'resource': results['sc...
fatihh92/virustotaler
virustotal.py
virustotal.py
py
4,165
python
en
code
0
github-code
13
36296861551
from django.contrib import admin from .models import * # Register your models here. admin.site.register(TransactionType) admin.site.register(TransactionStatus) @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_display = ("cs", "bl", "transaction_type", "transaction_status", "amount")
shoora-tech/dheera
transaction/admin.py
admin.py
py
319
python
en
code
0
github-code
13
39942354931
#!/usr/bin/env python from flexbe_core import EventState, Logger from flexbe_core.proxy import ProxyActionClient # example import of required action from o2ac_msgs.msg import FastenAction, FastenGoal class FastenActionState(EventState): ''' Actionlib for aligning the bearing holes -- task_name st...
o2ac/o2ac-ur
catkin_ws/src/o2ac_flexbe/o2ac_flexbe_states/src/o2ac_flexbe_states/fasten.py
fasten.py
py
2,079
python
en
code
92
github-code
13
24511632609
import matplotlib.pyplot as plt import numpy as np width = 0.1 country = ["USA" , "India" , "Amarica"] gold=[20,10,6] silver=[100,50,30] Bronze=[200,100,60] bar1 = np.arange(len(country)) bar2 = [i+width for i in bar1] bar3= [i+width for i in bar2] plt.bar(bar1,gold,width,color="r") plt.bar(bar2,silv...
iamvaibhav31/Machine-Learning
1. some important library of python used in machine learning/Matplotlib/Multiple_bar_chart(MATPLOTLIB).py
Multiple_bar_chart(MATPLOTLIB).py
py
503
python
en
code
1
github-code
13
5528342770
from flask import Flask, render_template, jsonify, redirect, request from flask_pymongo import PyMongo from pymongo import MongoClient from time import gmtime, strftime import pandas as pd import json import sys import os from urllib.parse import urlsplit from bson import BSON from bson import json_util from dotenv im...
jjahn0/ADA
app.py
app.py
py
3,764
python
en
code
1
github-code
13
15822892265
from data import Log from users import user def new_log(username): with open('log.txt', 'r+') as reader: # file object for reading and writing print("Enter New Journal") content = reader.read() # getting file content into a single object journal = input() # journal string is being en...
slk007/Journal-App
main.py
main.py
py
1,943
python
en
code
0
github-code
13
39324835649
#To Find Errors try: file = open("a_file.text") a_dictionary = {"key": "value"} print(a_dictionary["key"]) except FileNotFoundError: file = open("a_file.text", "w") file.write("something") except KeyError as error_message: print(f"the key {error_message} dosen't exist") else: content = file.read() pr...
mukalaraja/python_bootcamp
day030/day-30.py
day-30.py
py
385
python
en
code
0
github-code
13
24423077620
import sgtk from sgtk.platform.qt import QtCore, QtGui # import the shotgun_fields module from the qtwidgets framework shotgun_fields = sgtk.platform.import_framework( "tk-framework-qtwidgets", "shotgun_fields") # import the shotgun_globals module from the qtwidgets framework shotgun_globals = sgtk.platform.impor...
ColinKennedy/tk-config-default2-respawn
bundle_cache/app_store/tk-multi-demo/v1.0.2/python/tk_multi_demo/demos/custom_field_widget/demo.py
demo.py
py
4,306
python
en
code
10
github-code
13
10992276259
import time from sys import argv payload_size = 32 msg_tot = int(float(256)) file_name = 'rank_' + str('TEST') + '.csv' sent_time = {} msg_num = 0 delta = 0.0 rank = 1 if rank == 1: data = bytes(payload_size) beg = time.time() while True: if msg_tot in sent_time: sent_time[msg_tot][ms...
folkpark/MPI_Benchmarking
exp10/exp10_3n/test.py
test.py
py
836
python
en
code
0
github-code
13
2623831602
#Una función lambda son funciones anonimas #Son pequeñas, una linea de codigo def sumar(a, b): return a + b #Con una función lambda, la función es anonima #No se necesita agregar paréntesis para los parámetros #No se necesita usar la palabra return, pero sí debe regresar una expresión valida] mi_funcion_...
Chrisgmsl22/python_course
funciones_lambda.py
funciones_lambda.py
py
1,261
python
es
code
0
github-code
13
22756216624
from django.shortcuts import get_object_or_404 from rest_framework.views import APIView, Request, Response, status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from kmdb.pagination import CustomPageNumberPagination from .permission impor...
Marc-bd/KMDB-API
reviews/views.py
views.py
py
2,328
python
en
code
0
github-code
13
40394054165
# -*- encoding=utf8 -*- # 场景五:到店点餐点“焦糖奶茶-中杯+1元香草”,“波霸奶茶+价格-1”、下单,退一个“焦糖奶茶-中杯+1元香草”,改为“炸鸡腿(称重)+打包”,菜品上齐结账,和商家协商抹零操作,现金-找零,结账后查看宝报表 __author__ = "lsd" from airtest.core.api import * from poco.drivers.android.uiautomation import AndroidUiautomationPoco stop_app("com.yhbc.tablet") start_app("com.yhbc.tablet",activi...
gaojk/AirtestCase
AirtestCase/SmartPOS-Old/用例集/场景五-现金-找零.air/场景五-现金-找零.py
场景五-现金-找零.py
py
6,190
python
en
code
0
github-code
13
27460840925
from PIL import Image from math import ceil, sqrt class GridCanvasPainter: def __init__(self, images, layout=None, grid_shape=None, gap_shape=None, force_list=False, bg_color=None): """ painter for a new canvas with images placed on it as grids :param images: iterable, sequence of PIL imag...
shuheng-liu/misc-tools-python
image_utils/_grid_canvas.py
_grid_canvas.py
py
6,698
python
en
code
0
github-code
13
16006202120
import gym import os import torch import tqdm import numpy as np from mani_skill2.utils.wrappers import RecordEpisode from tools.utils import animate from mani_skill2.utils.sapien_utils import get_entity_by_name, look_at from copy import deepcopy import multiprocessing as mp import PIL.Image as im mp.set_start_method(...
haosulab/RPG
external/ManiSkill2/tools/replay.py
replay.py
py
5,499
python
en
code
18
github-code
13
1664590867
import turtle import random screen = turtle.Screen() turtlemain = turtle.Turtle() (x_pos, y_pos) = screen.screensize() xpos = x_pos / 2 ypos = y_pos / 2 (turtle_xpos, turtle_ypos) = turtlemain.pos() turtlex = abs(turtle_xpos) turtley = abs(turtle_ypos) turtlemain.penup() turtlemain.goto(0,0) def flipcoin(): retu...
bucs110SPRING23/portfolio-regina-lu
ch04/exercises/coinflip.py
coinflip.py
py
618
python
en
code
0
github-code
13
72124701138
from django.shortcuts import render, Http404,redirect, get_object_or_404 from django.contrib.auth.models import User from django.http import HttpResponse from django.core import serializers import datetime from .models import Country from .forms import NameForm, ContactForm, CountryForm # Create your views here. def he...
SahibSethi/mynewinstagram
mynewinstagram/account/views.py
views.py
py
2,588
python
en
code
0
github-code
13
16470983201
import json from django.http import JsonResponse from .models import FoodData, IntakeData, User, WaterConsumption from .serializers import FoodDataSerializer, UserSerializer, IntakeDataSerializer, WaterCountSerializer from django.views.decorators.csrf import csrf_exempt def food_search(request, query): foods = Foo...
ankitsawho/calorie-tracker
server/api/views.py
views.py
py
4,030
python
en
code
0
github-code
13
23158323008
import requests as r import json import tryagain import time import config as cfg tg_url = 'https://api.telegram.org/bot' + cfg.tg_token + '/sendmessage' tunnels_old = '' def checker(): global tunnels_old iteration = 0 tunnels = (r.get('https://api.ngrok.com/tunnels', h...
ZemlyakovDmitry/Ngrok-URL-Notifier-Minecraft
main.py
main.py
py
1,473
python
en
code
0
github-code
13
43246427942
import forecastio from datetime import datetime, timedelta from flask import current_app class Forecast: def __init__(self, key, lat, lon, units, refresh): self.forecast = None self.refresh = refresh self.key = key self.lat = lat self.lon = lon self.units = units ...
leoscholl/wallberry
wallberry/cache.py
cache.py
py
842
python
en
code
1
github-code
13
19092503687
import argparse import gzip import random import sys parser = argparse.ArgumentParser() parser.add_argument('--file1', required=True, type=str, metavar='<path>', help='path to _true_ sequence file') parser.add_argument('--file2', required=True, type=str, metavar='<path>', help='path to _fake_ sequence file') parser....
KorfLab/genDL
arch/data/seq2csv.py
seq2csv.py
py
1,791
python
en
code
1
github-code
13
12344248635
# program for computing the diameter of the tree. # Now, diameter is the maximum of the distance between two leaves. # So, we have already seen other solutions for the problem and also observed how we are processing the nodes again and again once while computing the # height and again while computing the diameter of in...
souravs17031999/100dayscodingchallenge
dynamic programming/diameter_tree_dp_general_syntax.py
diameter_tree_dp_general_syntax.py
py
1,748
python
en
code
43
github-code
13
1435857667
class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ def mycmp(a, b): if a[0] == b[0]: return a[1] - b[1] else: return b[0] - a[0] p...
hagho/leetcode_py
406_Queue_Reconstruction_by_Height[M].py
406_Queue_Reconstruction_by_Height[M].py
py
457
python
en
code
0
github-code
13
21656835054
import sys, os fin = open(sys.argv[1],'r') os.system("rm -f sched_plot_files/*") os.system("rm -f sched_plot_files/selected/*") processLogFiles = {} for line in fin: line = line.strip().split() process = line[0] process = process.replace('/','-') timestamp = line[3][:-1] if process not...
yuvraj2987/ResourceAccounting
python_module/graphScripts/backup/sched_1.py
sched_1.py
py
482
python
en
code
2
github-code
13
32687911732
import os import logging from distutils.util import strtobool from typing import Dict, Any from gamekithelpers import ddb from gamekithelpers.handler_request import get_player_id, get_path_param, get_query_string_param, log_event from gamekithelpers.handler_response import response_envelope from gamekithelpers.validat...
aws/aws-gamekit-unreal
AwsGameKit/Resources/cloudResources/functions/gamesaving/GetSlotMetadata/index.py
index.py
py
2,921
python
en
code
68
github-code
13
22115937253
import unittest import mock from scotty.config import ScottyConfig from scotty.core.exceptions import ScottyException class ScottyConfigTest(unittest.TestCase): def test_scotty_config_constructor(self): scotty_config = ScottyConfig() self.assertIsNotNone(scotty_config) @mock.patch('scotty.c...
mikelangelo-project/scotty.py
tests/test_config.py
test_config.py
py
2,479
python
en
code
0
github-code
13
72395622738
import numpy as np import time def backtracking_line_search(func, x_k, p_k, g_x_k, alpha, rho, c1, f_x_k, norm_g_x_k): number_function_call_bls = 0 nk = 1 #checking the gradient of the function if norm_g_x_k >= 1: nk = 1 else: nk = 1 - np.floor(np.log(norm_g_x_k)) su = 0 nk1...
cvshah/blackbox_for_optimization
sampling_function.py
sampling_function.py
py
3,456
python
en
code
0
github-code
13
16397051052
from flask import Flask, render_template, request, url_for, make_response, jsonify, session, redirect, g, flash import random, urllib from dogeify import * from quotes import * import dogeconfig import nltk.data, nltk.tag tagger = nltk.data.load("taggers/maxent_treebank_pos_tagger/english.pickle") app = Flask(__name_...
cloudcrypt/dogeify
app.py
app.py
py
1,409
python
en
code
4
github-code
13
43085603602
class Solution: def translateNum(self, num: int) -> int: # 动态规划中的零位目前都是为了保证转移方程的完整性,实际上不对应数据,是为了完整而构建的数字,值根据转移方程推导而得 str_num = str(num) a = 1 b = 1 for i in range(2, len(str_num) + 1): c = a + b if '10' <= str_num[i - 2: i] <= '25' else a b = a ...
Guo-xuejian/leetcode-practice
剑指 Offer46把数字翻译成字符串.py
剑指 Offer46把数字翻译成字符串.py
py
461
python
en
code
1
github-code
13