content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
nilq/baby-python
python
from raybot import config from raybot.model import db, POI, Location from raybot.bot import bot from raybot.util import h, get_user, get_map, pack_ids, uncap, tr import csv import re import os import random import logging from typing import List, Tuple from datetime import datetime from aiogram import types from aiogra...
nilq/baby-python
python
import numpy as np import math from keras.initializers import RandomUniform from keras.models import model_from_json from keras.models import Sequential from keras.layers import Dense, Flatten, Input, Lambda, Activation from keras.layers.merge import concatenate from keras.models import Sequential, Model from keras.opt...
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 fi...
nilq/baby-python
python
# Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’. # Example 1: # Input: [2, 1, 5, 1, 3, 2], k=3 # Output: 9 # Explanation: Subarray with maximum sum is [5, 1, 3]. # Example 2: # Input: [2, 3, 4, 1, 5], k=2 # Output: 7 # Explanation: Subarra...
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
import tkinter as tk from tkinter import * from tkinter import filedialog from tkinter import messagebox from Bio import Entrez import os doubleBackSlash = r'/ '[0] class Script1: def __init__(self): self.a_InputCSVFileName = "" self.b_OutputPATH = "" self.c_OutputFileName...
nilq/baby-python
python
import torch import torch.nn as nn import torch.optim as optim import numpy as np class DeepModel(nn.Module): def __init__( self, num_states, num_actions, ): super(DeepModel, self).__init__() self.conv1 = nn.Conv2d(1,20,(1,1)) self.conv2 = nn.Conv2d(1,20,(1,7...
nilq/baby-python
python
import logging import traceback lgr = logging.getLogger('datalad.revolution.create') _tb = [t[2] for t in traceback.extract_stack()] if '_generate_extension_api' not in _tb: # pragma: no cover lgr.warn( "The module 'datalad_revolution.revcreate' is deprecated. " 'The `RevCreate` class can be impo...
nilq/baby-python
python
# coding: utf-8 # Written by Lucas W. for Python 3.7.0 """Initialisation""" from time import time from threading import Timer from copy import deepcopy from random import choice name = "Terminal Chess (by Lucas W. 2019)" board_template = [ #standard setup ['wR','wN','wB','wQ','wK','wB','wN','wR'], ['wP','wP','wP','wP'...
nilq/baby-python
python
from hubcheck.pageobjects.widgets.item_list_item import ItemListItem from hubcheck.pageobjects.basepageelement import TextReadOnly, Link class TagsBrowseResultsRow1(ItemListItem): def __init__(self, owner, locatordict={}, row_number=0): super(TagsBrowseResultsRow1,self).__init__(owner,locatordict,row_num...
nilq/baby-python
python
import argparse import csv import sqlite3 import sys import random import time import sys import math #c.execute(UPDATE {} SET member=? WHERE callsign LIKE ? find_parent_sql = "SELECT * FROM orgs WHERE parentcallsign LIKE ?" org_insert_sql = "INSERT INTO orgs VALUES(?,?,?)" def update_org_id(table): return "UPDA...
nilq/baby-python
python
import logging import time from celery import shared_task from django.db import transaction from pontoon.checks.utils import ( bulk_run_checks, get_translations, ) log = logging.getLogger(__name__) @shared_task(bind=True) def check_translations(self, translations_pks): """ Run checks on translatio...
nilq/baby-python
python
from datetime import datetime import pytest from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from optuna.storages.rdb.models import BaseModel from optuna.storages.rdb.models import StudyModel from optuna.storages.rdb.models import StudySystemAttributeMod...
nilq/baby-python
python
from typing import Any, Dict, Iterator, List, Optional from loguru import logger from pydantic import Field from ..metadata_source import ColumnMetadata from .external_metadata_source import ( ExternalMetadataSource, ExternalMetadataSourceException, ) try: import boto3 import botocore from mypy_b...
nilq/baby-python
python
from django.conf.urls import patterns, include, url #from polls import views from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_angularjs_rest.views.home', name='home'), # url(r'^django_angularjs_rest/', include('django_angularjs_rest.foo.urls...
nilq/baby-python
python
from vk import VKAPI class Photos(VKAPI): method_class = 'photos' def __init__(self, access_token=''): super(Photos, self).__init__(access_token=access_token) def confirm_tag(self, **params): self.set_method('confirmTag') return self.send(params) def copy(self, **params)...
nilq/baby-python
python
from setuptools import setup, find_packages from distutils.util import convert_path long_description =""" # Virtual Pi The easiest way to use this package is to install using pip3 for python 3 ```bash $ sudo pip3 install VPi ``` To use the mock or virtual pi just type the following at the beginning of your script....
nilq/baby-python
python
# Concatenate strings in a (nested) list # 1. concatenate strings in a non-nested list # 2. list are themselves lists def concat_str(string_list): """ Concatenate all the strings in a possibly-nested list of strings @param str|list(str|list(...)) string_list: this string list. @rtype: str >>> lis...
nilq/baby-python
python
from __future__ import absolute_import, unicode_literals import os from setuptools import find_packages, setup version = __import__('logtailer').__version__ def read(fname): # read the contents of a text file return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-logtai...
nilq/baby-python
python
##TODO: move this to a common location from db_password import DB_PASSWORD DB_ENGINE = "postgresql_psycopg2" DB_NAME = "testdb"# "ConceptNet" DB_HOST = "localhost" # or whatever server it's on DB_PORT = "5432" # or whatever port it's on DB_USER = "pat" # change this to your PostgreSQL username DB_SCHEMA...
nilq/baby-python
python
from flask import Blueprint from flask import request from flask import jsonify from dock.common.exceptions import AppBaseException blueprint = Blueprint('transaction', __name__, url_prefix='/transaction') class Provision(object): def __init__(self): pass @classmethod def create(cls, p): ...
nilq/baby-python
python
#!/usr/bin/env python3 import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import learn2learn as l2l from learn2learn.data.transforms import NWays, KShots, LoadData, RemapLabels def pairwise_distances_logits(a, b): n = a....
nilq/baby-python
python
"""Shared pytest fixtures.""" import os import re import unittest.mock as mock from http.server import HTTPServer import pytest from pywemo import SubscriptionRegistry @pytest.fixture(scope='module') def vcr_config(): """VCR Configuration.""" def scrub_identifiers(response): body = response['body'...
nilq/baby-python
python
import json import pickle import sqlite3 import time import pandas as pd from old.src.Model.Redis_connecter import RedisConn def picklify(df): dt_bytes = pickle.dumps(df) return dt_bytes def res_depicklify_to_list(): r = RedisConn().r db = sqlite3.connect("t0419.db") res = [] count = r.scar...
nilq/baby-python
python
""" gcae.py PyTorch-Lightning Module Definition for the No-Language Latent Actions GELU Conditional Auto-Encoding (GCAE) Model. """ from pathlib import Path from typing import Any, List, Tuple import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim...
nilq/baby-python
python
# Sample file to deploy Cubes slicer as a WSGI application import sys import os.path import ConfigParser CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(CURRENT_DIR, "slicer.ini") try: config = ConfigParser.SafeConfigParser() config.read(CONFIG_PATH) except Exception as e...
nilq/baby-python
python
# # PySNMP MIB module ADAPTECSCSI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADAPTECSCSI-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:13:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
nilq/baby-python
python
import requests, zipfile, io, subprocess, os, sys from datetime import datetime from dotenv import load_dotenv load_dotenv() ZIP_FILE_URL = os.getenv('ZIP_FILE_URL') if not ZIP_FILE_URL: sys.exit('Error getting zip file url from env') try: r = requests.get(ZIP_FILE_URL) except: sys.exit('Error getting fi...
nilq/baby-python
python
from behave import then @then("The response status is {response_status:d}") def check_response_status(context, response_status): assert context.status == response_status
nilq/baby-python
python
import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.models import Model, Sequential from tensorflow.keras.layers import Layer from tensorflow.keras.layers import (Input, Concatenate, Dense, Activation, BatchNormalization, Reshape, Dropout, ...
nilq/baby-python
python
import os import sys import dicom import numpy as np # import SimpleITK as sitk from matplotlib import use use("Qt4Agg") from matplotlib import pyplot as plt from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.patches import Polygon from...
nilq/baby-python
python
import os import torch import shutil import pickle import numpy as np from tqdm import tqdm from pathlib import Path from torch.utils.data import Dataset class P3B3(Dataset): """P3B3 Synthetic Dataset. Args: root: str Root directory of dataset where CANDLE loads P3B3 data. part...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Natural Convection heat transfer calculation based on Churchill and Chu correlation """ def Churchill_Chu(D, rhof, Prf, kf, betaf, alphaf, muf, Ts, Tinf): """ Natural Convection heat transfer calculation based on Churchill and Chu correlation :param D: [m] Pipe inside di...
nilq/baby-python
python
import functools import numpy as np import unittest from scipy.stats import kendalltau, pearsonr, spearmanr from sacrerouge.data import Metrics from sacrerouge.stats import convert_to_matrices, summary_level_corr, system_level_corr, global_corr, \ bootstrap_system_sample, bootstrap_input_sample, bootstrap_both_sam...
nilq/baby-python
python
from argparse import ArgumentParser def parse_args(): parser = ArgumentParser(description="An auto downloader and uploader for TikTok videos.") parser.add_argument("user") parser.add_argument( "--no-delete", action="store_false", help="don't delete files when done" ) parser.add_argument( ...
nilq/baby-python
python
from random import randint from lotto import getLotto from wc.wc import WC def getBoard(width=5, height=5, extra=75 - 5 * 5): lotto = getLotto(width, height, extra) board = [[lotto.draw() for _ in range(width)] for __ in range(height)] # TODO free spaces return Board(board, width, height) def transpose(board): r...
nilq/baby-python
python
from infra.controllers.contracts.http import HttpRequest from cerberus import Validator from infra.controllers.validators.ports import CerberusErrors, PayloadValidator from utils.result import Error, Ok, Result class AddNewDebtValidator(PayloadValidator): def __init__(self) -> None: self.schema = { ...
nilq/baby-python
python
# Generated by Django 2.2.13 on 2020-10-27 04:49 from django.db import migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ("navigation", "0002_remove_pri_sec_footer_navs"), ] operations = [ migrations.AddField( ...
nilq/baby-python
python
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "l...
nilq/baby-python
python
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Oct 4 22:53:41 2016 @author: midhununnikrishnan """ import numpy as np import combinatorics as cb def sumofdigits(G,k=1)->int: """find + of digits """ su = 0 while G > 0: if k == 1: su += (G%10) else: su += (G%...
nilq/baby-python
python
from lacore.adf.persist import make_adf from lacore.archive import restore_archive as _restore_archive from lacli.nice import with_low_priority from lacli.hash import HashIO def archive_handle(docs): h = HashIO() make_adf(docs, out=h) return h.getvalue().encode('hex') restore_archive = with_low_priority(...
nilq/baby-python
python
import pandas as pd def find_related_cols_by_name(dataframe_list, relationship_dict=None): # dataframe_list # List of pandas dataframe objects # # relationship_dict # This is an existing relationship_dict. If None, a new # relationship_dict should be created ### # Studen...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 5 10:15:25 2021 @author: lenakilian """ import pandas as pd import copy as cp import geopandas as gpd wd = r'/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis/' years = list(range(2007, 2018, 2)) geog = 'MSOA' yr = 2015 dict_cat = 'c...
nilq/baby-python
python
""" Provides helping function for issues. """ import copy from json import JSONDecodeError from math import ceil from typing import Optional, List, Collection, Dict import arrow from pyramid.request import Request from slugify import slugify from dbas.database import DBDiscussionSession from dbas.database.discussion_...
nilq/baby-python
python
# Generated by Django 3.0.7 on 2020-07-12 09:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin_app', '0004_order_arsip'), ] operations = [ migrations.AddField( model_name='order', name='p1_a', ...
nilq/baby-python
python
import torch import torch.nn as nn from torchvision import models from torchvision import transforms from bench_press.models.modules.spatial_softmax import SpatialSoftmax pretrained_model_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, ...
nilq/baby-python
python
import arcade import math import random import settings # default window SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = "WeFly X Charlie" BULLET_SPEED = 2 Score = 0 INSTRUCTIONS_PAGE_0 = 0 INSTRUCTIONS_PAGE_1 = 1 GAME_RUNNING = 2 GAME_OVER = 3 WIN = 4 position_y_1 = 600 position_y_2 = 0 # default boss' propert...
nilq/baby-python
python
from Crypto.Cipher import AES import base64 import hashlib def jm_sha256(data): sha256 = hashlib.sha256() sha256.update(data.encode("utf-8")) res = sha256.digest() # print("sha256加密结果:", res) return res def pkcs7padding(text): bs = AES.block_size length = len(text) ...
nilq/baby-python
python
import os import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration DEBUG = False DOMAIN_NAME = "deeptipandey.site" AWS_STORAGE_BUCKET_NAME = AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME", "") AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID", "") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_AC...
nilq/baby-python
python
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' print("Задача 1") for i in range(1, 6): print(i, 0) i += 1 ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' print("Задача 2") count = 0 for i in ran...
nilq/baby-python
python
#coding=utf-8 import os, re, sys import json import datetime from openpyxl import load_workbook def parse_cell_value(value): #布尔类型 if isinstance(value, bool): return value #int类型 if isinstance(value, int): return value #float类型 if isinstance(value, float): return value ...
nilq/baby-python
python
import os.path from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from PIL import Image import random import util.util as util import numpy as np class ConditionalDataset(BaseDataset): """ This dataset class can load unaligned/unpaired datasets with classes. ...
nilq/baby-python
python
import json import urlparse import sys def handle(req): """handle a request to the function Args: req (str): request body """ sys.stderr.write(req) qs = urlparse.parse_qs(req) if "user_name" in qs: if not qs["user_name"][0] == "slackbot": emoticons = "" ...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt class PlotDrawer: @staticmethod def draw(mfcc_data): PlotDrawer.__prepare_plot(mfcc_data) plt.show() # plt.close() @staticmethod def save(filename, mfcc_data): PlotDrawer.__prepare_plot(mfcc_data) plt.savefig(...
nilq/baby-python
python
import datetime import io import operator import os import re from zipfile import ZipFile # def make_entry(entry): # if isinstance(entry, Entry): # return entry # mtime = os.path.getmtime(entry) # return Entry(entry, mtime) # handlers = { # ".zip": (lambda x: None) # } # class DirectoryHand...
nilq/baby-python
python
# Copyright (c) 2014 Rackspace Hosting # 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 req...
nilq/baby-python
python
#!/usr/bin/python import random import math import shelve import os #initialize constants STARTING_AMOUNT = 1000 MAX_BETS = 10000 #ROUND_LIMIT = 500000 ROUND_LIMIT = 5000 #whether or not to give verbose terminal output for each round of gambling #note: with short rounds, terminal output becomes a significant bottlenec...
nilq/baby-python
python
# Copyright 2016 Ericsson AB. # # 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...
nilq/baby-python
python
import mfclient import mf_connect import csv import time projSummary = "MFProjectSummary" storeSummary = "MFStoreSummary" timestr = time.strftime("%Y%m%d-%H%M%S") with open(projSummary+timestr+".csv", 'ab') as f: header = ["project","allocation","usage"] writer = csv.writer(f) writer.writerow(header) ...
nilq/baby-python
python
from flask import jsonify, request, abort, Blueprint from ..auth0 import auth from ..auth0.authManagementAPI import * from datetime import * from ..db.models import * api = Blueprint('api', __name__) # build Auth0 Management API builder = Auth0ManagementAPIBuilder() auth0api = builder.load_base_url(). \ load_acce...
nilq/baby-python
python
from _collections import deque def solution(): people = deque() while True: name = input() if name == 'End': print(f'{len(people)} people remaining.') break elif name == 'Paid': while people: popped_person = people.popleft() ...
nilq/baby-python
python
from numpywren import compiler, frontend, exceptions import unittest import astor import ast import inspect def F1(a: int, b: int) -> int: return a//b def F2(a: float, b: int) -> float: return a + b def F3(a: float, b: int) -> float: c = a + b d = log(c) e = ceiling(d) return c def F4(a:...
nilq/baby-python
python
from datetime import date from new_movies import movies_directory from new_movies.configuration import UNLIMITED_WATCHING_START_DATE, UNLIMITED_WATCHING_END_DATE from new_movies.exceptions import NoCreditsForMovieRent, MovieNotFound, ViewsLimitReached from new_movies.movie import Movie from new_movies.rented_movie imp...
nilq/baby-python
python
################################################################################ # # Implementation of angular additive margin softmax loss. # # Adapted from: https://github.com/clovaai/voxceleb_trainer/blob/master/loss/aamsoftmax.py # # Author(s): Nik Vaessen ###########################################################...
nilq/baby-python
python
#!/usr/bin/env python import os import sqlite3 from datetime import datetime from getpass import getuser from bashhistory import db_connection class SQL: COLUMNS = [ "command", "at", "host", "pwd", "user", "exit_code", "pid", "sequence", ] CREATE_COMMANDS: str = """ DROP TA...
nilq/baby-python
python
import numpy as np import pandas as pd def print_matrix(matrix): pd.set_option('display.max_rows', len(matrix)) print() print(matrix) def normalize(matrix): return matrix.div(matrix.sum(axis=1), axis=0) def generate_matrix(data): key_set = set(data.keys()) for edges in data.values(): ...
nilq/baby-python
python
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse class NegativeTargets(Client): """Amazon Advertising API for Sponsored Display Documentation: https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi#/Negative%20targeting This API enables programmatic access ...
nilq/baby-python
python
from vpython import * scene.title = "VPython: Draw a sphere" sphere() # using defaults #see http://www.vpython.org/contents/docs/defaults.html
nilq/baby-python
python
# -*- coding: utf-8 -*- import requests #resp = requests.post("http://localhost:5000/predict", json={"raw_text":"how do you stop war?"}) # resp_prod = requests.post("http://213.159.215.173:5000/get_summary", json={"raw_text":"A significant number of executives from 151 financial institutions in 33 countries say that ...
nilq/baby-python
python
# Generated by Django 3.2.6 on 2021-09-01 20:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('produtos', '0004_ajuste_produtos'), ] operations = [ migrations.CreateModel( name='Fornecedor',...
nilq/baby-python
python
import os dirpath = os.pardir import sys sys.path.append(dirpath) import torch.utils.model_zoo as model_zoo from torch.autograd import Variable from torch.optim import lr_scheduler import resnet_epi_fcr import resnet_vanilla import resnet_SNR import resnet_se from common.data_reader import BatchImageGenerator from c...
nilq/baby-python
python
from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from .models import ( Cart, Item ) from .serializers import ( CartSerializerDefault, CartSerializerPOST, ItemSerializerDefault, ItemSerializerPOST ) class CartViewSet(ModelViewSet): ...
nilq/baby-python
python
#coding:utf-8 # # id: bugs.core_1056 # title: A query could produce different results, depending on the presence of an index # decription: # tracker_id: CORE-1056 # min_versions: [] # versions: 2.0 # qmid: bugs.core_1056 import pytest from firebird.qa import db_factory, isql_act, Acti...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-22 19:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mimicon2016', '0001_initial'), ] operations = [ migrations.AlterField( model_name='signupextra', ...
nilq/baby-python
python
from django.contrib import admin from models import * # Register your models here. class CategoryAdmin(admin.ModelAdmin): list_display = ['id', 'title'] class GoodsInfoAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'price', 'unit', 'click', 'inventory', 'detail', 'desc', 'image'] admin.site.regis...
nilq/baby-python
python
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import db, login_manager @login_manager.user_loader def load_user(id): return User.query.get(int(id)) dictionary_table = db.Table('dictionary', db.Column('user_id', d...
nilq/baby-python
python
from typing import List, Tuple import torch from torch.utils.data import Dataset from .feature import InputFeature class FeaturesDataset(Dataset): def __init__(self, features: List[InputFeature]): self.features = features def __len__(self,): return len(self.features) def __getitem__(s...
nilq/baby-python
python
# Lint as: python2, python3 # Copyright 2019 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 req...
nilq/baby-python
python
#!/usr/bin/env python3 """Emulate a client by calling directly EC2 instance.""" import os import sys import json import logging # AWS Lambda does not ship requests out of the box # import requests import urllib3 # Global configuration logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.IN...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Implement S3 Backed Binary and Unicode Attribute. Since the content of big Binary or Unicode are not stored in DynamoDB, we cannot use custom attriubte ``pynamodb.attributes.Attribute`` to implement it. """ import os import zlib from base64 import b64encode, b64decode from pynamodb.model...
nilq/baby-python
python
# Copyright 2016 Isotoma Limited # # 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...
nilq/baby-python
python
from __future__ import print_function, division import sys sys._running_pytest = True import pytest from sympy.core.cache import clear_cache def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .munsell import * # noqa from . import munsell __all__ = [] __all__ += munsell.__all__
nilq/baby-python
python
import argparse import importlib from verify import mnist, cifar, imagenet import time def verify(args): try: net_class_module = importlib.import_module(args.netclassfile) net_class = getattr(net_class_module, args.netclassname) except Exception as err: print('Error: Import ...
nilq/baby-python
python
""" Produces template's named argument to article categories mapping """ from __future__ import print_function import logging import json import re from collections import defaultdict from mwclient.client import Site import requests logging.basicConfig(level=logging.INFO) def get_articles_from_top_categories(site...
nilq/baby-python
python
""" BaMi_optimal.py - compares BaMiC with BaMiF and includes the (according to us) optimal integration strategies. """ import sys import matplotlib.pyplot as plt from pywmi.engines.xsdd.literals import LiteralInfo from _pywmi.vtree.bottomup_elimination import bottomup_balanced_minfill as bamif from _pywmi.vtree.topdow...
nilq/baby-python
python
# Lint as: python3 # Copyright 2018 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 ...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright 2021 Cloudera, Inc. # # 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...
nilq/baby-python
python
# by amounra 0216 : http://www.aumhaa.com # written against Live 9.6 release on 021516 from __future__ import absolute_import, print_function import Live import math from ableton.v2.base import inject, listens from ableton.v2.control_surface import ControlSurface, ControlElement, Layer, Skin, PrioritizedResource, Co...
nilq/baby-python
python
# <Copyright 2019, Argo AI, LLC. Released under the MIT license.> """Collection of utility functions for Matplotlib.""" from typing import Any, Dict, List, Optional, Tuple, Union import matplotlib.pyplot as plt import numpy as np from descartes.patch import PolygonPatch from matplotlib.animation import FuncAnimation ...
nilq/baby-python
python
from fastapi.testclient import TestClient from app.main import app client = TestClient(app) def test_valid_input(): """Return 200 Success when input is valid.""" response = client.post( '/predict', json={ 'title': 'Water bike', 'blurb': 'A bike that floats', ...
nilq/baby-python
python
encode,decode=lambda s:''.join(c//200*"🫂"+c%200//50*"💖"+c%50//10*"✨"+c%10//5*"🥺"+c%5*","+(c==0)*"❤️"+"👉👈"for c in s.encode()),lambda s:bytes([200*(c:=b.count)("🫂")+50*c("💖")+10*c("✨")+5*c("🥺")+c(",")for b in s.split("👉👈")[:-1]]).decode()
nilq/baby-python
python
# -*- coding: utf-8 -*- """Sweep config interface.""" from .cfg import SweepConfig, schema_violations_from_proposed_config from .schema import fill_validate_schema, fill_parameter, fill_validate_early_terminate __all__ = [ "SweepConfig", "schema_violations_from_proposed_config", "fill_validate_schema", ...
nilq/baby-python
python
from typing import Callable from fastapi import FastAPI from app.db.init_db import init_db, create_engine def create_startup_handler(app: FastAPI, db_url: str) -> Callable: async def startup() -> None: engine = create_engine(db_url) await init_db(engine) app.state.alchemy_engine = engine...
nilq/baby-python
python
__author__ = 'socialmoneydev' from jsonBase import JsonBase from programlimit import ProgramLimit from programinterestrate import ProgramInterestRate class ProgramChecking(JsonBase): def isHashedPayload(self): return True def __init__(self): self.category = None self.type = None ...
nilq/baby-python
python
#!/usr/local/bin/python3.5 -u answer = 1 + 7 * 7 - 8 print(answer)
nilq/baby-python
python
__version__ = '0.1.5' name = "drf_scaffold"
nilq/baby-python
python
def count_prime_fuctors(n, c): # count the number of primes in particular number # argument `c` should be Counter class if n<2: return m=n i=2 while i<=m: while m%i==0: m//=i c[i]+=1 i+=1 from collections import Counter n=int(input()) d=Counter() ...
nilq/baby-python
python