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
29325722402
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ To read sequentially the data from the hard disk, the data format is convert to TFRecord. """ import re from pathlib import Path import pandas as pd import numpy as np import tensorflow as tf from tqdm import tqdm from sklearn.utils import shuffle __d...
ichiro-takahashi/tomoe-realbogus
src/data/make_record.py
make_record.py
py
3,756
python
en
code
2
github-code
6
27251363866
""" 文件名: Code/Chapter07/C02_RNNImgCla/FashionMNISTRNN.py 创建时间: 2023/4/27 8:08 下午 作 者: @空字符 公众号: @月来客栈 知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest """ import torch import torch.nn as nn import sys sys.path.append('../../') from Chapter06.C04_LN.layer_normalization import LayerNormalization class FashionMNIST...
moon-hotel/DeepLearningWithMe
Code/Chapter07/C02_RNNImgCla/FashionMNISTRNN.py
FashionMNISTRNN.py
py
1,754
python
en
code
116
github-code
6
75282287228
import re import sys def part1(): recepies = [3, 7] a_index, b_index = 0, 1 in_data = 440231 while len(recepies) < in_data + 10: s = recepies[a_index] + recepies[b_index] for l in str(s): recepies.append(int(l)) recepies_len = len(recepies) a_index = (a_index + recepies[a_index] + 1) % recepies_le...
elitan/adventofcode
2018/14/main.py
main.py
py
1,209
python
en
code
1
github-code
6
30590549707
import numpy as np from pathlib import Path from PIL import Image, ImageDraw, ImageFont from tqdm import tqdm SQSIZE = 60 SPACING = 15 def make_col(start, end, n=5): """Create a column of numbers.""" nums = np.random.choice(np.arange(start, end+1), size=n, replace=False) return nums def generate_card(): ...
Lewistrick/bingogenerator
bingo.py
bingo.py
py
3,060
python
en
code
0
github-code
6
21884308147
"""Setting up various cosmic populations.""" from frbpoppy import CosmicPopulation # You can set up a population with arguments ... pop = CosmicPopulation(1e4, n_days=1, name='my_own_population', repeaters=True, generate=False) # ... but also adapt specific components: # The numer density / dis...
TRASAL/frbpoppy
examples/setting_up_populations.py
setting_up_populations.py
py
1,478
python
en
code
26
github-code
6
9830880946
# -*- coding: utf-8 -*- ## # @file __init__.py # @brief Contain paths to information files # @author Gabriel H Riqueti # @email gabrielhriqueti@gmail.com # @date 06/05/2021 # import os from pathlib import Path PATH_NERNST_EQUATION_INFO = Path(os.path.abspath(__file__)).parent / 'nernst_equation.txt' PA...
gabrielriqu3ti/biomedical_signal_processing
biomedical_signal_processing/info/__init__.py
__init__.py
py
670
python
en
code
0
github-code
6
34913449577
import numpy as np import scipy.integrate import scipy.optimize import bokeh.plotting from bokeh.plotting import figure, output_file, show import bokeh.io from bokeh.models import Span def dilute(molecule_diluted,molecules_0,DR=0.2): #input Object want to dilute and where the parameters is stored molecules_0...
william831015/GRN-in-chemostat
scripts/functions.py
functions.py
py
3,004
python
en
code
0
github-code
6
4992423632
from __future__ import annotations import typing from homeassistant.components.switch import ( DOMAIN as PLATFORM_SWITCH, SwitchEntity, ) try: from homeassistant.components.switch import SwitchDeviceClass DEVICE_CLASS_OUTLET = SwitchDeviceClass.OUTLET DEVICE_CLASS_SWITCH = SwitchDeviceClass.SWITC...
ZioTitanok/HomeAssistant-Configuration
custom_components/meross_lan/switch.py
switch.py
py
4,016
python
en
code
0
github-code
6
71780096828
from colorfield.fields import ColorField from django.core.validators import MinValueValidator, RegexValidator from django.db import models from users.models import User class Ingredient(models.Model): """Класс интредиент""" name = models.CharField( verbose_name='Наименование ингредиента', ma...
GirzhuNikolay/foodgram-project-react
backend/recipes/models.py
models.py
py
7,583
python
ru
code
0
github-code
6
73811427708
from torch.utils.data import DataLoader from sklearn.model_selection import KFold from .datasets import get_cifar10_datasets, get_cifar100_datasets, get_mnist_datasets, get_image_net_dataset, TruncatedDataset, MergedDataset from .partition import partition_by_class, partition_with_dirichlet_distribution data_path = '...
somcogo/embedding
utils/data_loader.py
data_loader.py
py
3,860
python
en
code
0
github-code
6
22610043366
from django import forms from django.forms.models import inlineformset_factory from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, Fieldset, Div, HTML, Submit, Button from hybridjango.custom_layout_object import * from hybridjango.mixins import BootstrapFormMixin from .models impor...
hybrida/hybridjango
apps/events/forms.py
forms.py
py
3,382
python
en
code
4
github-code
6
14205447601
#!/usr/bin/env python # coding: utf-8 # ## Single Dimension Array # In[1]: import pandas as pd import matplotlib.pyplot as plt # In[2]: data = [10, 23, 34, 35, 45, 59] df = pd.DataFrame(data, columns=['Score']) df # In[3]: #plt.pie(df) plt.pie(df, labels=df['Score']) plt.title("Students Score") plt.show() ...
AileshC/PythonLearning
python_notebooks/MatPlotLib_Pie_Demo.py
MatPlotLib_Pie_Demo.py
py
1,233
python
en
code
1
github-code
6
38116639709
print("'0' for exit") #take ch input from the user ch = input('ch: ') if (ch == '0'): exit() elif ch.isnumeric(): print('digit') elif ch.isalpha(): print('alphabet') else: print('neither alphabet nor digit')
3Sangeetha3/python
if_elif_else.py
if_elif_else.py
py
224
python
en
code
1
github-code
6
6629686746
import tensorflow as tf from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession #Configure GPU config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) for gpu in tf.config.experimental.list_physical_devices('GPU'): tf.confi...
jfgf11/ml_genn_examples_ssh
Sequential API/mobilenetv1.py
mobilenetv1.py
py
7,524
python
en
code
0
github-code
6
43095956138
import plugins import sys import data import model plugins.load_all('config.json') target = sys.argv[1] start_node = model.Node('person', target) d = data.Storage(target) d.add_node(start_node) def handle(tokens): if tokens[0].lower() == 'list': # show list of nodes if len(tokens) > 1: ...
tracer-sec/osint
console.py
console.py
py
2,022
python
en
code
8
github-code
6
39540715020
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 15 2021 @author: sagrana """ from rest_framework import status from rest_framework.generics import CreateAPIView, RetrieveAPIView from rest_framework.response import Response from rest_framework.permissions import AllowAny from .models import User fr...
theRuthless/stark_ly3000_web_app
backend/users/views.py
views.py
py
1,740
python
en
code
0
github-code
6
35007798704
from src.main.python.Solution import Solution # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. # # Note: # Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) # The solution set...
renkeji/leetcode
python/src/main/python/Q015.py
Q015.py
py
1,482
python
en
code
0
github-code
6
27811540343
""" 쳅터: day 5 주제: 재귀함수(recursion) 자기 자신을 호출하는 함수 문제: A. 팩토리얼 계산 함수 fact를 재귀한수로 정의하여, fact(5)를 호출한 결과를 출력하라 작성자: 윤경환 작성일: 18 10 10 """ def fact(a): #팩토리얼 if a == 1: #a가 1일때 return a #a반환 else: #아닐때 return a*fact(a-1) #재귀함수 사용 print(fact(5)) #출력
younkyounghwan/python_class
lab5_13.py
lab5_13.py
py
427
python
ko
code
0
github-code
6
70264789629
import django, os from django.core.management import call_command from dotenv import load_dotenv def init_db(): """Method to initialize the database with sample data""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'FriendsLessonsSystem.settings') load_dotenv() django.setup() from FriendsLesson...
ValentinGiorgetti/Desafio-Backend
FriendsLessonsSystem/init_db.py
init_db.py
py
1,830
python
en
code
0
github-code
6
14254446016
from __future__ import absolute_import, division, print_function, unicode_literals from _GTW import GTW from _TFL._Meta.Once_Property import Once_Property import _GTW._RST._TOP._elFinder class Error (Exception) : """elFinder error message""" def __init__ (self, code, data = N...
xiaochang91/tapyr
_GTW/_RST/_TOP/_elFinder/Error.py
Error.py
py
689
python
en
code
0
github-code
6
2415322860
import gtk import gobject from tryton.gui.window.view_form.view.form import ViewForm from tryton.gui.window.view_form.view.form_gtk.widget import Widget from tryton.gui.window.view_form.screen import Screen from tryton.common.selection import SelectionMixin from tryton.common.treeviewcontrol import MOVEMENT_KEYS def...
PierreCookie/tryton_pre_mono
tryton/plugins/many2many_selection.py
many2many_selection.py
py
3,934
python
en
code
null
github-code
6
2825738960
# https://www.codewars.com/kata/51c8e37cee245da6b40000bd/train/python # Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. # Example: # Given an input string of: # apples, pears # and bananas # g...
Tadiuz/PythonPrograms
PP/CodeWars/Strip_Comment.py
Strip_Comment.py
py
998
python
en
code
0
github-code
6
7930998505
import numpy as np import matplotlib.pyplot as plt # seulement deux etats def epidemie_1(temps = 50, population = 10**6): propagation = np.array( [[0.9 , 0.1], [0.3, 0.7]]) # 0 -> infecte, 1 -> sain popu = np.array([0, 1]) X_temps = np.linspace(0, temps, temps) Y_infectes = [] for t in range(tem...
kmlst/TIPE-Coding-regions-in-DNA-with-Hidden-Markov-Model
tipe_code.py
tipe_code.py
py
10,617
python
en
code
0
github-code
6
6043134873
import logging import certifi import random, string from elasticsearch import Elasticsearch from flask import Flask, render_template, request, redirect, url_for, flash from datetime import datetime from quiz import quiz app = Flask(__name__) app.secret_key = 'dfuy48yerhfjdbsklueio' es = Elasticsearch( ['https://h...
mcascallares/esquiz
main.py
main.py
py
2,109
python
en
code
1
github-code
6
910310900
import os, sys from glob import glob __all__ = ['context', 'Context'] class Context(object): '''Finds out where the data directory is located etc. The data directory contains data files with standard basis sets and pseudo potentials. ''' def __init__(self): # Determine data direct...
theochem/horton
horton/context.py
context.py
py
1,945
python
en
code
83
github-code
6
26538766731
from backend.common.exceptions.common import RuleValidationException, ParameterException from backend.common.exceptions.mquery import MqueryException from backend.helpers.async_elastic_helper import AsyncElasticHelper from backend.helpers.mquery_helper import MqueryHelper from backend.helpers.yara_helper import YaraHel...
CorraMatte/malstream
backend/facades/yara_retrohunt_facade.py
yara_retrohunt_facade.py
py
2,715
python
en
code
3
github-code
6
16421467025
# Test the models with LG_chem stock # If the prediction is success, Expand the number of stock import math import os import pdb from datetime import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt from tqdm import tqdm import torch import torch.nn as nn from torch.utils.data import D...
groundwater98/Miraeasset_Bigdata_Festival
ML/Prediction/predict.py
predict.py
py
13,225
python
en
code
1
github-code
6
28031383283
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import rospy import cv2 import cv_bridge import sensor_msgs.msg import argparse import numpy as np class image_converter: def __init__(self, input_topic, output_topic): self.image_pub = rospy.Publisher( output_topic, sensor_msgs.msg.Im...
kargenk/image_converter
image_converter.py
image_converter.py
py
1,762
python
en
code
0
github-code
6
9842073923
import redneuronal import random import time import statistics class RedNeuronalGA: def __init__(self, size, config:list, inputsize, mut_rate = 0.01, lastbest_rate = 0.5, tour_size = 10): ''' :param size: :param n_genes: :param config: lista que indica [numero de layers, [numero ...
plt1994/cc5114ne
genalg.py
genalg.py
py
4,234
python
en
code
0
github-code
6
72873485629
import fileinput; import os; path = "E:\pythonProjects\Simple Examples\phpFiles"; data = os.listdir(path); i=0; wordtofind = input("Enter Word To Find"); wordtoreplace = input("Enter Word To Replace"); def manipulate(param): rfile = open(param).read() if rfile.__contains__(wordtofind): rfile = rfile....
ebuddiess/pythonTheSnake
Simple Examples/ContentRenamer.py
ContentRenamer.py
py
527
python
en
code
0
github-code
6
44713652316
import sys import xmltodict color_names = { 'Foreground Color': 'ForegroundColour', 'Background Color': 'BackgroundColour', 'Cursor Text Color': 'CursorColour', 'Ansi 0 Color': 'Black', 'Ansi 1 Color': 'Red', 'Ansi 2 Color': 'Green', 'Ansi 3 Co...
arcadecoffee/iterm-to-mintty
iterm-to-mintty.py
iterm-to-mintty.py
py
1,706
python
en
code
0
github-code
6
25008840061
from osv import fields, osv import ir class partner_wh_rebate(osv.osv): _name = "res.partner" _inherit = "res.partner" _columns = { 'rebate': fields.float('Rebate (%)', digits=(5, 2)), } partner_wh_rebate() class sale_order_rebate(osv.osv): _name = "sale.order" _inherit = "sale.order" ...
factorlibre/openerp-extra-6.1
sale_rebate/sale.py
sale.py
py
7,924
python
en
code
9
github-code
6
33967529914
# -*- coding: utf-8 -*- # !/usr/bin/env python # @Time :2020/7/7 15:39 # @Author :Sheng Chen # @Email :sheng.chen@inossem.com import sys sys.path.append(r'/home/chensheng/likou') from typing import List, Tuple class Solution: rows = [{} for i in range(9)] columns = [{} for i in range(9)] boxes = [{} fo...
fqlovetu/likou_python
37解数独/solution1.py
solution1.py
py
2,979
python
en
code
0
github-code
6
22959918169
#escreva um programa que leia um número inteiro e peça para o usuário escolher qual será a BASE DE CONVERSÃO: # 1-> para binário; 2-> para octal & 3-> para hexadecimal import math print('\n\t Base de Conversão!') num = int(input('\n Informe um número => ')) numConv = str(input(' Informe: \033[1;33m1 - binário, 2...
eduardabenevenutti77/curso_em_video.py
mundo2 - python/if_else/BaseConversao.py
BaseConversao.py
py
891
python
pt
code
0
github-code
6
1293789301
import numpy as np import onnx from tests.tools import expect class Sqrt: @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Sqrt', inputs=['x'], outputs=['y'], ) x = np.array([1, 4, 9]).astype(np.float32) y = np...
gglin001/onnx-jax
tests/node/test_sqrt.py
test_sqrt.py
py
632
python
en
code
7
github-code
6
70005437309
from __future__ import with_statement from fabric.api import * import os, glob, socket import fabric.contrib.project as project PROD = 'spreadwebm.org' PROD_PATH = 'domains/spreadwebm.com/web/public/' ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) DEPLOY_PATH = os.path.join(ROOT_PATH, 'deploy') def clean(): ...
louquillio/spreadwebm.com
fabfile.py
fabfile.py
py
1,127
python
en
code
1
github-code
6
19617294623
# _*_ coding: utf-8 _*_ import os import csv import time import json import logging import numpy as np import tensorflow as tf from sklearn.metrics import auc, roc_curve # calculate_auc : calculate AUC rate def calculate_auc(labels, predicts): fpr, tpr, _ = roc_curve(labels, predicts, pos_label=1) AUC = auc(f...
wangcong15/go-clone
Go-CloneF/src/tfrecord2test.py
tfrecord2test.py
py
15,894
python
en
code
5
github-code
6
27214868635
from enum import IntEnum, auto from typing import List, Mapping, Union, Tuple, Optional from .aetg import AETGGenerator from .matrix import MatrixGenerator from ...model import int_enum_loads from ...reflection import progressive_for __all__ = ['tmatrix'] @int_enum_loads(enable_int=False, name_preprocess=str.upper)...
HansBug/hbutils
hbutils/testing/generator/func.py
func.py
py
3,442
python
en
code
7
github-code
6
26113055515
__authors__ = ["T. Vincent"] __license__ = "MIT" __date__ = "28/06/2018" import logging import numpy import weakref import functools from typing import Optional from ....utils.weakref import WeakList from ... import qt from .. import items from ..items import core from ...colors import rgba logger = logging.getLog...
silx-kit/silx
src/silx/gui/plot/items/_roi_base.py
_roi_base.py
py
27,769
python
en
code
106
github-code
6
28765664515
from async_scrape import Scrape import requests import json from selenium.webdriver import Edge from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = "https://order.marstons.co.uk/" base_dir = "C:/Us...
cia05rf/marstons
webscrape/scrape.py
scrape.py
py
1,223
python
en
code
0
github-code
6
7090155614
import random def limiter(count, num): while count != 0: try: guess = int(input('Guess a number: ')) count -= 1 if guess == (random.randint(1, num)): print('YOU GOT IT RIGHT!') break else: print("\n That was Wr...
jan-far/Guessing_game
task3.py
task3.py
py
1,395
python
en
code
0
github-code
6
70501561789
from django.conf.urls import patterns, include, url urlpatterns = patterns('django_sprinkler', url(r"^get_context/?", "views.get_context", name="get_context"), url(r"^logs/?", "views.watering_logs", name="watering_logs"), url(r"^toggle_valve/(\d+)?/?", "views.toggle_valve", name="toggle_valve"), url(r"...
jpardobl/django_sprinkler
django_sprinkler/urls.py
urls.py
py
517
python
en
code
0
github-code
6
44364885746
''' 3. (fatores) Programa que lê um número inteiro positivo n e determina a sua decomposição em fatores primos calculando também a multiplicidade de cada fator. ''' def main(): n = int(input("Digite um numero (>1): ")) fator = 2 # primeiro fator while n != 1: # conta a multiplicidade de fator em...
danilosheen/topicos-especiais
q3.py
q3.py
py
681
python
pt
code
0
github-code
6
72777565307
# Plotting solution of x''(t) + x(t) = 0 equation import numpy as np import matplotlib.pyplot as plt import os from io import StringIO import pandas as pd from find_solution import find_solution from plot_utils import create_dir def plot_solution(plot_dir, t_end, delta_t): data = find_solution(t_end=t_end, delta_...
evgenyneu/ASP3162
03_second_order_ode/plotting/plot_solution.py
plot_solution.py
py
1,130
python
en
code
1
github-code
6
28382656931
import cgi import sys import io import genshin.database.operation as gdo form = cgi.FieldStorage() sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') template = """ <html> <head> <meta charset="utf-8"> <script type="text/javascript"> location.replace('/cgi-bin/characters.py?dname={name...
waigoma/genshin-charatraining-supporter
src/cgi-bin/character_delete.py
character_delete.py
py
628
python
en
code
0
github-code
6
17717247977
import image def photo_to_bw(filename): img=image.Image(filename) win=image.ImageWin(img.getWidth(),img.getHeight()) img.draw(win) img.setDelay(0) for row in range(img.getHeight()): for col in range(img.getWidth()): p=img.getPixel(col,row) newvalue=(p.getRed()+p.getG...
tim24jones/thinkcspy
Chap_8/09_photo_to_bw.py
09_photo_to_bw.py
py
627
python
en
code
5
github-code
6
8331488278
#!/usr/bin/env python # two functions "dir" and "help" when exploring modules in python. import urllib # function are implemented in each module by using dir function. dir(urllib) # read about module more using help function. help(urllib.urlopen) import re find_members = [] for member in dir(re): if "find" ...
igei-yh/learning-python
basic_modules.py
basic_modules.py
py
397
python
en
code
0
github-code
6
21944300528
# -*- coding: utf-8 -*- """ Created on Mon May 7 23:31:33 2018 @author: liguo 异常数据分析 """ from __future__ import print_function from nets import nets_factory from preprocessing import vgg_preprocessing import sys sys.path.append('../../tensorflow/models/slim/') # add slim to PYTHONPATH import tensorflow as tf impor...
wlkdb/dogs_vs_cats
transfer_learning/analysis_outliers.py
analysis_outliers.py
py
5,865
python
en
code
10
github-code
6
30804272942
#Exercise 1: Cats #Instantiate three Cat objects using the code provided above. #Outside of the class, create a function that finds the oldest cat and returns the cat. #Print the following string: “The oldest cat is <cat_name>, and is <cat_age> years old.”. Use the function previously created. class Cat: def ...
nadinebabenko/python1
week20/day2/XP.py
XP.py
py
4,157
python
en
code
0
github-code
6
25004993355
from typing import cast, Any from aea.skills.behaviours import TickerBehaviour from aea.helpers.search.models import Constraint, ConstraintType, Query from packages.fetchai.protocols.oef_search.message import OefSearchMessage from packages.fetchai.skills.tac_control.dialogues import ( OefSearchDialogues, ) from...
DENE-dev/dene-dev
RQ1-data/exp2/1010-OCzarnecki@gdp8-e6988c211a76ac3a2736d49d00f0a6de8b44c3b0/agent_aea/skills/agent_action_each_turn/behaviours.py
behaviours.py
py
3,601
python
en
code
0
github-code
6
31111183004
def getMoneySpent(keyboards, drives, b): budget_arr = [] for keyboard in keyboards: if keyboards == b: continue for drive in drives: if drive == b: continue if (keyboard + drive) <= b: budget_arr.append(keyboard + drive) if ...
spl99615/hackerrank
electronic_shop.py
electronic_shop.py
py
488
python
en
code
0
github-code
6
26470849611
""" Problem 34: Digit Factorials https://projecteuler.net/problem=34 Goal: Find the sum of all numbers less than N that divide the sum of the factorial of their digits (& therefore have minimum 2 digits). Constraints: 10 <= N <= 1e5 Factorion: A natural number that equals the sum of the factorials of its digits. Th...
bog-walk/project-euler-python
solution/batch3/problem34.py
problem34.py
py
1,839
python
en
code
0
github-code
6
2282915747
import torch from torch import Tensor from kornia.utils import one_hot import torch.nn.functional as F import numpy as np from matplotlib import pyplot as plt def reg_loss(prediction, ED, ES, device): # print(prediction) prediction_toSyn = prediction.squeeze().detach().cpu().numpy() y_k = synthetic_label(p...
carlesgarciac/regression
regression-cmr/utils/reg_loss.py
reg_loss.py
py
1,707
python
en
code
0
github-code
6
26023685530
import numpy as np import numpy as np import matplotlib.pyplot as plt from fealpy.mesh.uniform_mesh_2d import UniformMesh2d from scipy.sparse.linalg import spsolve #from ..decorator import cartesian class MembraneOscillationPDEData: # 点击这里可以查看 FEALPy 中的代码 def __init__(self, D=[0, 1, 0, 1], T=[0, 5]): """...
suanhaitech/pythonstudy2023
Mia_wave/wace_2.py
wace_2.py
py
5,381
python
en
code
2
github-code
6
7298829560
import matplotlib.pyplot as plt from astropy.io import fits from astropy.visualization import make_lupton_rgb from matplotlib.colors import LogNorm from astropy.wcs import WCS import numpy as np db_open = [fits.open('frame-g-006793-1-0130.fits'), fits.open('frame-i-006793-1-0130.fits'), fits.ope...
ViniBilck/Astro-Vinicius
Cubos/Codes/Galaxy - 1/Galaxy1.py
Galaxy1.py
py
2,530
python
en
code
0
github-code
6
26606119063
#!/usr/bin/env python # coding: utf-8 # # Import Library # In[387]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from glob import glob from sklearn.metrics import mean_absolute_error from sklearn.linear_model import LinearRegression from sklearn.linear_model import L...
tamerelateeq/Titanc
titank.py
titank.py
py
8,173
python
en
code
0
github-code
6
14469263973
''' You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. Return the number of pairs of different nodes that are unreachable from each oth...
loganyu/leetcode
problems/2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph.py
2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph.py
py
1,707
python
en
code
0
github-code
6
11467832022
#Vertex class class Vertex: def __init__(self, key): self.id = key self.connected_to = {} #Add neighbors def add_neighbor(self, nbr, weight=0): self.connected_to[nbr] = weight #return all keys in connected to dict def get_connections(self): self.connecte...
sarahovey/AnalysisOfAlgos
hw5/hw5.py
hw5.py
py
6,759
python
en
code
0
github-code
6
73551642109
import random class Rsa: def __init__(self, q=19, p=23, size_of_key=0): self.q = q self.p = p if size_of_key: self.q = self.gen_prime(size_of_key) self.p = self.gen_prime(size_of_key) while self.p == self.q : self.p = self.gen_prime(size...
Ibrahim-AbuShara/End-to-End-Encryption
RSA.py
RSA.py
py
5,861
python
en
code
1
github-code
6
10775113939
import re import os from collections import Counter, defaultdict, namedtuple from itertools import combinations, product from pprint import pprint from parse import parse, findall from math import prod, sqrt dirname = os.path.dirname(__file__) data = open(f'{dirname}/21-input.txt').read().splitlines() data = [parse('{}...
knjmooney/Advent-Of-Code
2020/21-allergens.py
21-allergens.py
py
1,513
python
en
code
0
github-code
6
37111986575
#얘는 계속 실행이 되어야 해서, jupyter notebook에서는 안된다. #이걸 하는 목적 : dialog flow로부터 데이터를 받아, 여기서 처리한 후 다시 dialog flow로 반환 #그걸 위해서는 json으로 리턴해야 한다. import requests import urllib import IPython.display as ipd import json from bs4 import BeautifulSoup from flask import Flask, request, jsonify def getWeather(city) : url = "ht...
ssh6189/2020.02.05
server.py
server.py
py
3,365
python
ko
code
0
github-code
6
38169404173
from . import parse as parser from modules import YaraRules, GeoIP, ProjectHoneyPot, LangDetect class Scanner: def __init__(self): self.yara_manager = YaraRules.YaraManager() def parse_email(self, email_content: str): return parser.parse_email(email_content) def scan(self, email: str): # parse it ...
lukasolsen/EmailAnalyser
server/base/service/scan.py
scan.py
py
2,296
python
en
code
0
github-code
6
2247235592
testname = 'TestCase 4.1.1' avoiderror(testname) printTimer(testname, 'Start', '测试AC通过配置二层vlan发现列表发现AP') ################################################################################ # Step 1 # # 操作 # AC1上面创建vlan20,将端口s1p1划入vlan20。 # AC1上面将vlan20加入到自动发现的vlan列表。 # AC1(config-wireless)#discovery vlan-list 20 # S3上面将s...
guotaosun/waffirm
autoTests/waffirm/waffirm_4.1.1_ONE.py
waffirm_4.1.1_ONE.py
py
5,708
python
en
code
0
github-code
6
73789788989
maior = 0 from random import randint import time from operator import itemgetter dados = {'j1': randint(1,6), 'j2': randint(1,6), 'j3': randint(1,6), 'j4': randint(1,6), 'j5': randint(1,6) } for d,i in dados.items(): time.sleep(1) print(f'joogador {d} tirou o numero {i}') ranking = dict() ranking = sorted(dados...
Kaue-Marin/Curso-Python
pacote dowlond/curso python/exercicio91.py
exercicio91.py
py
419
python
en
code
0
github-code
6
35574468725
from collections import defaultdict def createGraph(): g=defaultdict(list) return g def topoSort(g,indeg,q,cnt,n,res): for i in range(n): if indeg[i] is 0: q.append(i) while(q): cur=q.pop(0) for i in g[cur]: indeg[i]-=1 if(indeg...
goyalgaurav64/Graph
topological-sort-kahns-algo-bfs.py
topological-sort-kahns-algo-bfs.py
py
868
python
en
code
1
github-code
6
27643482594
from rest_framework.decorators import api_view from rest_framework.response import Response from base.serializers import ProductSerializer, UserSerializer, UserSerializerWithToken from base.models import Product @api_view(['GET']) def getProducts(request): query = request.query_params.get('keyword') if query...
hitrocs-polito/smart-bozor
base/views/product_views.py
product_views.py
py
917
python
en
code
0
github-code
6
15551870726
''' Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false. Example 1: Input: nums = [1,2,3,4] Output: false Explanation: There is no 13...
ojhaanshu87/LeetCode
456_132_pattern.py
456_132_pattern.py
py
1,155
python
en
code
1
github-code
6
1149669859
from lib.contents_reader import ContentsReader import asyncio CLEAR_SCREEN = "\u001b[2J" NEW_LINE = "\r\n" class ZineFunctions: def __init__(self, reader, writer, index_file_path): self.reader = reader self.writer = writer self.contents_reader = ContentsReader(index_file_path) asy...
caraesten/dial_a_zine
dialazine/lib/zine_functions.py
zine_functions.py
py
2,161
python
en
code
58
github-code
6
39253810380
from mangaki.models import Artist, Manga, Genre from django.db.utils import IntegrityError, DataError import re from collections import Counter def run(): with open('../data/manga-news/manga.csv') as f: next(f) artists = {} hipsters = Counter() for i, line in enumerate(f): ...
mangaki/mangaki
mangaki/tools/add_manga.py
add_manga.py
py
2,689
python
en
code
137
github-code
6
19107028474
"""Extract data on near-Earth objects and close approaches from CSV and JSON files. The `load_neos` function extracts NEO data from a CSV file, formatted as described in the project instructions, into a collection of `NearEarthObject`s. The `load_approaches` function extracts close approach data from a JSON file, for...
rcmadden/Near-Earth-Objects
extract.py
extract.py
py
2,061
python
en
code
0
github-code
6
12639173645
""" Escribe un programa que calcule las ganancias mensuales de un profesional, correspondientes a 20 días de trabajo, teniendo en cuenta: a. Debe ingresar el monto total por prestación realizada. b. El programa debe descontar el 10,5% correspondiente a impuestos. c. El programa debe mostrar por pantalla el importe brut...
sbelbey/pp-python
Ejercicios_21_al_30/ejercicio30.py
ejercicio30.py
py
1,220
python
es
code
0
github-code
6
36060029870
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class LocalizationNetwork(nn.Module): def __init__(self, numOfControlPoints=10): super().__init__() self.numOfControlPoints = numOfControlPoi...
xpiste05/knn_projekt
models/localizationNetwork.py
localizationNetwork.py
py
1,925
python
en
code
0
github-code
6
72493111869
import vk_api from vk_api.keyboard import VkKeyboard, VkKeyboardColor main = VkKeyboard(one_time=True) main.add_button('Создать жалобу на бандита/лидера☢', color=VkKeyboardColor.PRIMARY) main.add_button('Создать жалобу на лидера☣', color=VkKeyboardColor.POSITIVE) main.add_line() # создание новой строки main.ad...
Qerkdb/forum-bot
keyboards.py
keyboards.py
py
786
python
ru
code
0
github-code
6
13879817833
N, K = map(int, input().split()) x = 0 count = 0 if N % K == 0 : # 바로 나뉠 때 while(N != 1) : count += 1 N = N / K elif N % K != 0 : # 바로 안 나뉠 때 x = N % K # 뺄 값들 count += x N = N - x while(N != 1) : count += 1 N = N / K print(count) result = 0 # 처음...
codusl100/algorithm
백준/그리디/1이 될 때까지.py
1이 될 때까지.py
py
1,147
python
ko
code
0
github-code
6
13461358632
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. Given a non-negative integer n which represents the number of LEDs that are currently on, return al...
szhongren/leetcode
401/main.py
main.py
py
1,182
python
en
code
0
github-code
6
38726912007
from __future__ import unicode_literals import shutil import os HOME = os.path.join('pyupdater', 'vendor') junitxml = os.path.join(HOME, 'PyInstaller', 'lib', 'junitxml', 'tests') unittest2 = os.path.join(HOME, 'PyInstaller', 'lib', 'unittest2') items_to_remove = [junitxml, unittest2] def remove(x): if os.path...
timeyyy/PyUpdater
dev/fix_vendor.py
fix_vendor.py
py
525
python
en
code
7
github-code
6
14988584675
from setuptools import setup package_name = 'leg_controller' setup( name=package_name, version='0.0.0', packages=[package_name], data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], ...
PetriJF/Hexapod
src/leg_controller/setup.py
setup.py
py
813
python
en
code
2
github-code
6
29157516812
#!/usr/bin/env python3 import asyncio from mavsdk import System from mavsdk.gimbal import GimbalMode, ControlMode async def run(): # Init the drone drone = System() await drone.connect(system_address="udp://:14540") # Start printing gimbal position updates print_gimbal_position_task = \ ...
mavlink/MAVSDK-Python
examples/gimbal.py
gimbal.py
py
2,709
python
en
code
246
github-code
6
31973217705
"""filename and file size in file model Revision ID: 6d23296b922b Revises: 6ec29c8de008 Create Date: 2023-03-02 17:47:25.025321 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6d23296b922b' down_revision = '6ec29c8de008' branch_labels = None depends_on = None ...
synzr/file-transfer-service
migrations/versions/6d23296b922b_filename_and_file_size_in_file_model.py
6d23296b922b_filename_and_file_size_in_file_model.py
py
952
python
en
code
0
github-code
6
70943710908
from pytsbe.main import TimeSeriesLauncher def multivariate_launch_example(): """ Example how to launch benchmark with several libraries with different parameters for multivariate time series forecasting For more detailed info check documentation or docstring descriptions in classes below. Import...
ITMO-NSS-team/pytsbe
examples/multivariate_module_launch.py
multivariate_module_launch.py
py
1,037
python
en
code
30
github-code
6
32841420589
import pandas as pd import numpy as np import pickle as pkl import matplotlib.pyplot as plt import re import jieba import subprocess from gensim.test.utils import get_tmpfile, common_texts from gensim.models import Word2Vec, KeyedVectors from sklearn.metrics.pairwise import cosine_similarity from sklearn.manifold impo...
kartd0094775/IdentifyKOL
util/preprocessing.py
preprocessing.py
py
1,846
python
en
code
0
github-code
6
32149840487
# Upload BOJ silver-1 Brute-force 2615번 오목 # 참고 블로그 : https://velog.io/@hygge/Python-%EB%B0%B1%EC%A4%80-2615-%EC%98%A4%EB%AA%A9-Brute-Force import sys board = [list(map(int,input().split())) for _ in range(19)] visited = [[0 for _ in range(19)] for _ in range(19)] win = 0 ways = [[0,1],[1,0],[1,1],[-1,1]] answer...
HS980924/Algorithm
src/2.BruteForce/B#2615_오목.py
B#2615_오목.py
py
1,378
python
en
code
2
github-code
6
21160883826
import os import math import torch import pytorch_lightning as pl import torch.nn.functional as F import torch.nn as nn from numpy import sqrt, argmax from torch.optim import lr_scheduler from .model import CNN import numpy as np import pandas as pd from sklearn.metrics import roc_curve, confusion_matrix, roc_auc_sco...
Junkkkk/ovarian_cancer_detection
models/lightning_model.py
lightning_model.py
py
12,263
python
en
code
1
github-code
6
73019628988
# Bot information SESSION = 'Media_search' USER_SESSION = 'User_Bot' API_ID = 12345 API_HASH = '0123456789abcdef0123456789abcdef' BOT_TOKEN = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11' USERBOT_STRING_SESSION = '' # Bot settings CACHE_TIME = 300 USE_CAPTION_FILTER = False # Admins, Channels & Users ADMINS = [12345789...
Mahesh0253/Media-Search-bot
sample_info.py
sample_info.py
py
1,000
python
en
code
514
github-code
6
7705288630
import json import torch from transformers import GPT2Tokenizer from transformers import GPT2DoubleHeadsModel from MTDNN import MTDNN from tqdm import trange, tqdm from keras_preprocessing import sequence import pandas as pd import Utils import pickle import os from torch.utils.data import TensorDataset, Dat...
anandhperumal/ANA-at-SemEval-2020-Task-4-UNION
MTD-NCH.py
MTD-NCH.py
py
19,668
python
en
code
5
github-code
6
18164640711
import pickle import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer # Download NLTK data (you only need to do this once) nltk.download('stopwords') nltk.download('wordnet') # Load the trained model and vectorizer with open('check_spam_classifier.pkl', 'rb') as clf_file: ...
GOVINDFROMINDIA/Twitter-Scam-Victims
dsg.py
dsg.py
py
1,596
python
en
code
0
github-code
6
41794735960
import datetime import unittest from pyspark import SparkConf from pyspark.sql import SparkSession import pyspark.sql.functions as f from pyspark.sql.types import StructType, StructField, IntegerType, StringType, MapType, ArrayType import json import csv from src.transformations import add_columns, running_total, gro...
SA01/spark-unittest-tutorial
tests/test_transformations.py
test_transformations.py
py
13,745
python
en
code
0
github-code
6
23210233427
import pandas as pd from morpheus import SequentialComposition, ParallelComposition from morpheus.algo.selection import base_selection_algorithm, random_selection_algorithm from morpheus.utils.encoding import * from morpheus.utils import debug_print from sklearn.datasets import make_classification from sklearn.model_...
eliavw/morpheus
src/morpheus/tests/basics.py
basics.py
py
7,311
python
en
code
0
github-code
6
39729133373
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('store', '0010_auto_20151113_1608'), ] operations = [ migrations.AddField( model_name='review', name=...
midnitehighways/shop
store/migrations/0011_review_author.py
0011_review_author.py
py
420
python
en
code
0
github-code
6
36867613594
from datetime import datetime from sqlalchemy import Column, TIMESTAMP class TimestampsMixin: __abstract__ = True __created_at_name__ = 'created_at' __updated_at_name__ = 'updated_at' __datetime_func__ = datetime.now() created_at = Column( __created_at_name__, TIMESTAMP(timezone=...
siarie/fastapi-start
app/db/mixins.py
mixins.py
py
581
python
en
code
0
github-code
6
14555529648
from time import sleep import btc import click from core import BitcoinTwitterProfile import schedule @click.group() def bitc0in_twitter(): """ Syncs your twitter profile with bitcoin's volatility. """ @bitc0in_twitter.command() def run(): """Start Program""" bitcoin_percent_change = btc.get...
dgnsrekt/bitc0in-twitter
bitc0in_twitter/cli.py
cli.py
py
1,335
python
en
code
1
github-code
6
29282262756
# -*- coding: utf-8 -*- import ispformat.schema as _schema from jsonschema import Draft4Validator, RefResolver, draft4_format_checker from jsonschema.exceptions import RefResolutionError, ValidationError from urlparse import urlsplit class MyRefResolver(RefResolver): def resolve_remote(self, uri): # Prev...
Psycojoker/isp-format
ispformat/validator/schemavalidator.py
schemavalidator.py
py
4,121
python
en
code
0
github-code
6
12014916109
''' Find the nearest smaller numbers on left side in an array Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side. Examples: Input: arr[] = {1, 6, 4, 10, 2, 5} Output: {_, 1, 1, 4, 1, 2} First element ('1') has no element on left side. F...
umr55766/warmup
Find-the-nearest-smaller-numbers-on-left-side-in-an-array.py
Find-the-nearest-smaller-numbers-on-left-side-in-an-array.py
py
876
python
en
code
1
github-code
6
6401924379
# version: python 3.7 # zID: z5052292 from socket import * from datetime import datetime import time import sys serverIP = sys.argv[1] serverPort = int(sys.argv[2]) clientSocket = socket(AF_INET, SOCK_DGRAM) list_rtts = [] packets_lost = 0 for i in range(10): time_stamp = datetime.now().isoformat(s...
YuanG1944/COMP9331-Computer-Networks-and-Applications
Lab2/PingClient_zhou.py
PingClient_zhou.py
py
1,235
python
en
code
4
github-code
6
10426011052
"""Conceptual model page.""" from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.images.edit_handlers import ImageChooserPanel class CMPage(Page): template = "ecos_cm/cm_page.html" E...
CNR-ISMAR/ecoads
ecos_cm/models.py
models.py
py
1,600
python
en
code
0
github-code
6
4534058436
#!/usr/bin/env python # -*- coding: UTF-8 -*- import SPARQLWrapper # REF [site] >> https://sparqlwrapper.readthedocs.io/en/latest/main.html def select_example(): sparql = SPARQLWrapper.SPARQLWrapper("http://vocabs.ardc.edu.au/repository/api/sparql/csiro_international-chronostratigraphic-chart_geologic-time-scale-202...
sangwook236/SWDT
sw_dev/python/ext/test/database/sparqlwrapper_test.py
sparqlwrapper_test.py
py
7,970
python
en
code
17
github-code
6
38030500642
import numpy as np import matplotlib.pyplot as plt from tqdm.auto import tqdm """ Reads Siemens rawdata file and returns the DICOs values Author: Ali Aghaeifar <ali.aghaeifar@tuebingen.mpg.de> """ def read_dico(twixObj): mdb_vop = [mdb for mdb in twixObj[-1]['mdb'] if mdb.is_flag_set('MDH_VOP')] # concatenate...
aghaeifar-publications/RFPA_drift
dico_tools.py
dico_tools.py
py
2,283
python
en
code
0
github-code
6
39451137948
from tkinter import Tk, StringVar, Label, Button, Entry, filedialog, W from os.path import exists import generator as gp def cmdExec(): if checkFileExist(textIn.get()) and checkFileExist(textOut.get()): result.set("Gerando planilha de presença ...") isSuccess = gp.main(textIn.get(), textOut.get()) ...
lucasgbezerra/python_projects
attendance_sheet/app.py
app.py
py
2,139
python
en
code
0
github-code
6
70488508987
# accepted on codewars.com import random import math import time conflicts_threshold = 3 # main method def solve_n_queens(size, mandatory_coords): # here we use the simple bactracking if size <= 10: answer = queens_backtrack(size, mandatory_coords) return get_string_of_queens(size, answer) i...
LocusLontrime/Python
CodeWars_Rush/_1kyu/N_queens_problem_1kyu.py
N_queens_problem_1kyu.py
py
7,078
python
en
code
1
github-code
6
71476996348
# 피보나치 수열 import sys input = sys.stdin.readline n = int(input()) # 1번과 2번 더하면 3번, 2번과 3번 더하면 4번.. 이러한 방법이므로 # A는 B의 값을 받고, B는 A의 값을 더해서 받는다. # 최종 결과값은 A A = 0 B = 1 for i in range(n): A, B = B, B+A print(A)
YOONJAHYUN/Python
BOJ/10826.py
10826.py
py
318
python
ko
code
2
github-code
6