content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# -*- coding: utf-8 from richtypo import Richtypo from richtypo.rules import NBSP def test_russian_simple(): r = Richtypo(ruleset='ru-lite') text = u'Из-под топота копыт' assert r.richtypo(text) == u'Из-под%sтопота копыт' % NBSP def test_unicode_with_ascii_only_characters(): """ If this test doe...
nilq/baby-python
python
#!/usr/bin/env python2.7 import csv import sys import re from printf import printf a = [1,2,4,5,6,9,10,13,17,19,20,36,38,39,52,68] try: if (sys.argv[1] == '-'): f = sys.stdin.read().splitlines() else: filename = sys.argv[1] f = open(filename, 'r') csv = csv.reader(f) data = list(csv) for row i...
nilq/baby-python
python
__author__ = 'Aneil Mallavarapu (http://github.com/aneilbaboo)' from datetime import datetime import dateutil.parser from errors import InvalidTypeException def default_timestamp_parser(s): try: if dateutil.parser.parse(s): return True else: return False except: ...
nilq/baby-python
python
#!env python3 # Time-Stamp: <2021-04-20 19:12:36> # Copyright 2021 Sho Iwamoto / Misho # # 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 # Unle...
nilq/baby-python
python
""" Download data from here: https://drive.switch.ch/index.php/s/vmAZzryGI8U8rcE Or full dataset here: https://github.com/Waller-Lab/LenslessLearning ``` python scripts/evaluate_mirflickr_admm.py \ --data DiffuserCam_Mirflickr_200_3011302021_11h43_seed11 \ --n_files 10 --save ``` """ import glob import os import pa...
nilq/baby-python
python
import argparse import logging from typing import Callable from typing import Collection from typing import Dict from typing import List from typing import Optional from typing import Tuple import numpy as np import torch from typeguard import check_argument_types from typeguard import check_return_type from espnet2....
nilq/baby-python
python
#!/usr/bin/env python import pcd8544.lcd as lcd logo = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # 0x0010 (16) pixels 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xF8, 0xFC, 0xAE, 0x0E, 0x0E, 0x06, 0x0E, 0x06, # 0x0020 (32) pixels 0xCE, 0x86, 0x8E, 0x0E,...
nilq/baby-python
python
import os import errno from ftplib import FTP # this is used to get all tickers from the market. exportList = [] class NasdaqController: def getList(self): return exportList def __init__(self, update=True): self.filenames = { "otherlisted": "data/otherlisted.txt", "na...
nilq/baby-python
python
import hashlib import json from pathlib import Path from typing import TYPE_CHECKING from poetry.core.packages.utils.link import Link from .chooser import InvalidWheelName from .chooser import Wheel if TYPE_CHECKING: from typing import List from typing import Optional from poetry.config.config import ...
nilq/baby-python
python
import os import json from json import JSONDecodeError from .base import PersistentData def get_key_files(alternate_key_dir=None): key_dir = alternate_key_dir or PersistentData.config_dir try: keyfile_walk = next(os.walk(key_dir)) root, dirs, keyfiles = keyfile_walk key_file_list = [o...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from polyaxon_schemas.base import BaseMultiSchema from polyaxon_schemas.ml.layers.advanced_activations import ( ELUConfig, LeakyReLUConfig, PReLUConfig, ThresholdedReLUConfig ) from polyaxon_schemas.ml.layers.convo...
nilq/baby-python
python
# Importação das Livrarias import numpy as np import matplotlib.pyplot as plt # TODO: # Passo 0: Inicializar o vector de peso e o enviesamento com zeros (ou pequenos valores aleatórios). # Passo 1: Calcular uma combinação linear das características e pesos de entrada. # Passo 2: Aplicar a função sigmoide, que retorna ...
nilq/baby-python
python
# # DecoTengu - dive decompression library. # # Copyright (C) 2013-2018 by Artur Wroblewski <wrobell@riseup.net> # # 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 of the License...
nilq/baby-python
python
from typing import Callable, Union from pandas import DataFrame from ..utils import load as load__ from .paths import file_paths as paths__ def load( keys, info: Union[bool, Callable] = False, ) -> Union[DataFrame, dict]: if isinstance(keys, list): paths = { key: paths__[key] ...
nilq/baby-python
python
import os.path import numpy as np import keras.models from keras.models import model_from_json import tensorflow as tf my_path = os.path.abspath(os.path.dirname(__file__)) digit_model_json = os.path.join(my_path, "../../static/models/digit_model.json") digit_model_h5 = os.path.join(my_path, "../../static/models/digit...
nilq/baby-python
python
#ucapan selamat tahun baru ucapan_happynewyear = ['hello world', 'selamat tahun baru', 'stay safe be productive', 'happy new year', 'Shinen akemashite omedetou gozaimasu 新年あけましておめでとうございます', 'keep spirit and enjoy life'] Mywish_newyear2022 = ['keep productive', 'improving grade', 'accept on state university'] #prin...
nilq/baby-python
python
#Licensed under Apache 2.0 License. #© 2020 Battelle Energy Alliance, LLC #ALL RIGHTS RESERVED #. #Prepared by Battelle Energy Alliance, LLC #Under Contract No. DE-AC07-05ID14517 #With the U. S. Department of Energy #. #NOTICE: This computer software was prepared by Battelle Energy #Alliance, LLC, hereinafter the Cont...
nilq/baby-python
python
import torch import torch.nn as nn import torch.backends.cudnn as cudnn from torch.autograd import Function from torch.autograd import Variable from utils.box_utils import decode # test_RFB.py中被调用,生成的detector对象,结合net输出的out(forward中拆分为loc + conf,结合RFBNet结构, # 可以发现是一个全卷积的feature map,可以结合multibox函数理解),conf就是预测的分类得分, # lo...
nilq/baby-python
python
import textwrap import datetime import glob from collections import Counter from .getApi import getApi from .Exceptions import NoTownError def funcShelves(townName): # API取得部 town = getApi("town", "https://so2-api.mutoys.com/master/area.json") sale = getApi("sale", "https://so2-api.mutoys.com/json/sale/al...
nilq/baby-python
python
from __future__ import absolute_import from datetime import datetime from django.conf import settings from django.contrib import admin from django.contrib.admin import helpers from django.contrib.admin.util import (display_for_field, label_for_field, lookup_field, NestedObjects) from django.contrib.admin.views.ma...
nilq/baby-python
python
# %% import cv2 import os import argparse import time import func import numpy as np # %% args parser = argparse.ArgumentParser() parser.add_argument('-I','--image', default='100', help='import image type, such as 100 or Die') # 輸入圖片類型,範例為'100'及'Die' parser.add_...
nilq/baby-python
python
from redis import Sentinel, Redis from app.core.config import settings import app.core.logging sentinel = Sentinel([(settings.REDIS_SENTINEL_SERVER, settings.REDIS_SENTINEL_PORT)], socket_timeout=0.1) masters = sentinel.discover_master('mymaster') slaves = sentinel.discover_slaves('mymaster') master = sentinel.mas...
nilq/baby-python
python
import os import csv from dream_funcs import DeepDream from PIL import Image, ImageChops import numpy as np # deepdream setup blend_frames = True alpha_step = 0.5 layer = 'mixed5b_1x1' channel = 314 n_iter = 30 step = 1.5 octaves = 8 octave_scale = 1.5 dd = DeepDream(layer, (lambda T: T[:,:,:,channel])) # file data...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Defines earth model objects. :copyright: 2017 Agile Geoscience :license: Apache 2.0 """ import re import os import copy import numpy as np from bs4 import BeautifulSoup import vtk from vtk.util.numpy_support import vtk_to_numpy import matplotlib.pyplot as plt from bruges.transform import d...
nilq/baby-python
python
#!/usr/bin/python from flask import Flask, send_file app = Flask(__name__) @app.route('/image') def get_image(): filename = 'sid.png' return send_file(filename, mimetype='image/png')
nilq/baby-python
python
from .graph_export import export_scenegraph, export_subtree from .graph_import import import_scenegraph, import_subtree
nilq/baby-python
python
import requests import json from datetime import datetime,timedelta class T(object): ENDPOINT = "http://realtime.mbta.com/developer/api/v2/{apicall}" def __init__(self, api_key, response_format='json'): if api_key == "YOUR API KEY HERE" or api_key.strip() == "": raise ValueError("Fill in a...
nilq/baby-python
python
"""templates """ from flask import render_template, request, flash, url_for, redirect, \ send_from_directory, session from flask_login import current_user import datajoint as dj from ast import literal_eval from loris import config from loris.app.forms.dynamic_form import DynamicForm from loris.app.utils import u...
nilq/baby-python
python
# 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, software # d...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ 存储器,支持redis存储,使用zset对代理去重加评分,提供flask的api接口 """ import random import re import redis from proxypool.error import PoolEmptyError from proxypool.settings import HOST,PORT,PASSWORD,DB,INITIAL_SCORE,REDIS_KEY,MIN_SCORE,MAX_SCORE class RedisClient(object): def __init__(self): if PA...
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' julabo.py Contains Julabo temperature control see documentation http://www.julabo.com/sites/default/files/downloads/manuals/french/19524837-V2.pdf at section 10.2. :copyright: (c) 2015 by Maxime DAUPHIN :license: MIT, see LICENSE for details ''' import serial import time from .pytempera...
nilq/baby-python
python
import os import sys from pathlib import Path import numpy as np # Utils filepath = Path(__file__).resolve().parent # sys.path.append( os.path.abspath(filepath/'../ml') ) from ml.keras_utils import r2_krs from ml.data import extract_subset_fea try: import tensorflow as tf if int(tf.__version__.split('.')[0])...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2020 Future Internet Consulting and Development Solutions S.L. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License,...
nilq/baby-python
python
import time from nesta.server.define import define def test_server(control): # send stop command and check status resp = control.execute(command="server", argv=["stop"]) assert resp.exitcode == 0 time.sleep(0.5) resp = control.execute(command="server", argv=["status"]) assert resp.exitcode =...
nilq/baby-python
python
#!/usr/bin/env python import copy def split_train_override_patch(patch, train_parameter_list:list): """ This function returns a list of tuples containing only those parameters that are in the train_parameter_list, and a second list of tuples with the overridden parameters :param patch: original patch ...
nilq/baby-python
python
from ._UFDLObjectDetectionRouter import UFDLObjectDetectionRouter
nilq/baby-python
python
import cv2 img = cv2.imread("./images/sample_01.jpg", cv2.IMREAD_COLOR) cv2.imshow("My image", img) cv2.waitKey(0) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("My image", gray) cv2.waitKey(0) cascade = cv2.CascadeClassifier(cv2.haarcascades + "haarcascade_frontalcatface.xml") faces = cascade.detectMult...
nilq/baby-python
python
"""rest_url has to be hidden. Move it from ui_metadata to the lux_layer_internal_wms Revision ID: 46cb4ef6fd45 Revises: 1b9b2d6fb6e Create Date: 2015-01-07 11:32:20.615816 """ # revision identifiers, used by Alembic. revision = '46cb4ef6fd45' down_revision = '1b9b2d6fb6e' branch_labels = None depends_on = None from...
nilq/baby-python
python
import logging import os from handler.handler_context import HandlerContext from handler.model.base import FieldMask, HandlerBase, merge_resource from handler.model.model_reply import ModelReply from handler.model.model_thread import ModelThread from handler.model.model_user import ModelUser from handler.model.user im...
nilq/baby-python
python
''' Criação de um cronometro feito com POO''' from tkinter import * from tokenize import String class Stopwatch(Frame): def __init__(self, window = None): # Instancias da classe super().__init__(window) self.window = window self.running = False # Utilizado para con...
nilq/baby-python
python
import numpy as np # linear algebra import tensorflow as tf import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split from tensorflow.keras import layers, losses from tensorflow.keras.datase...
nilq/baby-python
python
from PythonPLC import plc import snap7.client as c from snap7.util import * from snap7.snap7types import * # Custom functions def ReadOutput(plc,byte,bit,datatype = S7WLBit): result = plc.read_area(areas['PA'],0,byte,datatype) if datatype==S7WLBit: return get_bool(result,0,bit) elif datatype==S7WLB...
nilq/baby-python
python
############################################## # MusicAnalyzer | 15-112 Term Project # Joel Anyanti | Janyanti ############################################## ############################################## # Imports ############################################## from GameObjects import MusicNote from Settings import ...
nilq/baby-python
python
import os import re import StringIO class Viewer(object): def __init__(self): ''' ''' self.__query_viewer_regex = re.compile('^/deep/.*$') self.__web_dir = 'web/' def content_type(self, extension): ''' ''' return { '.js': 'text/javascript', '.html': 'text/html', '.p...
nilq/baby-python
python
#!/usr/bin/env python3 # Pedir al usuario dos números válidos, si no son válidos seguir pidiendo valores. Efectuar con ellos la suma, resta, multiplicación, división, división entera, resto, y potencias. Utilice control de errores para evitar el error de división entre cero.
nilq/baby-python
python
""" @author: Rossi @time: 2021-01-26 """ from collections import OrderedDict, defaultdict import re from Broca.message import BotMessage from .event import ExternalEnd, ExternalStart, SkillStarted, SkillEnded from .event import BotUttered, SlotSetted, Form, Undo class Skill: def __init__(self): self.nam...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os import hydra import combustion config_path = "../conf" config_name = "config" log = logging.getLogger(__name__) if "WORLD_SIZE" not in os.environ: combustion.initialize(config_path=config_path, config_name=config_name) print("Called in...
nilq/baby-python
python
__all__ = [ "Currencies", "CurrencyResource", ] from decimal import Decimal from typing import Optional from pydantic import validator from decaf.api.client.machinery import BaseResource, ResourceListEndpoint, ResourceRetrieveEndpoint, command from decaf.api.client.types import Currency, Date class Currenc...
nilq/baby-python
python
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. from unittest import TestCase from pyiron_feal.utils import JobName, bfs import numpy as np class TestJobName(TestCase...
nilq/baby-python
python
""" ======================= Coarse Motor Processes ======================= """ import os import random import math import numpy as np from numpy import linspace # vivarium-core imports from vivarium.core.process import Process # plots from chemotaxis.plots.coarse_motor import plot_variable_receptor # directories f...
nilq/baby-python
python
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from recipe_engine import recipe_api DEPS = [ 'commit_position', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/raw_io', ...
nilq/baby-python
python
import math import matplotlib.pyplot as pl import numpy as np def euler1(F, a, b, x0, y0, n): Ly = [y0] Lx = [x0] x= x0 y= y0 h=(b-a)/n while x <= b: y= h*F(x,y)+y x+=h Lx.append(x) Ly.append(y) x= x0 y= y0 while x >= a: y=...
nilq/baby-python
python
import autograd.numpy as anp from pymoo.model.problem import Problem from pymoo.problems.util import load_pareto_front_from_file class CTP(Problem): def __init__(self, n_var=2, n_constr=1, option="linear"): super().__init__(n_var=n_var, n_obj=2, n_constr=n_constr, xl=0, xu=1, type_var=anp.double) ...
nilq/baby-python
python
def bumps(road: str) -> str: return "Woohoo!" if road.count('n') <= 15 else "Car Dead"
nilq/baby-python
python
# Generated by Django 2.1.5 on 2019-01-25 09:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('products', '0004_auto_20190125_1230'), ] operations = [ migrations.RenameField( model_name='choice', old_name='feature1', ...
nilq/baby-python
python
"""All output classes. AffineDynamicOutput - Base class for outputs with dynamics that decompose affinely in the input. FeedbackLinearizableOutput - Base class for feedback linearizable outputs. Output - Base class for outputs PDOutput - Base class for outputs with proportional and derivative components. RoboticSystem...
nilq/baby-python
python
# coding: utf-8 # DO NOT EDIT # Autogenerated from the notebook kernel_density.ipynb. # Edit the notebook and then sync the output with this file. # # flake8: noqa # DO NOT EDIT # # 核密度估计 # # 核密度估计是使用 *核函数* $K(u)$ 估计一个未知概率密度函数的过程。 直方图可以对任意区域中数据点的数量进行计数, # 而核密度估计是定义每个数据点的核函数之和的函数。 核函数通常具有以下属性: # # 1. 对称,使得 $K(u) = K(-...
nilq/baby-python
python
import logging from functools import wraps from .rpc import RPC logger = logging.getLogger(__package__) class NFSv4(RPC): pass
nilq/baby-python
python
import gym import gym_maze from agent.q_learning import QLearning env = gym.make("maze-sample-10x10-v0") env = gym.wrappers.Monitor(env, "q_learning", force=True) agent = QLearning(env, discount_factor=0.9) episodes = 10000 horizon = 10000 epsilon = 0.8 alpha = 1 for episode in range(episodes): observation = env....
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -* from warnings import simplefilter # ignore all future warnings simplefilter(action='ignore', category=FutureWarning) import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import argparse import os import pdb __author__ = "Rickard Hammarén @hammarn...
nilq/baby-python
python
# Generated by Django 2.0.6 on 2018-07-13 06:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parkingsystem', '0021_ticket_amount'), ] operations = [ migrations.RemoveField( model_name='ticket', name='amount', ...
nilq/baby-python
python
from selenium.webdriver.support.select import Select from common.webdriver_factory import get_driver driver = get_driver('chrome') driver.get('https://formsmarts.com/form/axi?mode=h5') first_name = driver.find_element_by_id('u_LY9_60857') first_name.clear() first_name.send_keys('Angie') last_name = driver.find_elemen...
nilq/baby-python
python
from crosswalk_client import Client import pytest def test_setup(token, service): client = Client(token, service) client.create_domain("presidents") client.create_domain("politicians") client.bulk_create([{"name": "George W. Bush"}], domain="politicians") client.bulk_create([{"name": "George W. Bu...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .server import RaspiIOServer, get_registered_handles if __name__ == "__main__": server = RaspiIOServer() for handle in get_registered_handles(): server.register(handle) server.run_forever()
nilq/baby-python
python
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.auth.backends import BaseBackend from django.db.models import Exists, OuterRef, Q from django.core.exceptions import ValidationError from rbac_auth.utils import validate_email UserModel = get_user_mode...
nilq/baby-python
python
#!/usr/bin/env python import random import re import time import datetime import sqlite3 import os import itertools import requests import eveapi from bs4 import BeautifulSoup conn = sqlite3.connect(os.path.expanduser("~/eve.sqlite")) HOME = "PR-8CA" def calc_jumps(system, start): url = "http://evemaps.dotlan.net/ro...
nilq/baby-python
python
# # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. from antlr4.atn.ATNState import StarLoopEntryState from antlr4.atn.ATNConfigSet import ATNConfigSet from antlr4.dfa.DFAState im...
nilq/baby-python
python
import numpy as np """ this file will create a GM(grey prediction machine), and enable user to predict the future data based on current array of data. please note that this machine is based on first order differential equation, so it will be good at predicting data with certain trend( growing or minimizing), not very ...
nilq/baby-python
python
""" Test the gva logger, this extends the Python logging logger. We test that the trace method and decorators raise no errors. """ import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) from gva.logging import LEVELS, get_logger, error_trap, verbose_logger try: from rich import traceback ...
nilq/baby-python
python
import logging, json, requests, jieba, sys, os, copy, re #from nlutools import tools as nlu from english_corrector import EnglishCorrector from data_utils import load_word_freq_dict, _get_custom_confusion_dict from utils import re_en, re_salary, is_alphabet_string, pinyin2hanzi, ErrorType, PUNCTUATION_LIST from config ...
nilq/baby-python
python
from .redict import ReDict, update_with_redict
nilq/baby-python
python
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random df = pd.DataFrame(np.random.choice(np.arange(0, 2), p=[0.9, 0.1],size=(10000, 5)), columns=list('ABCDE')) total_views = 10000 num_ads = 5 ad_list = [] total_reward = 0 for view in range(total_views): ad = random.randrange(num_ad...
nilq/baby-python
python
""" Optimizers --------- Module description """ from abc import ABC, abstractmethod from collections.abc import Iterable import copy import torch from brancher.standard_variables import Link from brancher.modules import ParameterModule, EmptyModule from brancher.variables import BrancherClass, Variable, Probabilistic...
nilq/baby-python
python
from PyQt5.QtWidgets import (QWidget, QToolButton, QPushButton, QVBoxLayout, QHBoxLayout, QWidgetAction, QMenu) from PyQt5.QtCore import Qt, pyqtSignal, QModelIndex, QSize from transcode.pyqtgui.qitemmodel import (QItemModel, Node, ChildNodes, NoCh...
nilq/baby-python
python
from wafw00f.main import WafW00F from wafw00f.lib.evillib import oururlparse from util.http_util import http_client __plugin__ = "Subdomain Scanner" SEQUENCE = 2 URL = "https://www.virustotal.com/vtapi/v2/domain/report" API_KEY = "a0283a2c3d55728300d064874239b5346fb991317e8449fe43c902879d758088" async def run(ur...
nilq/baby-python
python
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose import astropy.units as u from astropy.io import fits from gammapy.irf import Background3D, EffectiveAreaTable2D, EnergyDispersion2D class TestIRFWrite: def setup(self): self.energy...
nilq/baby-python
python
link='https://www.giveindia.org/certified-indian-ngos' def List_of_Indian_NGOs_to_donate(url): from bs4 import BeautifulSoup import pprint import requests page = requests.get(url) soup = BeautifulSoup(page.text,"html.parser") man_class=soup.find('table',class_='jsx-697282504 certified-ngo-table') list1=[] for ...
nilq/baby-python
python
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
nilq/baby-python
python
import types __all__ = ["lzip", "lfilter", "lfilternone", "copy_func", "find_in_bases"] def lzip(*iterables): r""" Shorthand for list(zip(*iterables)) """ return list(zip(*iterables)) def lfilter(func, iterable): r""" Shorthand for list(filter(func, iterable)) """ return list(filter(func, iterable)) def lfi...
nilq/baby-python
python
from pathlib import Path from statistics import median_high, mean import tensorflow as tf from metrics.base import Metric class SATAccuracy(Metric): def __init__(self) -> None: self.mean_acc = tf.metrics.Mean() self.mean_total_acc = tf.metrics.Mean() def update_state(self, model_output, st...
nilq/baby-python
python
class Dimensions(): """ Two dimensions: width and height """ def __init__(self, width, height): self.width = int(width) self.height = int(height)
nilq/baby-python
python
import numpy as np import pandas as pd from scipy import stats from math import isnan def apply(series, period, func, category=None, return_as_cat=None) -> pd.Series: """ Apply 'func' to rolling window grouped by 'category' :param series: time-series :param period: rolling window period :param fun...
nilq/baby-python
python
""" python consumer, consume messages from amqp and execute python code """ __version__ = '0.1.0'
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt from open_spiel.python.egt import dynamics from open_spiel.python.project.part_1.visualization import paths from open_spiel.python.project.part_1.visualization.probarray_visualization import prepare_plot payoff_matrix_prisoners_dilemma = np.array([[[3,0],[5,1]],[[3...
nilq/baby-python
python
from django.db import models class Mod(models.Model): fld = models.IntegerField() class M2mA(models.Model): others = models.ManyToManyField('M2mB') class M2mB(models.Model): fld = models.IntegerField()
nilq/baby-python
python
from math import prod import qiskit import numpy as np from generate_training_set import insert_pauli from qiskit import QuantumCircuit from random import sample, seed from itertools import product def get_measuring_circuit(basis_list: list) -> QuantumCircuit: qc = QuantumCircuit(len(basis_list[0][1])) # Find...
nilq/baby-python
python
""" The `domain` package provides a data structure for representing multi-zone meshes and their related data. The goal is to be able to represent all concepts from CGNS, though not necessarily in the same way. It also provides functions for obtaining flow values across a mesh surface and reading/writing in files vario...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @Time : 2019-11-03 13:04 # @Author : ljj0452@gmail.com import datetime from mongoengine import ( Document, StringField, DateTimeField, IntField, FloatField, BooleanField, EmbeddedDocument, EmbeddedDocumentListField ) class WorkerDetail(EmbeddedDocument): ...
nilq/baby-python
python
import csv import argparse data = [] parser = argparse.ArgumentParser(description='file input for parse bank information') parser.add_argument('--file', metavar='str', type=str) args = parser.parse_args() with open(args.file, 'rb') as csvfile: reader = csv.reader(csvfile) i = 0 for row in reader: ...
nilq/baby-python
python
#!/usr/bin/env python from __future__ import print_function import sys import glob import time import os, os.path import doctest import unittest try: import coverage except ImportError: print("No 'coverage' module found. Try:") print(" sudo apt-get install python-coverage") sys.exit(1) import logg...
nilq/baby-python
python
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np from scipy i...
nilq/baby-python
python
a = float(input()) b = float(input()) media = ((a*3.5) + (b*7.5)) / 11 print('MEDIA = {:.5f}'.format(media))
nilq/baby-python
python
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def homePageView(request): return HttpResponse('OK!')
nilq/baby-python
python
"""Error handling utils.""" import nestor_api.lib.io as io from nestor_api.utils.logger import Logger def non_blocking_clean(path: str, *, message_prefix: str = None): """Try to clean directory/file at path but don't raise an error if it fails (only log it).""" message = "Error trying to clean temporary ...
nilq/baby-python
python
from flask import Flask, jsonify, render_template, request from flask_sqlalchemy import SQLAlchemy from random import choice app = Flask(__name__) # Connect to Database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Cafe TABLE...
nilq/baby-python
python
from random import randint def quicksort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: ...
nilq/baby-python
python
# https://packaging.python.org/en/latest/distributing.html from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( # details nam...
nilq/baby-python
python
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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...
nilq/baby-python
python
class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums or k==0: return [] n=len(nums) queue=collections.deque() res=[] """ using the dequ...
nilq/baby-python
python
from django.core.cache import cache from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "verspaeti/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) verspaeti_data_cache = cache.get('verspaeti_data') ...
nilq/baby-python
python