content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Inspired by:
# https://codereview.stackexchange.com/questions/42359/condorcet-voting-method-in-oop-python
# and https://github.com/bradbeattie/python-vote-core/tree/master/pyvotecore
import sys
import os
import itertools
def main():
file = sys.argv[1]
if not os.path.isfile(file):
print("File path ... | nilq/baby-python | python |
import os, time
def cmd(cmdd):
os.system(cmdd)
while(True):
time.sleep(2)
cmd("cls")
cmd("python app.py")
| nilq/baby-python | python |
import getpass
import sys
from constants import cx_status
import paramiko
# setup logging
paramiko.util.log_to_file("/tmp/paramiko.log")
# Paramiko client configuration
UseGSSAPI = ( paramiko.GSS_AUTH_AVAILABLE)
DoGSSAPIKeyExchange = ( paramiko.GSS_AUTH_AVAILABLE)
class SilentPolicy(paramiko.MissingHostKeyPolicy)... | nilq/baby-python | python |
# Utilities for reading score-files
import numpy as np
from utils.data_loading import readlines_and_split_spaces
def load_scorefile_and_split_to_arrays(scorefile_path):
"""
Load a scorefile where each line has multiple columns
separated by whitespace, and split each column to its own
array
"""
... | nilq/baby-python | python |
import numpy as np
from numpngw import write_apng
# Example 5
#
# Create an 8-bit RGB animated PNG file.
height = 20
width = 200
t = np.linspace(0, 10*np.pi, width)
seq = []
for phase in np.linspace(0, 2*np.pi, 25, endpoint=False):
y = 150*0.5*(1 + np.sin(t - phase))
a = np.zeros((height, width, 3), dtype=np... | nilq/baby-python | python |
from django.apps import AppConfig
class TmplConfig(AppConfig):
name = 'tmpl'
| nilq/baby-python | python |
from rpython.flowspace.model import Variable, Constant, Block, Link
from rpython.flowspace.model import SpaceOperation, FunctionGraph, copygraph
from rpython.flowspace.model import checkgraph
from rpython.flowspace.model import c_last_exception
from rpython.translator.backendopt.support import log
from rpython.translat... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# # # #
# model-bi-gramms.py
# @author Zhibin.LU
# @created Fri Feb 23 2018 17:14:32 GMT-0500 (EST)
# @last-modified Wed Mar 14 2018 19:11:45 GMT-0400 (EDT)
# @website: https://louis-udm.github.io
# # # #
import gzip
import time
from collections import Counter
import re... | nilq/baby-python | python |
"ZKit-Framework Github : https://github.com/000Zer000/ZKit-Framework"
# Copyright (c) 2020, Zer0 . All rights reserved.
# This Work Is Licensed Under Apache Software License 2.0 More
# Can Be Found In The LICENSE File.
__author__ = "Zer0"
__version__ = "1.4.5"
__license__ = "Apache Software License 2.0"
__status__ = "P... | nilq/baby-python | python |
# Implement Bubble Sort
import time
# we have a data set starting with the very basic happy path to complex
data = {
"data1" : [5,4,1,3,2], # happy path easy to vizualize
"data2" : [5,4,1999,3,2,8,7,6,10,100], #larger range of values
"data3" : [5,4,1,3,2,2], # repeated values
"data4" : ... | nilq/baby-python | python |
import numpy as np
import time
from numba import njit, prange
def exact_solver_wrapper(A_org, Q, p, L, delta_l, delta_g, constr='1'):
"""
Exact attacks for A^1, A^2 or A^{1+2}
param:
A_org: original adjacency matrix
Q: matrix, Q_i = Q[i]
p: ve... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.conf import settings
# Create your models here.
class UserProfileManager(BaseUserManager):
"""Manager for U... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from unittest import TestCase
import os
from auxlib.packaging import get_version
# from auxlib.packaging import (_get_version_from_pkg_info, _is_git_dirty, _get_most_recent_git_tag,
# _get_git_hash,... | nilq/baby-python | python |
from rest_framework import serializers
from daily_tracker.models import Attandance
class AttandanceSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='api:attandance-detail')
class Meta:
model = Attandance
fields = ('id', 'enter_at', 'out_a... | nilq/baby-python | python |
import numpy as num
from decimal import *
import scipy as sci
from numpy.polynomial import polynomial as pol
def euler(f,a,b,n ,y_0):
h=Decimal((b-a))/Decimal(n)
vals = []
vals.append(y_0)
print ("Indice\t | t | Aproximado(u) ")
print("0\t | 0 |\t"+str(y_0))
for i in range (0, n-1):
... | nilq/baby-python | python |
from __future__ import absolute_import
import inspect
from textwrap import dedent
from types import FunctionType
from ..core.properties import Bool, Dict, Either, Int, Seq, String, AnyRef
from ..model import Model
from ..util.dependencies import import_required
from ..util.compiler import nodejs_compile, CompilationE... | nilq/baby-python | python |
import random
import sys
def room(map, times, max, min):
# map
width = len(map)
height = len(map[0])
# Storage generated rooms
rooms = []
for i in range(times):
sp = (random.randint(0, int((width-1)/2))*2+1,
random.randint(0, int((height-1)/2))*2+1)
length = rando... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Main module."""
import warnings
from collections import Counter
from math import sqrt
import mlprimitives
import numpy as np
from mlblocks import MLPipeline
from scipy.stats import entropy
from sklearn import metrics
from sklearn.model_selection import KFold
from sklearn.neighbors import Ne... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.optim as optim
import torch_geometric.transforms as transforms
from torch_geometric.data import Data, Batch
from tensorboardX import SummaryWriter
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d.axes3d as p3
import nump... | nilq/baby-python | python |
"""
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
import pytest
from byceps.services.board.dbmodels.posting import Posting as DbPosting
from byceps.services.board.dbmodels.topic import Topic as DbTopic
from byceps.services.board.tran... | nilq/baby-python | python |
"""
Here is a batch of evaluation functions.
The interface should be redesigned carefully in the future.
"""
import pandas as pd
from typing import Tuple
from qlib import get_module_logger
from qlib.utils.paral import complex_parallel, DelayedDict
from joblib import Parallel, delayed
def calc_long_short_prec(
pr... | nilq/baby-python | python |
from setuptools import setup, find_packages
from os.path import join, dirname
import sys
if sys.version_info[0] != 3 or sys.version_info[1] < 6:
print("This script requires Python >= 3.6")
exit(1)
setup(
name="vkmix",
version="1.5",
author="alekssamos",
author_email="aleks-samos@yandex.ru",
url="... | nilq/baby-python | python |
"""A basic JSON encoder to handle numpy and bytes types
>>> bool_array = np.array([True])
>>> bool_value = bool_array[0]
>>> obj = {'an_array': np.array(['a']), 'an_int64': np.int64(1), 'some_bytes': b'a', 'a_bool': bool_value}
>>> assert dumps(obj)
"""
import base64
import json
from functools import partial
import ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import codecs
import io
import logging
import os
import re
import shutil
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import tempfile
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from py3kwarn2to... | nilq/baby-python | python |
from django.contrib import admin
from .models import Nurse, NursePatient
class NurseAdmin(admin.ModelAdmin):
model = Nurse
list_display = ['user', ]
class NursePatientAdmin(admin.ModelAdmin):
model = NursePatient
list_display = ['nurse', 'patient', ]
admin.site.register(Nurse, NurseAdmin)
admin.s... | nilq/baby-python | python |
class Reactor(object) :
def addReadCallback( self, sockfd, callback ) :
raise NotImplementedError
def removeReadCallback( self, sockfd ) :
raise NotImplementedError
def addWriteCallback( self, sockfd, callback ) :
raise NotImplementedError
def removeWriteCallback( self, ... | nilq/baby-python | python |
from dronekit import *
from pymavlink import mavutil
import argparse
import serial
from random import uniform
class Pixhawk:
def __init__(self):
self.status = (
"down"
) # this status is used to check if a service is functioning normaly or not
self.vehicle = None
def star... | nilq/baby-python | python |
import brownie
def test_withdraw_all(splitter, alice, bob):
initial_alice_balance = alice.balance()
initial_contract_balance = splitter.balance()
initial_alice_contract_balance = splitter.balances(alice)["balance"]
initial_bob_balance = bob.balance()
initial_bob_contract_balance = splitter.balance... | nilq/baby-python | python |
#econogee, 1/28/2016
#Stock Data Retrieval Script
#If executed via the command line, will produce 500 data files with stock price information
#between the dates specified in the main method. Can also be imported to use the RetrieveStock method.
import os
import sys
import numpy as np
import urllib2
def RetrieveStoc... | nilq/baby-python | python |
import os
import sys
def pre_process(baseDir, x1, x2, x3):
"""
An utility function to pre-process the .comm input files by reading it
and replacing the design variables(Length, Breadth and Thickness) values with
the values provided by BOA
PARAMS:
baseDir - The path of the directory which hold... | nilq/baby-python | python |
#! /usr/bin/env python3.8
from larning.setup import (
get_version,
get_github_url,
PACKAGE_NAME,
PACKAGES,
setup,
LONG_DESCRIPTION,
require_interpreter_version,
)
# ˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇ
require_i... | nilq/baby-python | python |
import torch.nn as nn
import torch
import math
class AffinityLayer(nn.Module):
"""
Affinity Layer to compute the affinity matrix from feature space.
M = X * A * Y^T
Parameter: scale of weight d
Input: feature X, Y
Output: affinity matrix M
"""
def __init__(self, dim):
super(Af... | nilq/baby-python | python |
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def softmax(x):
x_exp = np.exp(x)
return x_exp /np.sum(x_exp)
def relu(x):
return np.maximum(x, np.zeros_like(x))
| nilq/baby-python | python |
"""
Author: Trenton Bricken @trentbrick
All functions in this script are used to generate and approximate the circle intersection
in binary and continuous space and also convert between cosine similarity and hamming distance.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom, norm... | nilq/baby-python | python |
import json
import sys
from concurrent.futures import ThreadPoolExecutor, Future
from urllib3.connectionpool import HTTPSConnectionPool, HTTPResponse
from urllib3.exceptions import NewConnectionError, MaxRetryError, HTTPError
from typing import Dict, List, Any
from string import Template
class NetMod:
_instance =... | nilq/baby-python | python |
import argparse
import logging
import sys
from pathlib import Path
import requests
from flask import Flask
from packaging import version
from .views.assets import blueprint as assets_blueprint
from .views.index import blueprint as index_blueprint
PROCESS_NAME = "Spel2.exe"
# Setup static files to work with onefile e... | nilq/baby-python | python |
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
import numpy as np
import os
# We set seeds for reproduciability
tf.random.set_seed(1)
np.random.seed(1)
url = 'https://archive.ics.uci.edu/ml/machine... | nilq/baby-python | python |
# Aula 20 - 05-12-2019
# Analise de dados superficial
# Dica: Para este formulário será necessário usar um metodo para string novo.
# Vocês já conhecem o .strip() que remove os caracteres especiais \n do final
# da string. o .splint('') que quebra a string em uma lista conforme o caracteres
# que tem dentro das aspa... | nilq/baby-python | python |
# pylint: disable=invalid-name
"""Utility function to get information from graph."""
from __future__ import absolute_import as _abs
import tvm
from . import graph_attr
def infer_shape(graph, **shape):
"""Infer the shape given the shape of inputs.
Parameters
----------
graph : Graph
The graph ... | nilq/baby-python | python |
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
GRAY = '\033[90m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
END = '\033[0m' | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
.. module:: Backend.utils
:platform: Unix, Windows
.. moduleauthor:: Aki Mäkinen <aki.makinen@outlook.com>
"""
__author__ = 'Aki Mäkinen'
s_codes = {
"OK": 200,
"BAD": 400,
"UNAUTH": 401,
"FORBIDDEN": 403,
"NOTFOUND": 404,
"METHODNOTALLOWED": 405,
"TEAPOT":... | nilq/baby-python | python |
import logging
from common.DataSyncer import DataSyncer
from common.logger import initialize_logger
from models.User import User
logger = logging.getLogger(__name__)
initialize_logger(logger)
class UserPartialSyncer:
"""
Sync only latest users info from API to db
"""
def __init__(self):
sel... | nilq/baby-python | python |
import sys
import ui
if __name__ == "__main__":
app = ui.QtWidgets.QApplication(sys.argv)
MainWindow = ui.QtWidgets.QMainWindow()
ui = ui.Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_()) | nilq/baby-python | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("student_scores.csv")
# verisetinin boyutları
dataShape = dataset.shape
print(dataShape)
print(dataset.head(7)) # datasetin başını gösterir. default değer 5'tir.
print(dataset.tail(7)) # datasetin sonunu gösteri... | nilq/baby-python | python |
import os, sys
variables_size = 3
dataset_name = "Epilepsy"
class_dictionary = {}
class_count = 1
dirname = os.path.abspath(os.path.dirname(sys.argv[0]))
train_test_str = ["_TRAIN","_TEST"]
for i in range(0,2):
arff_data_flag = 0
series_count = 1
file_location = dirname + "/" + dataset_name + train_test_... | nilq/baby-python | python |
from .AlgerianMobilePhoneNumber import AlgerianMobilePhoneNumber | nilq/baby-python | python |
from automl_infrastructure.experiment.observations import SimpleObservation
import numpy as np
class Std(SimpleObservation):
"""
Implementation of standard deviation scores aggregation.
"""
def __init__(self, metric):
super().__init__(metric)
def agg_func(self, values):
return np.... | nilq/baby-python | python |
import torch
import torchvision.transforms as T
from pytorch_grad_cam import GradCAMPlusPlus
from pytorch_lightning import LightningModule
from pawpularity.augmentations import mixup
from . import efficientnet, levit_transformer, swin_transformers, vision_transformers, learnable_resizer
class Model(LightningModule):
... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-04-29 10:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webpage', '0014_auto_20210428_0912'),
]
operations = [
migrations.AddField(
model_name='notification',
name='read',
... | nilq/baby-python | python |
from __future__ import print_function
# Time: O(n)
# Space: O(1)
#
# Given a roman numeral, convert it to an integer.
#
# Input is guaranteed to be within the xrange from 1 to 3999.
#
class Solution:
# @return an integer
def romanToInt(self, s):
numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100... | nilq/baby-python | python |
from mat_mult.mcm import memoized_mcm
def test_memo(test_cases):
for test in test_cases:
dims = test['dims']
best_cost = memoized_mcm(dims=dims)[0]
assert best_cost == test['cost']
| nilq/baby-python | python |
###########################################################################
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/... | nilq/baby-python | python |
import torch
from change_detection_pytorch.encoders import get_encoder
if __name__ == '__main__':
sample = torch.randn(1, 3, 256, 256)
model = get_encoder('mit-b0', img_size=256)
res = model(sample)
for x in res:
print(x.size())
| nilq/baby-python | python |
# -*- Mode: Python -*-
#
# This file calls PARC_FAME_Toolkit and determine possible fault modes
# that exists in CyPhy Driveline Model.
import sys, os, traceback, json, shutil
from collections import OrderedDict
import fetch
script_dir = os.path.dirname(os.path.realpath(__file__))
output_dir = os.path.abspath(os.pat... | nilq/baby-python | python |
import logging
from openpyxl import load_workbook, Workbook
from openpyxl.utils.exceptions import InvalidFileException
class XLSXWorkbook:
def __init__(self, filename: str):
self.filename = filename
@property
def filename(self):
return self.__filename
@filename.setter
def filenam... | nilq/baby-python | python |
from __future__ import annotations
from unittest import TestCase
from tests.classes.simple_book import SimpleBook
from tests.classes.simple_deadline import SimpleDeadline
class TestUpdate(TestCase):
def test_update_without_arguments_wont_change_anything(self):
book = SimpleBook(name='Thao Bvê', published... | nilq/baby-python | python |
#CYBER NAME BLACK-KILLER
#GITHUB: https://github.com/ShuBhamg0sain
#WHATAPP NO +919557777030
import os
CorrectUsername = "g0sain"
CorrectPassword = "sim"
loop = 'true'
while (loop == 'true'):
username = raw_input("\033[1;96m[#] \x1b[0;36m Enter Username\x1b[1;92m➤ ")
if (username == CorrectUsername):
pass... | nilq/baby-python | python |
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import re
from scout_apm.compat import iteritems
logger = logging.getLogger(__name__)
key_regex = re.compile(r"^[a-zA-Z0-9]{20}$")
class Register(object):
__slots__ = ("app", "key", "hostname")
... | nilq/baby-python | python |
"""Compute dispersion correction using Greenwell & Beran's MP2D executable."""
import pprint
import re
import sys
from decimal import Decimal
from typing import Any, Dict, Optional, Tuple
import numpy as np
import qcelemental as qcel
from qcelemental.models import AtomicResult, Provenance
from qcelemental.util import... | nilq/baby-python | python |
__all__ = ["partitionN"]
from partition import *
| nilq/baby-python | python |
# yellowbrick.utils.helpers
# Helper functions and generic utilities for use in Yellowbrick code.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Fri May 19 10:39:30 2017 -0700
#
# Copyright (C) 2017 District Data Labs
# For license information, see LICENSE.txt
#
# ID: helpers.py [79cd8cf] ... | nilq/baby-python | python |
import os
import random
class Playlist:
# maintains individual playlist
def __init__(self, path):
self.path = path
self.clips = []
n = os.path.basename(self.path).split(".")[:-1]
self.name = ".".join(n)
self.desc = ""
def load(self):
# each line has the form... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (C) SME Virtual Network contributors. All rights reserved.
# See LICENSE in the project root for license information.
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 14:07:32 2020
"""
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
data = Dataset(r"C:\Users\Jiacheng Li\Desktop\Study\University of Birmingham Relevant\Final Year Project\NetCDF_Handling\NetCDF_da... | nilq/baby-python | python |
from __future__ import absolute_import
from requests.exceptions import HTTPError
from six.moves.urllib.parse import quote
from sentry.http import build_session
from sentry_plugins.exceptions import ApiError
class GitLabClient(object):
def __init__(self, url, token):
self.url = url
self.token = t... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-06 04:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [(b'coding', '0001_initial'), (b'coding', '... | nilq/baby-python | python |
import json
from nebulo.sql.reflection.function import reflect_functions
from sqlalchemy.dialects.postgresql import base as pg_base
CREATE_FUNCTION = """
create table account(
id int primary key,
name text
);
insert into account (id, name)
values (1, 'oli');
create function get_account(id int)
returns accou... | nilq/baby-python | python |
# code modified from https://stackoverflow.com/questions/38401099/how-to-count-one-specific-word-in-python/38401167
import re
filename = input('Enter file:') # you can input any .txt file here. you need to type the path to the file.
# you can try the file in this folder: text_diamond.txt
handle = open(filename, 'r')... | nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='store-home-page'),
path('login/', views.login, name='login-page'),
path('signup/', views.signup, name='signup-page'),
]
| nilq/baby-python | python |
N = int(input())
X = list(map(int,input().split()))
menor = X[0]
pos = 0
for k in range(1,N):
if X[k] < menor:
menor = X[k]
pos = k
print("Menor valor: %d" % (menor))
print("Posicao: %d" % (pos))
| nilq/baby-python | python |
"""
Utilities Tests
---------------
"""
from poli_sci_kit import utils
def test_normalize():
assert sum(utils.normalize([1, 2, 3, 4, 5])) == 1.0
def test_gen_list_of_lists():
test_list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
assert utils.gen_list_of_lists(
original_list=test_list, new_structure=[3, 3, 3]... | nilq/baby-python | python |
from tark import constants
class DBSettings(object):
def __init__(self,
db_type=constants.DEFAULT_DB_TYPE,
db_name=constants.DEFAULT_DB_NAME,
db_user=constants.DEFAULT_DB_USER,
db_password=constants.DEFAULT_DB_PASSWORD,
db_node... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2011 Alan Franzoni. APL 2.0 licensed.
from unittest import TestCase
from abc import abstractmethod
from pydenji.ducktypes.function_copy import copy_raw_func_only, fully_copy_func
@abstractmethod
def example_func(a, b, c=1):
return 1
class AbstractTestFunction... | nilq/baby-python | python |
# Standard utils file
# Developed by Anodev Development (OPHoperHPO) (https://github.com/OPHoperHPO)
import time
import network
def wifi_connect(SSID, PASSWORD):
"""Connects to wifi."""
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('Connecting to network...')
sta... | nilq/baby-python | python |
# Lint as: python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | nilq/baby-python | python |
import math, sys
from konlpy.tag import Okt
class BayesianFilter:
def __init__(self):
self.words=set()
self.word_dict={}
self.category_dict={}
def fit(self, text, category):
'''
텍스트를 읽어 학습
'''
pos=self.split(text)
for word in pos:
... | nilq/baby-python | python |
"""Role testing files using testinfra."""
def test_kubelet_package(host):
kubelet = host.package("kubelet")
assert kubelet.is_installed
assert kubelet.version.startswith("1.21")
def test_kubelet_service(host):
kubelet = host.service("kubelet")
assert kubelet.is_running
assert kubelet.is_enab... | nilq/baby-python | python |
'''entre no sistema com dois valores e saia com a soma entre eles'''
v1 = int(input('Digite o primeiro valor: '))
v2 = int(input('Digite o segundo valor: '))
print('A soma de {} + {} = {} '.format(v1, v2, v1 + v2))
print('Acabou!')
| nilq/baby-python | python |
import tskit
import tszip
import matplotlib.pyplot as plt
import numpy as np
site_ts = str(snakemake.input.site_ts)
plot_path = str(snakemake.output.plot)
ts = tszip.decompress(site_ts)
for x in range(len(ts.populations())):
y = ts.tables.nodes.time[np.where(ts.tables.nodes.population==x)[0]]
plt.plot(np.lo... | nilq/baby-python | python |
# import os
# import sys
# TEST_DIR = os.path.dirname(os.path.abspath(__file__))
# PROJECT_DIR = os.path.abspath(os.path.join(TEST_DIR, os.pardir, 'api'))
# sys.path.insert(0, PROJECT_DIR)
| nilq/baby-python | python |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import unittest as ut
import os.path
import stripeline.timetools as tt
import numpy as np
class TestTimeTools(ut.TestCase):
def testSplitTimeRangeSimple(self):
'''Test split_time_range against a very simple input'''
result = tt.split_time_range(
... | nilq/baby-python | python |
#!/usr/bin/env pypy
import sys
from random import *
if len(sys.argv) < 3:
print "Usage: ", sys.argv[0], " [N] [M]"
exit(-1)
n = int(sys.argv[1])
m = int(sys.argv[2])
CMAX = 100
print n, m
assert m >= n - 1
for v in range(2, n + 1):
u = randrange(1, v)
w = randint(1, CMAX)
print u, v, w
for i i... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 15:24:53 2019
@author: melisa
"""
import pandas as pd
import logging
import server as connect
import math
# Paths
analysis_states_database_path = 'references/analysis/analysis_states_database.xlsx'
backup_path = 'references/analysis/backup/'
p... | nilq/baby-python | python |
import sqlite3
con = sqlite3.connect("danbooru2019.db")
con.isolation_level = None
cur = con.cursor()
buffer = ""
print ("Enter your SQL commands to execute in sqlite3; terminated with semicolon (;)")
print ("Enter a blank line to exit.")
while True:
line = input()
if line == "":
break
buffer +=... | nilq/baby-python | python |
from __future__ import division
from builtins import zip
from builtins import range
from builtins import object
__all__ = [
'NegativeBinomial', 'NegativeBinomialFixedR', 'NegativeBinomialIntegerR2',
'NegativeBinomialIntegerR', 'NegativeBinomialFixedRVariant',
'NegativeBinomialIntegerRVariant', 'NegativeBino... | nilq/baby-python | python |
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="py-royale",
version="0.1.0",
author="Kenan Džindo",
description="Asynchronous wrapper for the official Supercell Clash Royale API.",
long_description=long_... | nilq/baby-python | python |
print('=== DESAFIO 011 ===')
print('Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área \ne a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m²:')
L = float(input('Digite a largura da parede: '))
A = float(input('Digite a altura d... | nilq/baby-python | python |
from pad import pad1d, pad2d
def map_sequence(seq, sequence_map, unk_item_id):
""" Transform a splitted sequence of items into another sequence of items
according to the rules encoded in the dict item2id
seq: iterable
sequence_map: dict
unk_item_id: int"""
item_ids = []
for i... | nilq/baby-python | python |
import argparse
from preprocess import preprocess
import os
from pathlib import Path
import wave
import numpy as np
import unicodedata
import random
from tqdm import tqdm
import re
import yaml
import sys
import librosa
## Fairseq 스타일로 변환하기
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argumen... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: github.com/metaprov/modelaapi/services/modelpipelinerun/v1/modelpipelinerun.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... | nilq/baby-python | python |
import os.path
import re
from setuptools import setup
(__version__, ) = re.findall("__version__.*\s*=\s*[']([^']+)[']",
open('toms/__init__.py').read())
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md")) as fid:
README = fid.read()
setup(
... | nilq/baby-python | python |
from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-time-pattern-3-NS"
@dataclass
class NistschemaSvIvListTimePattern3:
class Meta:
name = "NISTSchema-SV-IV-list-time-pattern-3"
namespace = "NISTSchema-SV-IV-list-time-pattern-3-NS"
value: L... | nilq/baby-python | python |
from enum import Enum
class Colors(Enum):
GREEN = "#00C2A4"
PINK = "#FD5383"
PURPLE = "#8784FF"
BLUE_1 = "#1B2A4D"
BLUE_2 = "#384B74"
BLUE_3 = "#8699B7"
class ColorPalettes(Enum):
CATEGORY = [
Colors.BLUE_1.value,
Colors.GREEN.value,
Colors.PURPLE.value,
C... | nilq/baby-python | python |
from .test_controller import JsonController, JsonArrayController, TemplateController
| nilq/baby-python | python |
"""
This file is a meant to make custom frame work like set up.
It will enable us to have a enpoints/routes for our API without
using a framework like flask or Django.
We will use WebOb to create a request and response object which
is centered around the WSGI model.
For more info https://docs.pylonsproject.org/projec... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 18:14:29 2016
@author: becker
"""
import numpy as np
import numpy.linalg as linalg
from simfempy import fems
from simfempy.meshes.simplexmesh import SimplexMesh
import scipy.sparse as sparse
#=================================================================#
class Fe... | nilq/baby-python | python |
"""
Module: 'uzlib' on esp8266 v1.9.3
"""
# MCU: (sysname='esp8266', nodename='esp8266', release='2.0.0(5a875ba)', version='v1.9.3-8-g63826ac5c on 2017-11-01', machine='ESP module with ESP8266')
# Stubber: 1.1.2 - updated
from typing import Any
class DecompIO:
""""""
def read(self, *argv) -> Any:
pas... | nilq/baby-python | python |
import sys
from random import randint
import pytest
from src.app.main.model_centric.cycles.worker_cycle import WorkerCycle
from src.app.main.model_centric.processes.fl_process import FLProcess
from . import BIG_INT
from .presets.fl_process import (
AVG_PLANS,
CLIENT_CONFIGS,
CYCLES,
MODELS,
PROTOC... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2018 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.