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
43512837698
class Solution: def merge(self, nums1, m, nums2, n): if n != 0: if m == 0: for i in range(n): nums1[i] = nums2[i] m = n else: for i in range(n): l = i print(l) r = m-1 while l <= r: mid = int((l+r)/2) if...
km1994/leetcode
old/t20190909_merge/merge.py
merge.py
py
783
python
zh
code
24
github-code
1
11587990326
#!/usr/bin/env python3 """ Solution for embedded items 5x5 matrices - plot data as grid and average response in each category (col 0) - compare with random/no-structure model (col 1) - compare with user-specified model (col 2) """ # core import csv, os, re # data management import pandas as pd # scientific ...
knielbo/survey_visualization
embedded2plot.py
embedded2plot.py
py
6,395
python
en
code
1
github-code
1
35052674716
import sqlite3 class Database: def __init__(self, dbName): self.dbName = dbName self.con = sqlite3.connect('C://NFT_DATABASES/' + dbName +'.db') def getNFT(self, id): stmt = "SELECT * FROM NFT WHERE ID = " + str(id) cursor = self.con.cursor() cursor.execute(stmt) ...
Ahmad-Shehzad/NFT-Generator
NFT Image Creator/Database.py
Database.py
py
1,735
python
en
code
0
github-code
1
28273046112
RABBITMQ_HOST = 'localhost' RABBITMQ_PORT = 5672 RABBITMQ_USER = 'guest' RABBITMQ_PASS = 'guest' import pika from os import environ ### #local RABBITMQ hostname = environ.get('rabbit_host') or 'localhost' port = environ.get('rabbit_port') or 5672 # connect to the broker and set up a communication cha...
peterwengg/Eevee-Trading
Backend/amqp_setup.py
amqp_setup.py
py
4,384
python
en
code
0
github-code
1
20969486373
import math import sys import time from nba_api.stats.static import players from nba_api.stats.endpoints import playergamelog from nba_api.stats.library.parameters import SeasonAll from nba_api.stats.endpoints import leaguegamefinder import csv import pandas as pd from bs4 import BeautifulSoup import requests from date...
DanielMillward/NBADataScraper
1_update_db.py
1_update_db.py
py
11,619
python
en
code
0
github-code
1
8043880352
from db import db def add_course(name, questions, teacher_id): sql = """insert into courses (name, teacher_id, visible) values (:name, :teacher_id, 1) returning id""" course_id = db.session.execute(sql, {"name":name, "teacher_id":teacher_id}).fetchone()[0] for i in questions.split("\n"): ...
janikakalliokoski/tsoha-opetussovellus
courses.py
courses.py
py
4,487
python
en
code
0
github-code
1
27808418456
import os import sys import tensorflow as tf def __write_class_start(output_file, class_name): if not isinstance(class_name, str): raise AssertionError("Attribute class_name has to be of the type String") output_file.write("import tensorflow as tf\n\n") output_file.write("class %s(tf.keras.Model):\n" % (class_na...
karthikrangasai/Deep-Learning-Deep-Learning
models/rmg/model_class_file_generator.py
model_class_file_generator.py
py
2,422
python
en
code
2
github-code
1
72259961953
from django.db import models from django.conf import settings class CountCheckUtils: @staticmethod def seeding(index: int, single: bool = False, save: bool = True) -> models.QuerySet: from apps.count_check.serializers import CountCheckBaseSr if index == 0: raise Exception('Indext m...
tbson/24ho
api/apps/count_check/utils.py
utils.py
py
1,234
python
en
code
0
github-code
1
37589968716
''' Build a tweet sentiment analyzer ''' from __future__ import print_function import six.moves.cPickle as pickle import time from collections import OrderedDict import sys import time from sys import argv import numpy import theano from theano import config import theano.tensor as tensor from theano.sandbox.rng_mrg i...
njustkmg/ACML17_DMS
dms.py
dms.py
py
33,100
python
en
code
4
github-code
1
10412589273
from collections import Counter import numpy as np import pandas import pprint # noinspection PyUnresolvedReferences from utils import tokenize # nltk.download('stopwords') # importing corpus as resume resume_file = open('../assets/resume.txt', 'r') resume = resume_file.read().lower() resume_file.close() # tokeniz...
anishLearnsToCode/bow-representation
src/one-hot-vector.py
one-hot-vector.py
py
1,229
python
en
code
1
github-code
1
35533985483
import argparse import socket from pretenders.server.base import in_parent_process, save_pid_file from pretenders.server.log import get_logger from pretenders.client import BossClient from pretenders.common.constants import RETURN_CODE_PORT_IN_USE LOGGER = get_logger("pretenders.server.pretender") class Pretender(o...
pretenders/pretenders
pretenders/server/pretender.py
pretender.py
py
2,599
python
en
code
108
github-code
1
26364184361
d1 = int(input()) d2 = int(input()) m = int(input()) f = (10 * m) / (d1 + d2) print(f'Scar conseguiu criar uma frustração {f:.2f} na turma') if f >= 4: print('Eu matei Mufasa') elif f > 2: print('Consegui lacaios preciosos') else: print('Mais um fracasso...')
WilliamdeSousa/lab-algoritmos
Lista 2 - Estrutura condicional/2501.py
2501.py
py
283
python
pt
code
0
github-code
1
32437564312
import pandas as pd from stable_baselines3.ppo import MlpPolicy from stable_baselines3.common.callbacks import CheckpointCallback from stable_baselines3 import PPO from torch import nn from tqdm import trange from golds.contracts import Currency, Stock, Option, OptionFlavor, OptionStyle, Holdings from golds.en...
fany02656/RL-Finance-FY
main.py
main.py
py
5,173
python
en
code
0
github-code
1
23739113062
import argparse import pytorch_lightning as pl import torch from torch.nn import functional as F import constants from lightling_wrapper import BaseTorchLightlingWrapper, SpeechCommandDataModule from models.bc_resnet.bc_resnet_model import BcResNetModel from models.bc_resnet.mel_spec_dataset import MelSpecDataSet, me...
egochao/speech_commands_distillation_torch_lightling
test.py
test.py
py
1,768
python
en
code
0
github-code
1
70431605475
import numpy as np import matplotlib.pyplot as plt class Kmeans(object): def __init__(self, k=1): self.k = k def train(self, data, verbose=1): shape = data.shape ranges = np.zeros((shape[1], 2)) centroids = np.zeros((shape[1], 2)) for dim in range(shape[1]): ...
divyanshugit/representation_learning
models/classificaton/kMeans.py
kMeans.py
py
2,669
python
en
code
2
github-code
1
73034211233
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import skipIf, TestCase from salttesting.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch ) fro...
shineforever/ops
salt/tests/unit/states/rabbitmq_plugin_test.py
rabbitmq_plugin_test.py
py
2,591
python
en
code
9
github-code
1
40250930163
import sys import heapq class PriorityQueue: """ Implements a priority queue data structure. """ def __init__(self): self.heap = [] self.count = 0 self.items = [] def push(self, item, priority): entry = (priority, self.count, item) heapq.heappush(self.hea...
nummy/exec
todo/graph/question2d/a1.py
a1.py
py
3,583
python
en
code
0
github-code
1
27733324416
import logging from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from timeline.models import Timeline # Models class SubscribeRecord(models.Model): is_read = models.BooleanField( defau...
Sergey19940808/blog
blog/models.py
models.py
py
3,771
python
en
code
0
github-code
1
24249664220
import os from PySide6 import QtWidgets from PySide6.QtGui import QFont, QIcon from PySide6.QtWidgets import ( QCheckBox, QComboBox, QFileDialog, QFrame, QLabel, QLineEdit, QPushButton, QRadioButton, QSizePolicy, QSpacerItem, QTabWidget, QTextEdit, QWidget, ) from n...
Natsume-197/NadeOCR
nadeocr/GUI/widgets/options_widget.py
options_widget.py
py
10,175
python
en
code
2
github-code
1
907482435
class Solution: # @param A : string # @return an integer def solve(self, A): count=0 vowels = ["a","e","i","o","u"] for i in range(len(A)): if A[i].lower() in vowels: count=count+len(A)-i return (count%10003)
rohinarora/InterviewBit
5. Strings/4. Amazing Subarrays/tmp.py
tmp.py
py
281
python
en
code
0
github-code
1
32596992467
import heapq from collections import defaultdict class HuffmanNode: def __init__(self, symbol, freq): self.symbol = symbol self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(f...
s25672-pj/asdZad4
zad4.py
zad4.py
py
1,980
python
en
code
0
github-code
1
17605302358
temperaturas = [] continuar = True while continuar == True: temperatura = int(input("Temperatura que deseja informar: ")) temperaturas.append(temperatura) if input("Deseja continuar (s/n)? ") == 's': continuar = True else: continuar = False valor_limiar = int(input("Digite um valor limiar(média): "))...
PerseuSam/FATEC-MECATRONICA-0791811039-SAMUEL
LTPC2-2020-2/Prova/exerci3.py
exerci3.py
py
938
python
pt
code
0
github-code
1
25253445700
from test_cases import PseudocodeConverter filename = input("What is the name of the file? ") line_series = [line.rstrip('\n') for line in open(filename + '.py')] converter = PseudocodeConverter(line_series) converted_lines = converter.get_converted_lines() with open(filename + " pseudocode.txt", 'w') as f: for...
melodicht/PythonToPseudoCode
__init__.py
__init__.py
py
467
python
en
code
0
github-code
1
73654169633
import os from qgis.PyQt import QtWidgets, uic from qgis.PyQt.QtCore import pyqtSignal from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtWidgets import QApplication from qgis.utils import iface from qgis.core import ( QgsProject, QgsPointXY, QgsCoordinateReferenceSystem, QgsCoordinateTransform, ) fro...
danylaksono/GeoKKP-GIS
modules/draw_nlp.py
draw_nlp.py
py
8,095
python
en
code
2
github-code
1
13255279223
#! python 3 """ Program that reads in text files and lets users replace some keywords. Lastly, save as new file """ from pathlib import Path import re ### read in text file file_name = input("Enter relative path of file (eg. folder/file.txt): ") p = Path(Path.cwd() / file_name) input_file = open(p) txt = input_file.r...
simink/py_automatetheboringstuff
code/madLibs.py
madLibs.py
py
893
python
en
code
1
github-code
1
31276842685
""" Fix binary png images so that they're in a consistent binary format Used for ground truth (_fg) images which can be saved by some image programs as 8 bit RGB pngs rather than binary ones. """ import cv2 import os import io for img in os.listdir("/home/carter/Desktop/our-data/training/imgs"): if "_fg" in img: ...
cpsiff/plant-segmentation
fix_imgs.py
fix_imgs.py
py
795
python
en
code
3
github-code
1
71727466274
input = open("input").read().splitlines() register = 1 cycle = 0 total = 0 sprite = "###....................................." for instruction in input: op = instruction.split() if op[0] == "noop": cycles = 1 elif op[0] == "addx": cycles = 2 for i in range(cycles): cycle += 1...
CasEbb/Advent-of-Code-2022
10/10.py
10.py
py
795
python
en
code
0
github-code
1
43439917172
import tests_suite import unittest from cpu import CPU from ram import RAM from rom import ROM class tests_ld_rr_nn(unittest.TestCase): def test_ld_BC_nn_correctly_stores_value_to_BC(self): cpu = CPU(ROM(b'\x01\xba\xab')) cpu.readOp() self.assertEqual(0xabba, cpu.BC) def test_ld_DE_...
pawlos/Timex.Emu
tests/tests_ld_rr_nn.py
tests_ld_rr_nn.py
py
2,253
python
en
code
5
github-code
1
70007433955
from __future__ import print_function import wave import numpy as np from struct import unpack class WaveWrap(object): def __init__(self, filename, output_window_size, window_overlap, unpack_fmt="<{}h"): self.wav_buffer_size = output_window_size - window_overlap self.wave_file = wave.open(filename...
lelloman/python-utils
sfft_from_wav.py
sfft_from_wav.py
py
1,927
python
en
code
0
github-code
1
13839587396
################################################################################# # Description: Class for generating augmented data for training of # neural network and SVM # # Authors: Petr Buchal <petr.buchal@lachub.cz> # Martin Ivanco <ivancom.fr@gmail....
LachubCz/ItAintMuchButItsHonestWork
src/batch.py
batch.py
py
6,122
python
en
code
0
github-code
1
11350861272
# -*- coding: utf-8 -*- """Home dashboard layout.""" import locale from apps import utils_dash import dash_bootstrap_components as dbc import dash_core_components as dcc import pandas as pd import plotly.express as px import plotly.graph_objects as go from portfolio.fii import FiiPortfolio from portfolio.funds i...
thobiast/myinvestments
apps/home_dash.py
home_dash.py
py
3,748
python
en
code
3
github-code
1
12556113252
# かぼちゃライブラリを読み込む import CaboCha cabocha = CaboCha.Parser('-n1') def parse_sentence(sentence_str, sentence_begin): # カボチャ関数の呼び出し、係り受け木を取得 tree = cabocha.parse(sentence_str) offset = sentence_begin text = sentence_str for i in range(tree.chunk_size()): # chunk「文節に相当する塊」の事、chanking単語を一番小さい物...
takuyaamamo/NaturalLanguageProcessing
src/cabochatest.py
cabochatest.py
py
2,034
python
ja
code
0
github-code
1
40257633553
'''Find minimum number of merge operations to make an array palindrome Link for this problem is given below: https://www.geeksforgeeks.org/find-minimum-number-of-merge-operations-to-make-an-array-palindrome/ ''' def mergeOperations(arr): n = len(arr) for i in range(n): if arr[i] != arr[n-(i+1)]: ...
barvaliyavishal/DataStructure
GeeksForGeeks/minimum number of merge operations.py
minimum number of merge operations.py
py
389
python
en
code
2
github-code
1
42291469922
import os from torchvision.transforms import CenterCrop from PIL import Image completed_processing = set() source_dir = "C:/Users/jessi/Documents/Master_Courses/MIE1517_IDL/Project/dataset/dataset/" output_dir = "C:/Users/jessi/Documents/Master_Courses/MIE1517_IDL/Project/dataset/processed_dataset/" i = 0 nb_exclude...
ChessieN132D/Self-Supervised-Image-Inpainting
Image Preprocessing/image_center_crop_128.py
image_center_crop_128.py
py
945
python
en
code
0
github-code
1
38712381876
# Imports import bs4 import requests from bs4 import BeautifulSoup # URL Base url_base = 'https://www.who.int' def scrapingCovid(): # URL com os dados do COVID-19 (coloque essa URL no seu navegador e compreenda os dados disponíveis) url = 'https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situati...
AleTavares/scrapingCovid19
scraping.py
scraping.py
py
2,144
python
pt
code
0
github-code
1
33881354393
import numpy from matplotlib import pyplot from utils import timeit @timeit def get_data(): data = [] with open('input.txt') as input_file: for line in input_file: points = tuple((int(x), int(y)) for x, y in (point.split(',') for point in line.strip().split(' -> '))) data.appen...
bdaene/advent-of-code
2022/day14/solve.py
solve.py
py
2,337
python
en
code
1
github-code
1
21563726124
import json from tags.tests.base_test import TagsBaseTestCase class TagNamespaceTestCase(TagsBaseTestCase): fixtures = ["test_authentication.yaml", "test_marketplace.yaml"] def test_create_scoped_namespace(self): ############################## # Creation of global namespace self.log...
Mines-Paristech-Students/Portail-des-eleves
backend/tags/tests/test_namespaces.py
test_namespaces.py
py
5,854
python
en
code
23
github-code
1
70738755233
import re import keyword import os from collections import Counter def add_keywords(python_kw, cpp_kw, java_kw): # keyword.kwlist is a list with python language keywords python_kw.extend(keyword.kwlist) # list of cpp keywords: http://www.cplusplus.com/doc/oldtutorial/variables/ cpp_kw.extend...
aaronojeda/language-detector
LangDetector.py
LangDetector.py
py
4,294
python
en
code
0
github-code
1
21193775708
class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: # 空矩阵,退出 if not grid or not grid[0]: return 0 rows, columns = len(grid), len(grid[0]) # 维度小于3, 退出 if rows < 3 or columns < 3: return 0 count = 0 # 以左上点出发,全...
excaliburnan/SolutionsOnLeetcodeForZZW
840_MagicSquaresInGrid/numMagicSquaresInside.py
numMagicSquaresInside.py
py
1,633
python
zh
code
0
github-code
1
35097748353
# 1 - Напишите программу, которая принимает на вход вещественное число и показывает сумму его цифр. Учтите, что числа могут быть отрицательными # Пример: # 67.82 -> 23 # (-0.56) -> 11 num = input('Введите вещественное число: ') num = num.replace('-', '') x = num.split(".") int_num = int(x[0]) fract_num = int(x[1]...
YMikitas/python
sem/HW2/task13_sum.py
task13_sum.py
py
678
python
ru
code
0
github-code
1
45290308912
# -*- coding: utf-8 -*- import abc import importlib from django.core.exceptions import ImproperlyConfigured from django.conf import settings class BaseEventsPushBackend(object, metaclass=abc.ABCMeta): @abc.abstractmethod def emit_event(self, message:str, *, routing_key:str, channel:str="events"): pa...
phamhongnhung2501/Taiga.Tina
fwork-backend/tina/events/backends/base.py
base.py
py
1,213
python
en
code
0
github-code
1
5047930515
from flask import Flask from flask import render_template, url_for, jsonify, request from game import Game app = Flask(__name__) @app.route('/') def main(): return render_template('index.html') game=0 @app.route('/init', methods=['POST']) def init(): global game game = Game() game.start() # I ha...
Samcfuchs/DataSci
2048/server.py
server.py
py
807
python
en
code
0
github-code
1
34490854766
import json filename = r'/home/xxm/下载/qlora/data/estate_qa.json' with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip() example = json.loads(line) content = example['output'] if content == '': print(example)
xxm1668/qlora_chatglm
data_processon.py
data_processon.py
py
320
python
en
code
4
github-code
1
2299113487
import os import json def get_ground_truth(filename): #0022000159342.jpg #0022000159342_1.jpg if filename.find("_")!=-1: return filename[0:filename.find("_")] else: return filename[0:filename.find(".")] f = open("single_test.txt","r") for line in f.readlines(): d...
xulihang/Barcode-Reading-Performance-Test
utils/create_ground_truth_for_barcode_bb.py
create_ground_truth_for_barcode_bb.py
py
891
python
en
code
11
github-code
1
36260433523
import streamlit as st import pandas as pd import pickle from random import randint books = pd.read_csv('df_2.csv') df_1 = pickle.load(open('df_1.pkl', 'rb')) def recommendation(title): recommendations = pd.DataFrame(df_1.nlargest(11, title)['title']) recommendations = recommendations[recommendations['title'...
Hainguyendangduc/BookRecommendation
app.py
app.py
py
1,748
python
en
code
0
github-code
1
32156179471
""" Python module to parse FastQC output data. """ from __future__ import print_function class Fadapa(object): """ Returns a parsed data object for given fastqc data file """ def __init__(self, file_name, **kwargs): """ :arg file_name: Name of fastqc_data text file. :type fil...
ChillarAnand/fadapa
fadapa/fadapa.py
fadapa.py
py
2,217
python
en
code
16
github-code
1
75183965793
# -*- coding: utf-8 -*- """ Created on Sun Oct 1 03:00:44 2023 @author: allen """ import math def sc(a, b): r = 0 for i in range(math.ceil(a ** 0.5), (int(b ** 0.5) + 1)): r += i ** 2 return (r) x = int(input()) s = 1 for i in range(x): a = int(input()) b = int(input()) print(f"Case...
zhanallen/zero-judge
zero/a059.py
a059.py
py
349
python
en
code
0
github-code
1
35251753542
'''PROGRAM DESCRIPITON: HMTL form for registration is created and after filling the data, the student details like name,email, course are stored in the MongoDB "Registration" database. ''' # PROGRAMMED BY: PULI SNEHITH REDDY # MAIL ID : snehithreddyp@gmail.com # DATE : 23-09-2021 # VERSION : 3.7.9 # ...
SnehithReddy09/Python
Class Assignments/Storing deatils of HTML form in Mongodb/app.py
app.py
py
2,383
python
en
code
0
github-code
1
31623979015
import socket import json import sys # for exit # Create a UDP socket at client side UDPClientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Initialize variables udp_port = 1234 local_host = socket.gethostname() serverAddressPort = (local_host, udp_port) IPAddr = socket.gethostbyname(local_host) buffer_...
pmdung2011/Simple_Text_SocketProgramming
client.py
client.py
py
2,409
python
en
code
0
github-code
1
29505854194
''' Prepare a word sequence (sentence) with padding - convert a sentence String to list of words in sentence - convert list of words in sentence to array of word_embedding and padded ''' import numpy as np from keras.preprocessing import sequence from textblob import Sentence from src.static_variable import loa...
jamemamjame/JameChat
coding_model/preprocess/word_seq_perp.py
word_seq_perp.py
py
3,013
python
en
code
0
github-code
1
36031611270
class CSP: ''' Class to solve a problem using CSP approach. Contains all the functions relevant to the CSP. ''' def __init__(self, graph): self.graph = graph def degree_heuristic(self, vertices): ''' orders the vertices of the graph based on the degree and retu...
sasivs/AI-Lab
graph_color.py
graph_color.py
py
8,056
python
en
code
0
github-code
1
38806583081
import pygame import math # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLUE = (0, 0, 250) RED = (255, 0, 0) pygame.init() # Set the width and height of the screen [width, height] size = (800, 700) screen = pygame.display.set_mode(size) pygame.display.set_caption("My Game") # Loop...
omarjcm/p59-programacion_hipermedial
code/rv/caracteristicas/01_taller.py
01_taller.py
py
2,876
python
en
code
1
github-code
1
33283932467
import datetime from django.shortcuts import render from django.db.models import Subquery, Count from django.http import HttpResponseRedirect from django.views.decorators.cache import cache_page from port.models import Port from stats.models import Submission, PortInstallation from port.filters import PortFilterByMul...
macports/macports-webapp
app/views.py
views.py
py
1,811
python
en
code
49
github-code
1
13563725205
""" the Bot makes everyday posts with some picture+Belarusial legal word and its definition """ #!/usr/bin/python3 import telegram import time TOKEN = 'your_token_here' bot = telegram.Bot(token=TOKEN) chat_id='your_chat_id_here' f = open('dictionary.txt', 'r', encoding='UTF-8') words = f.read().split('\n') f.close()...
HauryDow/bel_legal_lang_bot
Bel_legal_language_bot.py
Bel_legal_language_bot.py
py
760
python
en
code
0
github-code
1
8246364725
import matplotlib.pyplot as plt from matplotlib import ticker # taken from https://scikit-learn.org/stable/auto_examples/manifold/plot_compare_methods.html#sphx-glr-auto-examples-manifold-plot-compare-methods-py def plot_3d(points, points_color, title): x, y, z = points.T fig, ax = plt.subplots( fig...
MoritzM00/Bachelor-Thesis
python/plot_utils.py
plot_utils.py
py
1,064
python
en
code
0
github-code
1
9441754915
import numpy as np import tensorflow as tf def draw_batch(batch_size): xs = np.random.choice([0.0, 1.0], [batch_size, 2]) ys = np.array(list(map(lambda x: [x[0] != x[1]], xs))) return (xs, ys) # first layer - weights + bias W1 = tf.Variable(tf.random_uniform([2, 2], -1, 1), name="W1") b1 = tf.Variable(t...
foss-ag/workshop_tensorflow
src/solutions/xor.py
xor.py
py
1,071
python
en
code
1
github-code
1
9389708795
def handle(client,topic,payload,mem): topic_s = topic.split('/') if topic_s[2] == 'task1' and topic_s[3] == 'requests': return if topic_s[2] == 'task1' and topic_s[3] == 'responses': #print(mem) # identify operation id = int(payload[0:4]) output = str(mem[id]) + ":::" + ...
zhouy1017/MQTT-Demo
handler.py
handler.py
py
408
python
en
code
0
github-code
1
12429451740
import sys if sys.version_info[0] >= 3: unicode = str def get_str(s): """ :param str|unicode|bytes s: :rtype: str|unicode """ if isinstance(s, (str, unicode)): return s if isinstance(s, bytes): return s.decode("utf8") raise Exception("Type not supported: %r" % s)
jotix16/tools
i6lib/str_.py
str_.py
py
316
python
en
code
0
github-code
1
45140457164
from telebot import types from datetime import date, timedelta from ...utils import constants def get_days(room_name: str) -> types.InlineKeyboardMarkup: now = date.today() markup = types.InlineKeyboardMarkup() for day in range(7): """ add in InlineKeyboard """ w_day = now + timedelta(days...
BernarBerdikul/mybooking
mybooking/core/bot_services/get_days.py
get_days.py
py
1,086
python
en
code
1
github-code
1
40898453515
# 백준 6단계 문자열 # 10809번 알파벳 찾기 import sys sys.stdin = open('input.txt') input = sys.stdin.readline # 여기부터 제출해야 한다. input_word = input() list_result = [-1 for i in range(26)] # print(list_result) # ord(i)-97로 input world의 문자들이 알파벳의 몇 번째 숫자인지 구한다. for i in input_word: # input_word.find(i)로 처음 나온 알파벳의 위치를 입력해준다....
boogleboogle/baekjoon
step/6/3_10809.py
3_10809.py
py
533
python
ko
code
0
github-code
1
6304937748
import cv2 import math import numpy as np import pyautogui as gui cap = cv2.VideoCapture(1) while(cap.isOpened()): ret, img = cap.read() #cv2.resizeWindow('window1', 768,1366) cv2.rectangle(img, (0,0), (200,200), (0,255,0),0) ##left hand rectangle cv2.rectangle(img,(630,200),(430,0),(0,255,0),0) ##rig...
DB11051998/RGBGesture-control
gest.py
gest.py
py
6,146
python
en
code
0
github-code
1
12143832924
import config import classes.player import classes.club def create_players(): ''' ABOUT: Creates the players for the game. gametype tells us whether it's a single game or a league so that we can generate the right number of players. names set to None will allow us to randomly generate them. ...
chimel3/stormbowl
createplayers.py
createplayers.py
py
3,440
python
en
code
0
github-code
1
73034200353
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>` ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import ( MagicMock,...
shineforever/ops
salt/tests/unit/states/mdadm_test.py
mdadm_test.py
py
3,815
python
en
code
9
github-code
1
21026304473
# -*- coding: utf-8 -*- """ Created on Wed Apr 12 14:13:33 2017 预处理获取小波系数、重构系数、模极大值 对预处理后的序列进行特征提取,包括能量、归一化能量、能量熵、能量矩、排列熵、近似熵、样本熵、最大Lyapunov指数、灰度矩 分形维数、奇异熵 @author: baishuhua """ import pywt import numpy as np from scipy import stats import sys sys.path.append('E:\\大数据\\基础研究\\HilbertHuang变换') import HilbertHuang impor...
baishuhuaGitHub/Transformer-Simulink
DwtFeatureExtraction.py
DwtFeatureExtraction.py
py
14,858
python
en
code
3
github-code
1
11351681816
import os Import('CfgmEnv') env = CfgmEnv.Clone() setup_sources = [ 'setup.py', 'requirements.txt', 'MANIFEST.in', ] setup_sources_rules = [] for file in setup_sources: setup_sources_rules.append(env.Install(Dir('.'), File(file).srcnode())) local_sources = [ ...
Juniper/contrail-dev-controller
src/config/common/SConscript
SConscript
4,415
python
en
code
3
github-code
1
28993145664
#!/usr/bin/env python3 from argparse import ArgumentParser from collections import namedtuple import hashlib import json import os import shutil LayerInfo = namedtuple('LayerInfo', ['path', 'metadata', 'contenthash']) def hash(data): m = hashlib.sha256() m.update(bytes(data, 'utf-8')) return m.hexdigest...
iknow/nix-utils
oci/build-image-manifest.py
build-image-manifest.py
py
3,280
python
en
code
0
github-code
1
11424782465
arr = [-2, -3, 4, -1, -2, -1, 5, -3, 8] first_index = 0 end_index = 0 s = 0 best = 0 for i in range(1, len(arr)): s = s + arr[i] if(s > 0): best = best + s end_index = i if(arr[i] >= best): best = arr[i] s = 0 first_index = i end_index = 0 print(first_inde...
mshadloo/Algorithm
max-subarray.py
max-subarray.py
py
352
python
en
code
0
github-code
1
4422201464
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for :mod:`orion.algo.evolution_es`.""" import copy import hashlib import numpy as np import pytest from orion.algo.evolution_es import BracketEVES, EvolutionES, compute_budgets from orion.algo.space import Fidelity, Real, Space @pytest.fixture def space(): ...
lebrice/orion
tests/unittests/algo/test_evolution_es.py
test_evolution_es.py
py
11,353
python
en
code
null
github-code
1
30294078087
import retrogamelib as rgl import pygame, random, sys, os from retrogamelib.constants import * from objects import spritesheet, flip_images class Intro(object): def __init__(self): load_image = rgl.util.load_image self.oldman1 = spritesheet("data/lawn-mower.png", (96, 96)) self.bubbma...
randyheydon/BubbMan2-PND
lib/intro.py
intro.py
py
3,742
python
en
code
4
github-code
1
16874544930
#!/usr/bin/env python3 import argparse import sys from KaSaAn.functions import prefixed_snapshot_analyzer def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description='Get cumulative and mean distribution of complex sizes, plus distribution of numbe...
yarden/KaSaAn
KaSaAn/scripts/prefixed_snapshot_analyzer.py
prefixed_snapshot_analyzer.py
py
1,606
python
en
code
null
github-code
1
26355673371
import importlib from pathlib import Path, PurePath import glob import os import logging import numpy as np from pydub import AudioSegment import pandas as pd import cv2 # TODO: General solution # TODO: Can string_filtering be called by generate_filenames? # TODO: output only benign file? # TODO: think about input ...
wdwlinda/Snoring_Detection_full
dataset/dataset_utils.py
dataset_utils.py
py
23,868
python
en
code
0
github-code
1
10304558871
import CompanyClasses if __name__ == "__main__": # Mitarbeiter erzeugen m1 = CompanyClasses.Mitarbeiter("Nimit", "Singh", 21, "Verkaufsleiter", 1900) m2 = CompanyClasses.Mitarbeiter("Phillip", "Schueler", 18, "Programmierer", 2000) # Gruppenleiter erzeugen g1 = CompanyClasses.Gruppenleit...
nimitsingh7/nimitsingh7-SWP-SP-02-21
Company.py
Company.py
py
1,412
python
de
code
0
github-code
1
4154952558
# # # UtmTrav : calculation of an open and cloded traverse # projected on planeor UTM projected grid. # # from pygeodesy.dms import toDMS, parseDMS from pygeodesy import Utm,parseUTM5,Ellipsoids import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import yaml,sys from...
phisan-chula/Construction_Survey
UtmTraverse/UtmTrav.py
UtmTrav.py
py
13,935
python
en
code
3
github-code
1
39206311612
#!/bin/python3 __author__ = "Adam Karl" """Find the sum of all numbers below N which divide the sum of the factorial of their digits""" #https://projecteuler.net/problem=34 digitFactorials = [] def sumCuriousNumbersUnderN(n): """Return a sum of all numbers that evenly divide the sum of the factorial of their dig...
adamkkarl/ProjectEuler
34/euler34.py
euler34.py
py
1,135
python
en
code
0
github-code
1
1528409753
import copy import os import numpy as np from metadrive.manager.base_manager import BaseManager from metadrive.scenario.scenario_description import ScenarioDescription as SD, MetaDriveType from metadrive.scenario.utils import read_scenario_data, read_dataset_summary class ScenarioDataManager(BaseManager): DEFAU...
metadriverse/metadrive
metadrive/manager/scenario_data_manager.py
scenario_data_manager.py
py
8,264
python
en
code
471
github-code
1
704796313
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Reading the file data=pd.read_csv(path) #Code starts here # Step 1 #Reading the file #Creating a new variable to store the value counts loan_status=data["Loan_Status"].value_counts() #Plotting bar pl...
raghulsenthilkumar/greyatom-python-for-data-science
visulization/code.py
code.py
py
2,181
python
en
code
1
github-code
1
34568931935
import random import sys sys.tracebacklimit = -1 errors = (AttributeError, ValueError) #let's make it a class so it's easier to modify class TicTacToe(): def __init__ (self, gameboard = None): self.gameboard = gameboard self.gameboard = [] self.player = None #let's build the Gameboard def build...
jenellyparra/TicTacToe
tictactoe.py
tictactoe.py
py
2,239
python
en
code
0
github-code
1
44962919854
from tkinter import * from tkinter import messagebox from PIL import ImageTk, Image import pygame import time import threading import serial pygame.mixer.init() arduinoData = serial.Serial('COM3', 9600) test = False musica = False ''' Esta función se encarga de crear la ventana principal, donde se muestra la consola d...
josuect0212/Proyecto-3-Robot-con-Control-CE-1102
ProyectoIII.py
ProyectoIII.py
py
8,931
python
es
code
0
github-code
1
32330400016
import os import requests import time import pyfiglet req = requests.get('https://google.com') os.system('clear') print ("Fuck Dunia Percintaan") time.sleep(1) os.system('clear') print ("\33[36;1m") text = pyfiglet.figlet_format("SantriXploiter") print (text) print print ("[1] Tentang SantriXploiter") pri...
santrixploiter/santri
sx.py
sx.py
py
1,344
python
en
code
0
github-code
1
21753112789
# import the required modules and types for this example... from typing import Any, Dict, List # import the paginator and modal... from discord.ext.modal_paginator import ModalPaginator, PaginatorModal # import the discord.py module import discord from discord.ext import commands bot = commands.Bot(command_prefix=c...
Soheab/modal-paginator
examples/verify_command.py
verify_command.py
py
5,303
python
en
code
2
github-code
1
11710691906
""" 1. Imports and definitions """ # i) imports import matplotlib.pyplot as plt import torch import pyro import pyro.distributions as dist from pyro.infer import SVI, Trace_ELBO from pyro.optim import Adam import seaborn as sns """ 2. Data & stochastic model """ # i) Generate data true_mean = torch.te...
atlasoptimization/stochastic_modelling
pyro_experiments/pyro_tests_posterior_v_model.py
pyro_tests_posterior_v_model.py
py
3,463
python
en
code
0
github-code
1
20522292534
import os import shutil declare_namespace_template = """ import pkg_resources pkg_resources.declare_namespace(__name__) """ pkgutil_extend_path_template = """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) """ module_template = """ print ('this is module %s' % __name__) """ setup_templat...
pyinstaller/pyinstaller
tests/scripts/eggs4testing/build-nspkg-tests.py
build-nspkg-tests.py
py
3,601
python
en
code
10,769
github-code
1
7990357254
import logging import os from pprint import pprint from gensim import corpora, models, similarities logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if (os.path.exists("tmp/mesh.dict")): dictionary = corpora.Dictionary.load('tmp/mesh.dict') corpus = corpora.MmCorpus('tm...
meetsha/gensim
test_models.py
test_models.py
py
918
python
en
code
0
github-code
1
7419751756
import core.constants as const from core.aiml_sample import aiml_processing def processing(data: str, kernel, input_memory, is_empty: bool, ans: str='') -> dict: if not is_empty: id_current, is_user_msg, answer = data.split(sep=';', maxsplit=2) id_current = int(id_current) is_user_msg = in...
VasenkovArtem/chatbot_second_team
backend/core/processing.py
processing.py
py
1,118
python
en
code
0
github-code
1
26923650558
from flask import request, jsonify, Blueprint from flask_jwt_extended import jwt_required, current_user from models.Containers_model import Container from models.Image_model import Image from models.db import db from controller import Containers_controller as containerctl from utils import check_authorization containe...
abhirambsn/stuniq-web-desktop
backend/routes/Container_routes.py
Container_routes.py
py
7,313
python
en
code
0
github-code
1
73276503395
""" Microdeploy Configuration manager. """ import yaml import glob import re import os class Config(object): # config = None def __init__(self, config_filename=None, default_baudrate=115200, override={}): if config_filename: try: with open(config_filename) as config_fil...
damiencorpataux/microdeploy
microdeploy/config.py
config.py
py
5,313
python
en
code
1
github-code
1
15066006918
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup(name='immudb-py', version='1.4.0', license="Apache License Version 2.0", description='Python SDK for Immudb', long_description=long_description, long_description_content_type="text/mark...
codenotary/immudb-py
setup.py
setup.py
py
1,404
python
en
code
40
github-code
1
40033104803
# -*-coding: utf-8 -*- # Python 3.6 # Author:Zhang Haitao # Email:13163385579@163.com # TIME:2018-08-15 16:04 # NAME:zht-wind_api.py import datetime import multiprocessing import pickle from WindPy import w from utils.dateu import get_today import numpy as np DIR=r'e:\tmp_wind' w.start() import pandas as pd impor...
luilui163/zht
data/wind/wind_api.py
wind_api.py
py
4,251
python
en
code
0
github-code
1
37658889204
#!./icao-venv/bin/python3 # needs: opencv2-python # opencv2-contrib-python # dlib import os from pathlib import Path import sys import cv2 import dlib import numpy as np import json show_rectangle = False # set here, where to look for pretrained models: datadir = Path("data") # following fi...
Anaeijon/icao_check
geometry_check/geometry_check.py
geometry_check.py
py
8,700
python
en
code
0
github-code
1
26575618453
from odoo import models, fields, api class AccountInvoice(models.Model): _inherit = "account.invoice" channel_id = fields.Many2one( "purchase.order.channel", string="Channel", ondelete="restrict" ) @api.onchange("origin") def onchange_origin(self): order = self.env["purchase.or...
calyx-servicios/custom-sustentar
purchase_order_channel/models/account_invoice.py
account_invoice.py
py
403
python
en
code
0
github-code
1
33842505413
#!/usr/bin/env python import unittest import os import shutil import multiprocessing import glob from matador.scrapers.castep_scrapers import res2dict ROOT_DIR = os.getcwd() REAL_PATH = "/".join(os.path.realpath(__file__).split("/")[:-1]) + "/" TEST_DIR = REAL_PATH + "/tmp_test" NUM_CORES = multiprocessing.cpu_count(...
ml-evs/ilustrado
ilustrado/tests/test_init.py
test_init.py
py
3,373
python
en
code
2
github-code
1
37571536835
from rest_framework import serializers from .models import RedditPost, RedditPostSnapshot class RedditPostSerializer(serializers.HyperlinkedModelSerializer): # snapshots = serializers.HyperlinkedRelatedField( # many=True, # read_only=True, # view_name='reddit_post_snapshots' # ) c...
SDupZ/memex
reddit/serializers.py
serializers.py
py
811
python
en
code
2
github-code
1
31904422454
# dash_callbacks.py from dash.dependencies import Input, Output from dashboard.dash_app import app from dashboard.dash_aux import get_pending_html_table from session.sc_helpers import QuitMode from dashboard.sc_df_manager import DataframeManager from binance import enums as k_binance from datetime import datetime, tim...
xavibenavent/scorpius
src/dashboard/dash_callbacks.py
dash_callbacks.py
py
20,621
python
en
code
0
github-code
1
34469305090
k, n = map(int, input().split()) arr = [] # cnt번째 자리 숫자 결정 def select(a): # 종료조건 # 횟수n 넘으면 if a == n+1: print(*arr) return # 재귀호출 # 1부터 시작해서 사전순으로 정렬됨 for i in range(1, k+1): # i를 위한 연산 arr.append(i) select(a+1) # i에 대한 역 연산 arr.pop() se...
yeafla530/algorithms
코드트리/IL/백트래킹/k개중에1개를n번뽑기.py
k개중에1개를n번뽑기.py
py
660
python
ko
code
0
github-code
1
38105929547
#!/usr/bin/python # -*- coding:utf-8 __author__ = 'lvfei' # id int(8) not null primary key auto_increment, # rec_algorithm_test_id int(8) not null, # package_name char(100) not null, # package_title char(255) not null, # package_icon Text not null, # package_info Text not null, # partin_num TINYINT not...
kkfnui/ToolKit
src/sql2Java/sql2Java.py
sql2Java.py
py
9,052
python
en
code
0
github-code
1
17847754743
from __future__ import nested_scopes from twisted.internet import defer import sys class _DeferredCache: """ Wraps a call that returns a deferred in a cache. Any subsequent calls with the same argument will wait for the first call to finish and return the same result (or errback). """ ha...
rcarmo/divmod.org
Sine/xshtoom/defcache.py
defcache.py
py
3,176
python
en
code
10
github-code
1
22992656893
# -*- coding: utf-8 -*- import asyncio from playwright.async_api import async_playwright from cf_clearance import async_retry, stealth_async async def main(): async with async_playwright() as p: browser = await p.chromium.launch(headless=False, proxy={"server": "socks5://localhost:7890"}, args=[ ...
0therGuys/cf_clearance
tests/test_async_cf.py
test_async_cf.py
py
1,256
python
en
code
null
github-code
1
15891473847
import os import cv2 as cv import numpy as np imagedb_train = ('imagedb_train') sift = cv.xfeatures2d_SIFT.create() folders = os.listdir(imagedb_train) def extract_local_features(path): img = cv.imread(path) kp = sift.detect(img) desc = sift.compute(img, kp) desc = desc[1] retur...
SteliosMouslech/Computer-Vision-Duth
Project 3/CreateVoc_CreateTrainDiscs.py
CreateVoc_CreateTrainDiscs.py
py
2,340
python
en
code
1
github-code
1
70716332195
from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm # 비어있는 폼 제공 from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout # Create your views here. def login(request): if request.method == 'POST': # 로그인폼을 입력하고 로그인을...
ysparrk/Django
230322/01_auth_template/accounts/views.py
views.py
py
1,386
python
ko
code
0
github-code
1
30352443016
from config import * from lib import cords, led from utils.time import sleep_ms def _is_row(side): return side == cords.TOP or side == cords.BOTTOM def lines(gen, source=cords.TOP): side = DISPLAY_ROWS if _is_row(source) else DISPLAY_COLUMNS other_side = DISPLAY_COLUMNS if _is_row(source) else DISPLAY_R...
LeLuxNet/GridPy
animations/coded/lines.py
lines.py
py
714
python
en
code
0
github-code
1