content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
"""Command line tools for Flask server app.""" from os import environ from uuid import UUID from flask_script import Manager from flask_migrate import MigrateCommand, upgrade from app import create_app, db from app.mongo import drop_mongo_collections from app.authentication.models import User, PasswordAuthentication...
nilq/baby-python
python
import torch from transformers import BertTokenizerFast from colbert.modeling.tokenization.utils import _split_into_batches, _sort_by_length class DocTokenizer(): def __init__(self, doc_maxlen): self.tok = BertTokenizerFast.from_pretrained('bert-base-uncased') self.doc_maxlen = doc_maxlen ...
nilq/baby-python
python
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
nilq/baby-python
python
import signal import argparse import logging as log import os from pathlib import Path import errno from alive_progress import alive_bar from backupdef import BackupDef from entries import FolderEntry from diskspacereserver import DiskSpaceReserver from util import sanitizeFilename def backup(source: str, destinatio...
nilq/baby-python
python
import redis def handler(message): print("New message recieved:", message['data'].decode('utf-8')) r = redis.Redis('10.14.156.254') p = r.pubsub() p.subscribe(**{'chat': handler}) thread = p.run_in_thread(sleep_time=0.5) # Создание потока для получения сообщий print("Press Ctrl+C to stop") while True: try...
nilq/baby-python
python
#!/usr/bin/env python """ methrafo.train <reference genomes><input MeDIP-Seq bigWig> <input Bisulfite-Seq bigWig> <output model prefix> e.g. methrafo.train hg19 example_MeDIP.bw example_Bisulfite.bw output_trained_model_prefix """ import pdb,sys,os import gzip from File import * import re import pyBigWig from scipy....
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Initialize the Hanabi PyQT5 Interface. """ from PyQt5 import QtCore, QtGui from PyQt5.QtGui import QPalette from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication from py_hanabi.interface.hanabi_window import HanabiWindow from py_hanabi.interface.window import Window __aut...
nilq/baby-python
python
# Reference: https://github.com/zhangchuheng123/Reinforcement-Implementation/blob/master/code/ppo.py import torch def ppo_step( policy_net, value_net, optimizer_policy, optimizer_value, optim_value_iter_num, states, actions, returns, advantages, fixed_log_probs, clip_epsi...
nilq/baby-python
python
# # PySNMP MIB module SL81-STD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SL81-STD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:57:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
nilq/baby-python
python
from allauth.account.forms import ChangePasswordForm as AllauthChangePasswordForm class ChangePasswordForm(AllauthChangePasswordForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields["oldpassword"].widget.attrs["placeholder"] del self.fields["password...
nilq/baby-python
python
"""Tests for the convention subsections.""" import re import pytest from tests.test_convention_doc import doctypes @pytest.fixture( scope="module", params=[ pytest.param((index, subsection), id=subsection.identifier) for section in doctypes.SECTIONS for index, subsection in enumerat...
nilq/baby-python
python
from PKG.models import ResnetV2 import tensorflow as tf class Classifier(tf.keras.models.Model): def __init__(self, nclasses, weights=None): super(Classifier, self).__init__() self.nn = ResnetV2() self.classifier = tf.keras.layers.Dense(nclasses) self.activation = tf.keras.layers....
nilq/baby-python
python
from helpers.observerpattern import Observable from HTMLParser import HTMLParser class DomBuilder(Observable, HTMLParser): """ This class is on charge of parse the plainHTML provided via a Reader and construct a dom representation with it. DOM structure is decoupled from this class and need to be passe...
nilq/baby-python
python
class Eventseverity(basestring): """ EMERGENCY|ALERT|CRITICAL|ERROR|WARNING|NOTICE|INFORMATIONAL|DEBUG Possible values: <ul> <li> "emergency" - System is unusable, <li> "alert" - Action must be taken immediately, <li> "critical" - Critical condition, <li> "error" ...
nilq/baby-python
python
from .attachment import Attachment from .integration import Integration from .message import Message from .field import Field
nilq/baby-python
python
""" 152. Maximum Product Subarray Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanatio...
nilq/baby-python
python
import numpy as np import math import matplotlib.pyplot as plt from bandit import Bandit from explore_then_exploit_agent import ExploreThenExploit from MC_simulator import * from epsilon_greedy_agent import EpsilonGreedy from ubc1_agent import UBC1Agent from report import plot
nilq/baby-python
python
# -*- coding: utf-8 -*- # import the necessary packages from tnmlearn.nn.conv import MiniVGGNet from keras.optimizers import SGD from tnmlearn.examples import BaseLearningModel from tnmlearn.datasets import load_cifar10 # %% class MiniVggNetCifar10(BaseLearningModel): def __init__(self): super(MiniVggNetCi...
nilq/baby-python
python
from app.order.domain.order import Order from app.order.domain.order_repository import OrderRepository class SqlOrderRepository(OrderRepository): def __init__(self, session): self.session = session def save(self, order: Order): self.session.add(order) self.session.commit() def fi...
nilq/baby-python
python
import os import numpy as np from copy import copy from easyric.io import pix4d, geotiff, shp, plot from easyric.calculate import geo2raw, geo2tiff, raw2raw #################### # Software wrapper # #################### class Pix4D: def __init__(self, project_path, raw_img_path=None, project_name=None, ...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 8 14:38:17 2018 @author: jgoldstein """ # try to get some simulated PTA data like in Jeff Hazboun's github https://github.com/Hazboun6/pta_simulations import numpy as np import glob, os import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] =...
nilq/baby-python
python
N = int(input()) ans = 0 if N % 100 == 0: ans = N // 100 else: ans = (N // 100) + 1 print(ans)
nilq/baby-python
python
#_*_ coding: utf-8 -*- { 'name': "Carlosma7", 'summary': """ This is the summary of the addon, second try.""", 'description': """ This is the description of the addon. """, 'author': "Carlos Morales Aguilera", 'website': "http://www.carlosma7.com", 'category': 'Personal project', 'version...
nilq/baby-python
python
# # PySNMP MIB module BENU-HTTP-CLIENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-HTTP-CLIENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:37:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
nilq/baby-python
python
""" .. module:: __init__ :synopsis: This is where all our global variables and instantiation happens. If there is simple app setup to do, it can be done here, but more complex work should be farmed off elsewhere, in order to keep this file readable. .. moduleauthor:: Dan Schlosser <dan@dan@...
nilq/baby-python
python
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: ...
nilq/baby-python
python
""" Unit test for re module""" import unittest import re class ReTests(unittest.TestCase): def test_findall(self): #Skulpt is failing all the commented out tests in test_findall and it shouldn't be val = re.findall("From","dlkjdsljkdlkdsjlk") self.assertEqual(len(val), 0) val = re.f...
nilq/baby-python
python
import os from setuptools import setup def package_files(directory): paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: paths.append(os.path.join('..', path, filename)) return paths extra_files = package_files('sejits4fpgas/hw') extra_files....
nilq/baby-python
python
# ====================================================================================================================== # Fakulta informacnich technologii VUT v Brne # Bachelor thesis # Author: Filip Bali (xbalif00) # License: MIT # ======================================================================================...
nilq/baby-python
python
import numpy as np import math def nanRound(vs, *args, **kw): def fun(v): if math.isnan(v): return(v) return np.around(v, *args, **kw) return [fun(i) for i in vs]
nilq/baby-python
python
import os import sys import pprint from PIL import Image from av import open video = open(sys.argv[1]) stream = next(s for s in video.streams if s.type == b'video') for packet in video.demux(stream): for frame in packet.decode(): frame.to_image().save('sandbox/%04d.jpg' % frame.index) if frame_cou...
nilq/baby-python
python
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE import re nested_uls = """ <ul> <li>1 <ul> <li>a <ul> <li>I</li> <li>II</li> <li>III</li> ...
nilq/baby-python
python
from Assignment2 import * def test_case1(): cost = [[0,0,0,0], [0,0,5,10], [0,-1,0,5], [0,-1,-1,0] ] print(UCS_Traversal(cost,1,[3])) def test_case2(): cost = [[0,0,0,0,0], [0,0,0,10,5], [0,-1,0,5,0], [0,-1,-1,0,0], [0,-1,-1,5,0] ] print(UCS_Traversal(cost,1,[3])) def test_case3(): cos...
nilq/baby-python
python
import numpy as np import sys, time, glob #caffe_root = "/home/vagrant/caffe/" #sys.path.insert(0, caffe_root + 'python') import caffe from sklearn.metrics import accuracy_score from random import shuffle from sklearn import svm def init_net(): net = caffe.Classifier(caffe_root + 'models/bvlc_reference_caffenet/de...
nilq/baby-python
python
import numpy as np import py2neo as pn import random import math import copy def create_ba_subgraph(M, m_0, n, relation): # Generate Users-Friends un-directed subgraph # Generate Users-Follower directed subgraph node_list = [] for i in range(m_0): node_list.append(pn.Node('User', name='user'...
nilq/baby-python
python
# coding=utf-8 from __future__ import print_function import authcode from sqlalchemy_wrapper import SQLAlchemy from helpers import SECRET_KEY def test_user_model(): db = SQLAlchemy('sqlite:///:memory:') auth = authcode.Auth(SECRET_KEY, db=db, roles=True) assert auth.users_model_name == 'User' assert...
nilq/baby-python
python
# -*- coding: utf-8 -*- def fluxo_caixa(): fluxo = db(MovimentoCaixa).select() return locals() def entradas(): entradas = db(Entradas).select() return locals() def n_entrada(): entrada_id = request.vars.entrada if entrada_id is None: form = SQLFORM(Entradas, fields=['descri...
nilq/baby-python
python
# (C) British Crown Copyright 2013 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
nilq/baby-python
python
import sys, os, Jati class Serve: def run(self, host, port, sites, log_file, isSSL): current_dir = os.getcwd() if current_dir not in sys.path: sys.path.insert(1, current_dir) try: jati = Jati.Jati(host=host, port=port, isSSL=None, log_file=log_file) jati....
nilq/baby-python
python
from django.contrib import admin from .models import Classifier admin.site.register(Classifier)
nilq/baby-python
python
def cgi_content(type="text/html"): return('Content type: ' + type + '\n\n') def webpage_start(): return('<html>') def web_title(title): return('<head><title>' + title + '</title></head>') def body_start(h1_message): return('<h1 align="center">' + h1_message + '</h1><p align="center">') def body_end(): return("...
nilq/baby-python
python
"""Class to host an MlModel object.""" import logging import json from aiokafka import AIOKafkaProducer, AIOKafkaConsumer from model_stream_processor import __name__ from model_stream_processor.model_manager import ModelManager logger = logging.getLogger(__name__) class MLModelStreamProcessor(object): """Proces...
nilq/baby-python
python
# -*- coding:utf-8 -*- from __future__ import print_function import zipfile import os import shutil import time import property import shutil print('====================================\n\nThis Software Only For Android Studio Language Package Replace\nDevelop By Wellchang\n2019/03/20\n\n==============================...
nilq/baby-python
python
from collections import Iterable from iterable_collections.factory import DefaultMethodStrategyFactory class Collection: def __init__(self, iterable, strategies): self._iterable = None self.iterable = iterable self._strategies = strategies def __getattr__(self, item): if ite...
nilq/baby-python
python
#!/usr/bin/env python2 import os import sys # add the current dir to python path CURRENT_DIR = os.path.expanduser(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, CURRENT_DIR) os.system('cd %s ;git pull' % CURRENT_DIR) from app import app if 'SERVER_SOFTWARE' in os.environ: import sae application ...
nilq/baby-python
python
# MIT License # # Copyright (c) 2021 Douglas Davis # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge...
nilq/baby-python
python
import numpy as np import pandas as pd import joblib dataset = pd.read_csv("datasets/cleaned_cleveland.csv") X = dataset.iloc[:, :-1] y = dataset.iloc[:, -1] from sklearn.neighbors import KNeighborsClassifier regressor = KNeighborsClassifier(n_neighbors=21) regressor.fit(X, y) joblib.dump(regressor, "classificati...
nilq/baby-python
python
from flask import Flask # 创建flask框架 # 静态文件访问的时候url匹配时,路由规则里的路径名字 默认值是、static app = Flask(__name__, static_url_path='/static') print(app.url_map) # @app.route('/') # def index(): # """处理index页面逻辑""" # return 'nihao' @app.route('/login.html') def login(): """登录的逻辑""" # 读取login.html 并且返回 with open('login.htm...
nilq/baby-python
python
# -*- coding: utf-8 -*- from setuptools import setup import pathlib here = pathlib.Path(__file__).parent.resolve() long_description = (here / "README.md").read_text(encoding='utf-8') setup( name='zarr-swiftstore', version="1.2.3", description='swift storage backend for zarr', long_description=long_d...
nilq/baby-python
python
import argparse from config.config import Config from dataset.factory import DatasetModule from domain.metadata import Metadata from logger import logger from model.factory import ModelModule from trainer.factory import TrainerModule def main(args): mode = args.mode.lower() config_file_name = args.config.low...
nilq/baby-python
python
from qiskit.circuit.library import PauliFeatureMap class ZZFeatureMap(PauliFeatureMap): def __init__( self, feature_dimension, reps=2, entanglement="linear", data_map_func=None, insert_barriers=False, name="ZZFeatureMap", parameter_prefix="x", ):...
nilq/baby-python
python
# # @lc app=leetcode.cn id=1 lang=python3 # # [1] 两数之和 # # https://leetcode-cn.com/problems/two-sum/description/ # # algorithms # Easy (48.55%) # Likes: 8314 # Dislikes: 0 # Total Accepted: 1.1M # Total Submissions: 2.2M # Testcase Example: '[2,7,11,15]\n9' # # 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,...
nilq/baby-python
python
class DetFace: def __init__(self, conf, bbox): self.conf = conf self.bbox = bbox self.name = ''
nilq/baby-python
python
from pathlib import Path import tables import pandas as pd class Stream: def __init__(self, path): self.path = path self.frame_id_list = self._frame_id_list() self.frame_dict = {k:frame_id for k, frame_id in enumerate(self.frame_id_list)} def _frame_id_list(self): if not Path(...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: xiaxianba @license: Apache Licence @contact: scuxia@gmail.com @site: http://weibo.com/xiaxianba @software: PyCharm @file: SimTrade.py @time: 2017/02/06 13:00 @describe: 展期数据 """ import csv import datetime as pydt import...
nilq/baby-python
python
import obswebsocket, obswebsocket.requests import logging import time import random from obs.actions.Action import Action from obs.actions.ShowSource import ShowSource from obs.actions.HideSource import HideSource from obs.Permission import Permission class Toggle(Action): def __init__(self, obs_client, command_name...
nilq/baby-python
python
from collections import namedtuple from . import meta, pagination, resource_identifier class ToOneLinks(namedtuple('ToOneLinks', ['maybe_self', 'maybe_related'])): """ Representation of links for a to-one relationship anywhere in a response. """ __slots__ = () def __new__(cls, maybe_self=None, ...
nilq/baby-python
python
import random import networkx as nx from LightningGraph.LN_parser import read_data_to_xgraph, process_lightning_graph LIGHTNING_GRAPH_DUMP_PATH = 'LightningGraph/old_dumps/LN_2020.05.13-08.00.01.json' def sample_long_route(graph, amount, get_route_func, min_route_length=4, max_trials=10000): """ Sample src...
nilq/baby-python
python
# identifies patients with gout and thiazides import csv import statsmodels.api as statsmodels from atcs import * from icd import is_gout highrisk_prescription_identified = 0 true_positive = 0 true_negative = 0 false_positive = 0 false_negative = 0 gout_treatment = allopurinol | benzbromaron | colchicin | febuxost...
nilq/baby-python
python
from AoCUtils import * result = 0 partNumber = "1" writeToLog = False if writeToLog: logFile = open("log" + partNumber + ".txt", "w") else: logFile = "stdout" printLog = printLogFactory(logFile) heights = {} with open("input.txt", "r") as inputFile: lines = inputFile.read().strip().split("\n") for ...
nilq/baby-python
python
import setuptools __version__ = "0.2.0" __author__ = "Ricardo Montañana Gómez" def readme(): with open("README.md") as f: return f.read() setuptools.setup( name="Odte", version=__version__, license="MIT License", description="Oblique decision tree Ensemble", long_description=readme(...
nilq/baby-python
python
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='ddp_asyncio', version='0.3.0', description='Asynchronous DDP library', long_description=long_description, long_description_content_type='text/markdown', url='https://git...
nilq/baby-python
python
import random import pandas as pd def synthetic(n, categorical=[], continuous=[]): """Synthetic dataset. For each element in ``categorical``, either 0 or 1 is generated randomly. Similarly, for each element in ``continuous``, a random value between 0 and 100 is generated. Parameters --------...
nilq/baby-python
python
# Copyright Aleksey Gurtovoy 2001-2004 # # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # # See http://www.boost.org/libs/mpl for documentation. # $Source: /CVSROOT/boost/libs/mpl/preprocessed/preprocess_set.py...
nilq/baby-python
python
#!/usr/bin/env python from Bio import SeqIO from Bio.SeqUtils import GC import click import math import random import sys CONTEXT_SETTINGS = { "help_option_names": ["-h", "--help"], } @click.command(no_args_is_help=True, context_settings=CONTEXT_SETTINGS) @click.argument( "fasta_file", type=click.Path(ex...
nilq/baby-python
python
# Copyright 2021 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff # This software is distributed under the 3-clause BSD License. # Code that is producing a xhat and a confidence interval using sequential sampling # This is the implementation of the 2 following papers: # [bm2011] Bayraksan, G., Mort...
nilq/baby-python
python
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.python.tasks.isort_run import IsortRun from pants_test.pants_run_integration_test import PantsRunIntegrationTest, ensure_daemon class IsortRunIntegrationTest(PantsRunI...
nilq/baby-python
python
import cv2 import random import numpy as np from utils.bbox_utils import iou, object_coverage from utils.textboxes_utils import get_bboxes_from_quads def random_crop_quad( image, quads, classes, min_size=0.1, max_size=1, min_ar=1, max_ar=2, overlap_modes=[ None, [0.1, No...
nilq/baby-python
python
import torch import torch.nn as nn import torchvision from . import resnet as resnet from . import resnext as resnext from torch.nn.init import kaiming_normal_,constant_,normal_ from core.config import cfg import torch.nn.functional as F import modeling.CRL as CRL import modeling.cspn as cspn import time timer=time.t...
nilq/baby-python
python
# -*- coding: utf-8 -*- # 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 applicable law or agreed to in writing, softw...
nilq/baby-python
python
# # @lc app=leetcode id=1022 lang=python3 # # [1022] Sum of Root To Leaf Binary Numbers # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: ...
nilq/baby-python
python
"""Setup script of django-blog-zinnia""" from setuptools import find_packages from setuptools import setup import zinnia setup( dependency_links=[ "git+https://github.com/arrobalytics/django-tagging.git@027eb90c88ad2d4aead4f50bbbd8d6f0b1678954#egg=django-tagging", "git+https://github.com/arrobalyt...
nilq/baby-python
python
from numbers import Number from timegraph.drawing.plotter import Plotter class Drawing: def __init__(self): self.plotter = Plotter() def create_graph(self, title, db_response): value_list = self.get_value_list(db_response.get_points()) self.plotter.plot_timeseries(value_list) d...
nilq/baby-python
python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def __init__(self): self.res=[] def printnode(self,start,end): if start==end: return if start.next==...
nilq/baby-python
python
from django.shortcuts import render # Create your views here. def about_view(request): return render(request, 'about/about.html')
nilq/baby-python
python
# -*- coding: utf-8 -*- """ v13 model * Input: v12_im Author: Kohei <i@ho.lc> """ from logging import getLogger, Formatter, StreamHandler, INFO, FileHandler from pathlib import Path import subprocess import glob import math import sys import json import re import warnings import scipy import tqdm import click import...
nilq/baby-python
python
from __future__ import absolute_import, unicode_literals import json from mopidy.models import immutable class ModelJSONEncoder(json.JSONEncoder): """ Automatically serialize Mopidy models to JSON. Usage:: >>> import json >>> json.dumps({'a_track': Track(name='name')}, cls=ModelJSONEn...
nilq/baby-python
python
"""Generate a plot to visualize revision impact inequality based on data-flow interactions.""" import typing as tp import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib import axes, style from varats.data.databases.blame_interaction_database import ( BlameInteractionDatabase, ) fr...
nilq/baby-python
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
nilq/baby-python
python
from InsertionSort import insertionSort import math def bucketSort(customList): numBuckets = round(math.sqrt(len(customList))) maxValue = max(customList) arr = [] # Creating buckets for i in range(numBuckets): arr.append([]) # Shifting elemets to buckets for j in range(customList...
nilq/baby-python
python
# -*- coding: utf-8 -*- import re import requests from datetime import datetime, timedelta from jobs import AbstractJob class Vaernesekspressen(AbstractJob): def __init__(self, conf): self.airport_id = 113 # Vaernes is the the only supported destionation self.from_stop = conf["from_stop"] ...
nilq/baby-python
python
import jax.numpy as jnp from jax import vmap, grad, nn, tree_util, jit, ops, custom_vjp from functools import partial from jax.experimental import ode from collections import namedtuple GradientFlowState = namedtuple('GradientFlowState', ['B', 's', 'z']) def gradient_flow(loss_fn, init_params, inputs, labels, t_fi...
nilq/baby-python
python
""" Crie um programa que aprove um emprestimo bancário, onde o programa leia: Valor da Casa / salário da pessoa / quantos anos será o pagamento Calcule o valor da prestação mensal, sabendo que ela não pode ser superior a 30% da renda da pessoa, se passar o emprestimo será negado """ import time valor_casa = float(inpu...
nilq/baby-python
python
"""Core module for own metrics implementation""" from sklearn.metrics import mean_squared_error import numpy as np def rmse(y, y_pred): return np.sqrt(mean_squared_error(y, y_pred))
nilq/baby-python
python
from django.contrib import admin from .models import Ballot, Candidate, SubElection, Election, Image, ElectionUser class CandidateAdmin(admin.StackedInline): model = Candidate extra = 0 class SubElectionAdmin(admin.ModelAdmin): model = SubElection inlines = [ CandidateAdmin, ] list_...
nilq/baby-python
python
""" Defines the Note repository """ from models import Note class NoteRepository: """ The repository for the note model """ @staticmethod def get(user_first_name, user_last_name, movie): """ Query a note by last and first name of the user and the movie's title""" return Note.query.filter...
nilq/baby-python
python
prefix = '14IDA:shutter_auto_enable2' description = 'Shutter 14IDC auto' target = 0.0
nilq/baby-python
python
"""Pipeline subclass for all multiclass classification pipelines.""" from evalml.pipelines.classification_pipeline import ClassificationPipeline from evalml.problem_types import ProblemTypes class MulticlassClassificationPipeline(ClassificationPipeline): """Pipeline subclass for all multiclass classification pipe...
nilq/baby-python
python
import os import sys import time import random import string import datetime import concurrent.futures # Import function from module from .program_supplementals import enter_key_only, exception_translator # Import function from 3rd party module from netmiko import ConnectHandler def file_output(ssh_res...
nilq/baby-python
python
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import os i...
nilq/baby-python
python
""" Module containing character class for use within world. """ from abc import ABC from .. import entity class Character(entity.Entity): """ Abstract class representing a character within a world. """ pass if __name__ == "__main__": pass
nilq/baby-python
python
# Copyright 2017 The TensorFlow Authors. 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 applica...
nilq/baby-python
python
import unittest from pygments import lexers, token from gviewer.util import pygmentize, _join class TestUtil(unittest.TestCase): def test_pygmentize(self): python_content = """ import unittest class Pygmentize(object): pass""" result = pygmentize(python_content, lexer...
nilq/baby-python
python
import json import unittest from contextlib import contextmanager @contextmanager def mock_stderr(): from cStringIO import StringIO import sys _stderr = sys.stderr sys.stderr = StringIO() try: yield sys.stderr finally: sys.stderr = _stderr cla...
nilq/baby-python
python
''' Skip-thought vectors ''' from __future__ import print_function from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import zip from builtins import range from past.utils import old_div import os import theano import theano.tensor as tensor import pic...
nilq/baby-python
python
#!/bin/env python ## # @file This file is part of the ExaHyPE project. # @author ExaHyPE Group (exahype@lists.lrz.de) # # @section LICENSE # # Copyright (c) 2016 http://exahype.eu # All rights reserved. # # The project has received funding from the European Union's Horizon # 2020 research and innovation programme unde...
nilq/baby-python
python
from sklearn.compose import ColumnTransformer from sklearn.decomposition import PCA from sklearn.impute import KNNImputer from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import RobustScaler class TrainModel(): @...
nilq/baby-python
python
import cv2 from .drawBoxes import drawBoxes def addPedestriansToTrack(image, tracker, trackers, trackedObjectsNum): if trackers == None: trackers = cv2.MultiTracker_create() markedObjects = trackedObjectsNum while True: manualMarking = cv2.selectROI("Mark pedestrian to track", image) ...
nilq/baby-python
python
import argparse import io import csv import scipy from scipy.sparse import csr_matrix import numpy as np import tensorflow as tf def add_data(r, indptr, indices, data, vocab): if len(r) > 1: label = r[0] for f in r[1:]: if f: k, v = f.split(':') idx = vocab.setdefault(k, len(vocab)) ...
nilq/baby-python
python
import importlib import xarray as xr import numpy as np import pandas as pd import sys import os from CASutils import filter_utils as filt from CASutils import calendar_utils as cal importlib.reload(filt) importlib.reload(cal) def calcdeseas(da): datseas = da.groupby('time.dayofyear').mean('time', skipna=True) ...
nilq/baby-python
python