content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import os
import json
import pkgutil
import datetime
import ast
import yaml
from yaml import Loader
# Get version without importing module
mod = ast.parse(pkgutil.get_data(__name__, "__init__.py").decode())
assignments = [node for node in mod.body if isinstance(node, ast.Assign)]
__version__ = [node.value.s for node ... | nilq/baby-python | python |
import os
import json
import base64
from urllib import request
from io import BytesIO
def _download_file(url, local_file_path):
response = request.urlopen(url)
with open(local_file_path, 'wb') as local_file:
local_file.write(BytesIO(response.read()).read())
def _upload_to_s3(s3_interface, local_soft... | nilq/baby-python | python |
from runtime import *
"""list.pop(n)"""
def main():
a = list(range(10))
print a
b = a.pop()
print b
print a
assert( b==9 )
c = a.pop(0)
assert( c==0 )
d = ['A', 'B', 'C']
assert( d.pop(1)=='B' )
assert( len(d)==2 )
main()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
import re
from datetime import timedelta, datetime
from DictObject import DictObject
from luckydonaldUtils.logger import logging
from luckydonaldUtils.encoding import unicode_type, to_unicode as u, to_native as n
from luckydonaldUtils.functions import deprecated
from luckydonaldUtil... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | nilq/baby-python | python |
from math import trunc
num = float(input("Digite um valor: "))
print("\nO valor digitado foi {} e a sua porção inteira é {}".format(num, trunc(num))) | nilq/baby-python | python |
from PyQt5 import QtWidgets
import difflib
from nixui.graphics import generic_widgets
class DiffedOptionListSelector(generic_widgets.ScrollListStackSelector):
ItemCls = generic_widgets.OptionListItem # TODO: remove break dependency with generic_widgets.py
def __init__(self, updates, *args, **kwargs):
... | nilq/baby-python | python |
"""
This file will parse the input text file and get important
knowledge from it and create a database known as Knowledge Base
"""
import json
import os
from engine.components.knowledge import Knowledge
from engine.logger.logger import Log
class KnowledgeBaseParser:
"""
Class the parse the file and create t... | nilq/baby-python | python |
# Generated by Django 3.1.2 on 2021-04-23 20:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recruiters', '0002_auto_20210423_2028'),
]
operations = [
migrations.RemoveField(
model_name='job',
name='slug',
),
... | nilq/baby-python | python |
"""
Ringing artifact reduction example
==================================
This example shows how to subtract the impulse response from a filter to
reduce ringing artifacts.
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import butter, lfilter
from meegkit.detrend import reduce_ringing
# i... | nilq/baby-python | python |
import numpy as np
import statsmodels.formula.api as smf
from patsy import dmatrix, build_design_matrices
from pandas import DataFrame
class QuantileSpline:
def __init__(self, quantiles=0.5, df=3):
self.quantiles = quantiles
self.df = df
self.label = 'Quantile Spline'
self.filename ... | nilq/baby-python | python |
# Copyright 2008 German Aerospace Center (DLR)
#
# 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 |
from django.test import TestCase
from . import factories
from .. import models
class TestCard(TestCase):
model = models.Card
def test_str(self):
"""A card's str representation is its name."""
name = 'Leeroy Jenkins'
card = factories.CardFactory.create(name=name)
self.assertEq... | nilq/baby-python | python |
from foolbox.zoo import git_cloner
import os
import hashlib
import pytest
from foolbox.zoo.git_cloner import GitCloneError
def test_git_clone():
# given
git_uri = "https://github.com/bethgelab/convex_adversarial.git"
expected_path = _expected_path(git_uri)
# when
path = git_cloner.clone(git_uri)
... | nilq/baby-python | python |
# pip3 install 'gym[atari,accept-rom-license]==0.22.0'
import matplotlib.pyplot as plt
import gym
from gym import wrappers
import random
import numpy as np
env = gym.make('ALE/MsPacman-v5', render_mode='human')
height, width, channels = env.observation_space.shape
actions = env.action_space.n
episodes = 1
random_mo... | nilq/baby-python | python |
from django import template
register = template.Library()
@register.filter
def mul(value, arg):
arg = int(arg)
return int(value * arg) | nilq/baby-python | python |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # ####
# ## ## # ## # #
# # # # # # # # # ###
# # ## # ## ## #
# # # # # # ####
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 ... | nilq/baby-python | python |
import logging
import os
import arrow
from humanfriendly import parse_size
from .api import delete_file, get_all_results, upload_file
from .utils_fs import download_file, validate_metadata
MAX_SIZE_DEFAULT = '128m'
class OHProject:
"""
Work with an Open Humans Project.
"""
def __init__(self, master... | nilq/baby-python | python |
# =============================================================================
#
# Copyright (c) Kitware, Inc.
# All rights reserved.
# See LICENSE.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even
# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.... | nilq/baby-python | python |
tri = [
[0, 75, 0],
[0, 95, 64, 0],
[0, 17, 47, 82, 0],
[0, 18, 35, 87, 10, 0],
[0, 20, 4, 82, 47, 65, 0],
[0, 19, 1, 23, 75, 3, 34, 0],
[0, 88, 2, 77, 73, 7, 63, 67, 0],
[0, 99, 65, 4, 28, 6, 16, 70, 92, 0],
[0, 41, 41, 26, 56, 83, 40, 80, 70, 33, 0],
[0, 41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0],
[0, 53, 71, 44, 65,... | nilq/baby-python | python |
from .model import (
set_db_path,
Model,
Field,
IntField,
DateTimeField,
StrField
)
| nilq/baby-python | python |
from typing import Union, Optional
import torch
from falkon.options import FalkonOptions
from falkon.sparse.sparse_tensor import SparseTensor
from falkon.utils import TicToc, decide_cuda
from falkon.la_helpers import mul_triang, copy_triang, trsm, vec_mul_triang
from falkon.utils.tensor_helpers import create_same_str... | nilq/baby-python | python |
from IPython import get_ipython
# %%
####################
# GRAPH GENERATION #
####################
# TODO: remove duplicate of nbIndividuals in viz
nbIndividuals = 1000 # number of people in the graph | nombre d'individus dans le graphe
initHealthy = 0.85 # proportion of healthy people at start | la proportion de per... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import time
import tempfile,random,string
from common.common import BaseService
import HTMLParser
import imgkit
from common import logger
class BaseBot(BaseService):
type = None
'''
给指定的群组和用户发消息
由于目前,很少给用户发消息,所以,没必要定一个send(user,message)接口
group: QQ群名称、QQ讨论群名称、微... | nilq/baby-python | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import datetime
from six import iteritems
import frappe
from frappe import _
from frappe.utils import flt, formatdate
from erpnext.controll... | nilq/baby-python | python |
import sys
import os
import re
import networkx as nx
import random
import numpy as np
from alias_table_sampling import AliasTable as at
class BatchStrategy(object):
# G is a DiGraph with edge weights
def __init__(self, G, num_new, mapp, rmapp, num_modify, params = None):
self.edges = []
probs_... | nilq/baby-python | python |
from django import forms
from .models import squirrel_data
class SquirreldataForm(forms.ModelForm):
'''
Class to handle ModelForms that are used in the Add Sighting form
'''
class Meta:
model = squirrel_data
fields = '__all__'
| nilq/baby-python | python |
import logging
import pandas as pd
from flask import request
from mlpiper.components.connectable_component import ConnectableComponent
from datarobot_drum.drum.common import LOGGER_NAME_PREFIX
from datarobot_drum.drum.exceptions import DrumCommonException
from datarobot_drum.profiler.stats_collector import StatsColl... | nilq/baby-python | python |
"""Adds config flow for NorwegianWeather."""
import logging
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.const import CONF_MONITORED_CONDITIONS
from homeassistant.helpers import config_vali... | nilq/baby-python | python |
count_weekday_years = survey_data.groupby([survey_data["eventDate"].dt.year, survey_data["eventDate"].dt.dayofweek]).size().unstack() | nilq/baby-python | python |
import os;
import bvpl_octree_batch
import multiprocessing
import Queue
import time
import random
import optparse
import sys
from numpy import log, ceil
from xml.etree.ElementTree import ElementTree
class dbvalue:
def __init__(self, index, type):
self.id = index # unsigned integer
self.type = type # ... | nilq/baby-python | python |
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from app.models import Question, Answer, Tag
CONFIRMATION = 'remove database'
class Command(BaseCommand):
help = 'Remove all data from the database'
requires_migrations_checks = True
def add_arguments(self, pa... | nilq/baby-python | python |
import numpy
from PIL import Image
def get_origin(canny_img):
image = canny_img.load()
pixels_x = []
pixels_y = []
for x in range(0, canny_img.size[0]):
for y in range(0, canny_img.size[1]):
if image[x,y] != 0:
pixels_x.append(x)
pixels_y.append(y)
... | nilq/baby-python | python |
"""A Python library for perturbation-based classifiers.
``Perturbation Classifier`` is a library containing the implementation of the Perturbation-based
Classifier (PerC) and subconcept Perturbation-based Classifier (sPerC).
Subpackages
-----------
subconcept
The implementation of subconcept Perturbation-based C... | nilq/baby-python | python |
import goprolib.HERO4.HERO4 as HERO4
import datetime
import time
def main(path='/media/xyoz/XYOZ-INT1000E/Pictures/2016_07_13 GoPro Auto'):
h4 = HERO4.HERO4()
h4.download_all(delete_after_download=True, path=path)
if __name__ == '__main__':
while True:
try:
main('/media/xyoz/XYOZ-INT1... | nilq/baby-python | python |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# 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 versio... | nilq/baby-python | python |
import re
import six
import ast
import json
import global_params
from utils import run_command
from ast_helper import AstHelper
class Source:
def __init__(self, filename):
self.filename = filename
self.content = self._load_content()
self.line_break_positions = self._load_line_break_positi... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import copy
from functools import partial
import math
import numpy as np
from pathlib import Path
import random
from typing import Callable, Dict, List, Tuple, Union
import torch
from torch.utils.data import Datase... | nilq/baby-python | python |
from django import template
register = template.Library()
@register.filter(name='get_vulnerable_endpoints')
def get_vulnerable_endpoints(endpoints):
return endpoints.filter(remediated=False)
@register.filter(name='get_remediated_endpoints')
def get_remediated_endpoints(endpoints):
return endpoints.filter(re... | nilq/baby-python | python |
class Node():
def __init__(self, key, data):
"""Create a new node
Arguments:
key {[type]} -- [description]
data {[type]} -- [description]
"""
self.key = key
self.data = data
self.next = None | nilq/baby-python | python |
if __name__ == '__main__':
# print("a")
# ord: characters -> ASCII code
# print(ord('a'))
# chr: ASCII code -> characters
# print(chr(97))
result = chr(ord('a') + 1)
print(result) | nilq/baby-python | python |
"""download and/or process data"""
import torch
import torch.nn as nn
import torchaudio
import pandas as pd
from sonopy import power_spec, mel_spec, mfcc_spec, filterbanks
class MFCC(nn.Module):
def __init__(self, sample_rate, fft_size=400, window_stride=(400, 200), num_filt=40, num_coeffs=40):
super(MFC... | nilq/baby-python | python |
from substance.monads import *
from substance.logs import *
from substance import (Engine, Command)
from substance.exceptions import (SubstanceError)
class Env(Command):
def getUsage(self):
return "substance engine env [ENGINE NAME]"
def getHelpTitle(self):
return "Print the shell variables ... | nilq/baby-python | python |
from PIL import Image
import math
import os
DATASET_PATH = 'A:/temp/temp'
output_path = 'image_resize/'
MAXIMUM_RESOLUTION = 1280*720
def img_resize(img, maximum_resolution):
img_width = img.width
img_height = img.height
img_definition = img_width * img_height
img_dpi = img.info['dpi']
if img_... | nilq/baby-python | python |
from kivy.uix.screenmanager import Screen
from kivy.properties import BooleanProperty, StringProperty
from kivy.event import EventDispatcher
from kivy.network.urlrequest import UrlRequest
from kivy.app import App
from kivy.lang import Builder
from kivy.factory import Factory
import sys
sys.path.append("/".join(x for x ... | nilq/baby-python | python |
"""A module that fails the tests"""
long_string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
def bad_function(a: int) -> int:
"""Return input + 2
Parameters
----------
a : int
input integer
Returns
-------
int
input + 2
"""
return a ... | nilq/baby-python | python |
TESTING=True
"""
TESTING=False IN CASE OF PRODUCTION
TESTING=True IN CASE OF TESTING
"""
from flask import (Flask, abort, jsonify, make_response, request)
from flask_sqlalchemy import SQLAlchemy
import secrets
import os
from __init__ import db, SECRET
from models import (NotReceived, User, #Product, Order, #Image,
d... | nilq/baby-python | python |
import pickle
import numpy as np
import torch
from torch import Tensor
from torch.utils.data import Dataset
import arguments as args
class CrepeDataset(Dataset):
def __init__(self,
data_path: str,
sample_len: int,
scaler,
device: str
... | nilq/baby-python | python |
def obter_dados_canal(lista):
for _ in range(lista):
nome,inscritos,monetizacao,ehpremium = input().split(';')
inscritos = int(inscritos)
monetizacao = float(monetizacao)
ehpremium = ehpremium == 'sim'
canais.append([nome, inscritos, monetizacao, ehpremium])
def calcular_bonificacao(valor... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR, TINYINT, TIMESTAMP
from webspider import constants
from webspider.models.base import BaseModel
class JobModel(BaseModel):
__tablename__ = 'job'
id = Column(INTEGER, nu... | nilq/baby-python | python |
"""
:date_created: 2021-11-18
"""
from do_py.abc import ABCRestrictions
from db_able.base_model.database_abc import Database
from db_able.client import DBClient
@ABCRestrictions.require('save_params')
class Savable(Database):
"""
This is a mixin designed to access DB with a standard method action, `save`.
... | nilq/baby-python | python |
from .orient import ImageOrienter
from recipes.dicts import pformat
class keep:
pass
class CalibrationImage:
"""Descriptor class for calibration images"""
# Orientation = ImageOrientBase
def __init__(self, name):
self.name = f'_{name}'
def __get__(self, instance, owner):
if in... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import math
import json
from tqdm import tqdm
from time import time
from datetime import datetime, timedelta
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
import matplotlib.pyplot as plt
import matplotlib.cm
from matplotlib.colors import ... | nilq/baby-python | python |
import random
from donphan.utils import not_creatable
from tests.utils import async_test
from donphan import Column, Table, SQLType
from unittest import TestCase
class _TestAlterColumnsTable(Table):
a: Column[SQLType.Text] = Column(primary_key=True)
class AlterColumnsTest(TestCase):
def test_query_drop_col... | nilq/baby-python | python |
import torch
class AutocastCPUTestLists(object):
# Supplies ops and arguments for test_autocast_* in test/test_cpu.py
def __init__(self, dev):
super().__init__()
n = 8
# Utility arguments, created as one-element tuples
pointwise0_bf16 = (torch.randn(n, dtype=torch.bfloat16, devi... | nilq/baby-python | python |
from __future__ import print_function
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import os
import glob
import skimage.io as io
import skimage.transform as trans
khong = [0,0,0]
vua = [0,0,128]
nang = [0,128,0]
ratnang = [128,128,0]
lut = [128,0,0]
COLOR_DICT = np.array([khong,vua,na... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# import general neural network model
from .dnn import NN
# import multilayer perceptron model
from .mlp import *
# import NEAT model
from .neat_model import NEATModel
# import convolutional neural network
from .cnn import *
# import recurrent neural network
from .rnn import *
# import aut... | nilq/baby-python | python |
import django_tables2 as tables
from nautobot.utilities.tables import (
BaseTable,
ButtonsColumn,
ToggleColumn,
)
from dummy_plugin.models import DummyModel
class DummyModelTable(BaseTable):
"""Table for list view of `DummyModel` objects."""
pk = ToggleColumn()
name = tables.LinkColumn()
... | nilq/baby-python | python |
from stonehenge import Application, Route, Router, run
from stonehenge.modules import DefaultModules
from stonehenge.admin import AdminRouter
from stonehenge.cms import CMSRouter
from blog import BlogModule
from handlers import home, about, portfolio, subpage, blog_handler, user_handler
class App(Application):
m... | nilq/baby-python | python |
import pytorch_lightning as pl
from pytorch_lightning import loggers
from l5kit.configs import load_config_data
from raster.lyft import LyftTrainerModule, LyftDataModule
from pathlib import Path
import argparse
import torch
from raster.utils import boolify
import pandas as pd
parser = argparse.ArgumentParser(descripti... | nilq/baby-python | python |
# Copyright (c) 2018 Steven R. Brandt
# Copyright (c) 2018 R. Tohid
#
# 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)
import phylanx
from phylanx import Phylanx
@Phylanx
def sumn():
n = 0
sum = 0
fo... | nilq/baby-python | python |
from django.apps import AppConfig
class ScannerappConfig(AppConfig):
name = 'scannerapp'
| nilq/baby-python | python |
"""
Developed by : Adem Boussetha
Email : ademboussetha@gmail.com
"""
import cv2
import datetime
import os
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_default.xml')
# Read the input image
#img = cv2.imread('test.png')
cap = cv2.VideoCapture(0)
print ("you're gonna be added to db face re... | nilq/baby-python | python |
"""
523. Continuous Subarray Sum
Given a list of non-negative numbers and a target integer k,
write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k,
that is, sums up to n*k where n is also an integer.
Example 1:
Input: [23, 2, 4, 6, 7], k=6
Output: ... | nilq/baby-python | python |
#!/usr/bin/env python3
import xmlrpc.client
import time
test1 = xmlrpc.client.ServerProxy('http://localhost:8081')
print(test1.system.listMethods())
test1.start_trial()
test1.turnLeft()
test1.turnRight()
test1.end_trial()
| nilq/baby-python | python |
class Solution:
def missingNumber(self, nums: [int]) -> int:
nums_set = set(nums)
for i in range(len(nums) + 1):
if i not in nums_set:
return i | nilq/baby-python | python |
#
# gemini_python
#
# recipe_system.reduction
# reduceActions.py
# -----------------------------------------------------------------------... | nilq/baby-python | python |
from fastapi import APIRouter
from fastapi import Depends, HTTPException, status
from fastapi.responses import ORJSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapidi import get_dependency
from app.modules.auth.depends import validate_jwt_token
from app.modules.auth.dtos.token import Toke... | nilq/baby-python | python |
"""
fasta - manipulations with FASTA databases
==========================================
FASTA is a simple file format for protein sequence databases. Please refer to
`the NCBI website <http://www.ncbi.nlm.nih.gov/blast/fasta.shtml>`_
for the most detailed information on the format.
Data manipulation
---------------... | nilq/baby-python | python |
from log import LOG
from .image import Image
from .digits import Digits
| nilq/baby-python | python |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82083609
class Solution(object):
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
B = set()
for a in A:
B.add(''.join(sorted(a[0::2])) + ''.join(sorted(a[1::2])))
... | nilq/baby-python | python |
# ======================================================================
# Dirac Dice
# Advent of Code 2021 Day 21 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ===============================... | nilq/baby-python | python |
from rest_framework import viewsets
from rest_framework.permissions import IsAdminUser
from src.apps.users.models import User
from src.apps.users.serializers import FullUserSerializer, LimitedUserSerializer
from src.contrib.permission import ReadOnly
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""rackio/managers/api.py
Thi module implements API Manager.
"""
import falcon
from falcon import api_helpers as helpers
from falcon_auth import FalconAuthMiddleware, TokenAuthBackend
from falcon_multipart.middleware import MultipartMiddleware
from falcon_cors import CORS
from ..api import Ta... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import sys
import json
import zipfile
import datetime
import shutil
from wearebeautiful import model_params as param
MAX_SCREENSHOT_SIZE = 256000 # 256Kb is enough!
bundles_json_file = "bundles.json"
def bundle_setup(bundle_dir_arg):
''' Make the bundle dir, in case it doesn't e... | nilq/baby-python | python |
from flask import render_template, flash, redirect, url_for, session, Markup
from flask_login import login_user, logout_user, login_required
from app import app, db, lm
from app.models.forms import *
from app.models.tables import *
@lm.user_loader
def load_user(id):
return Usuario.query.filter_by(id=id).first()
... | nilq/baby-python | python |
import logging
import paho.mqtt.client as mqtt
import time
# from utils_intern.messageLogger import MessageLogger
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__file__)
class MQTTClient:
def __init__(self, host, mqttPort, client_id... | nilq/baby-python | python |
from gym_trafficnetwork.envs.parallel_network import Cell
import numpy as np
# For the simplest road type
def homogeneous_road(num_cells, vfkph, cell_length, num_lanes):
r = []
for _ in range(num_cells):
r.append(Cell(vfkph, cell_length, num_lanes))
return r
# For roads who have cells with the number of lanes a... | nilq/baby-python | python |
import re
import typing as tp
from time import time
from loguru import logger
def time_execution(func: tp.Any) -> tp.Any:
"""This decorator shows the execution time of the function object passed"""
def wrap_func(*args: tp.Any, **kwargs: tp.Any) -> tp.Any:
t1 = time()
result = func(*args, **k... | nilq/baby-python | python |
import os
import time
import argparse
import numpy as np
import cv2
from datetime import datetime
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S
import nnabla.logger as logger
import nnabla.utils.save as save
from nnabla.monitor import Monitor, Moni... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: get_app_health_config_v2.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from go... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
import visa
import time
#-------------------------------------------------------------#
## main function
# @param there is no parameter for main function
def main():
rm = visa.ResourceManager()
print rm.list_resources()
instr1 = rm.open_resource('USB0::0x05E6::0x2280::410... | nilq/baby-python | python |
import os, time
from this import d
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta
from detector import detect_anomaly
from decomposition import load_STL_results, decompose_model
from models import *
from data_loade... | nilq/baby-python | python |
import datetime
import time
from open_publishing.core.enums import EventTarget, EventAction, EventType
class Events(object):
def __init__(self,
ctx):
self._ctx = ctx
def get(self,
references=None,
target=None,
action=None,
type=None,
... | nilq/baby-python | python |
def add(x, y):
return x + y
def double(x):
return x + x | nilq/baby-python | python |
import math
import datetime
block_size = 0.5
def block_name(lat, lon):
discretized_lat = (math.floor(lat/block_size)+0.5)*block_size
discretized_lon = (math.floor(lon/block_size)+0.5)*block_size
return (discretized_lat, discretized_lon)
def inside_polygon(x, y, points):
"""
Return True if a coord... | nilq/baby-python | python |
"""
Results represent Prefect Task inputs and outputs. In particular, anytime a Task runs, its output
is encapsulated in a `Result` object. This object retains information about what the data is, and how to "handle" it
if it needs to be saved / retrieved at a later time (for example, if this Task requests for its out... | nilq/baby-python | python |
import numpy
import pytest
from pauxy.systems.ueg import UEG
from pauxy.estimators.ueg import fock_ueg, local_energy_ueg
from pauxy.estimators.greens_function import gab
from pauxy.utils.testing import get_random_wavefunction
from pauxy.utils.misc import timeit
@pytest.mark.unit
def test_fock_build():
sys = UEG({'... | nilq/baby-python | python |
import subprocess
host = ["www.google.com", "192.0.0.25"]
rounds = 32
ping = subprocess.Popen(
["ping", "-c", str(rounds), host[1]],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print "Out : %s"%out
import re
matcher = re.compile("rtt min/avg/max/m... | nilq/baby-python | python |
#!/usr/bin/env python3
# This script is used to avoid issues with `xcopy.exe` under Windows Server 2016 (https://github.com/moby/moby/issues/38425)
import glob, os, shutil, sys
# If the destination is an existing directory then expand wildcards in the source
destination = sys.argv[2]
if os.path.isdir(destination) == T... | nilq/baby-python | python |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class TicketTests(APITestCase):
def setUp(self):
"""
Configurations to be made available before each
individual test case inheriting from this class.
"""
url = reve... | nilq/baby-python | python |
from interface import create_new_user
import unittest
from passlock import User,Credentials
class TestClass(unittest.TestCase):
'''
A Test class that defines test case for the user behaviour
'''
def setUp(self) :
'''
set up mehtod that runs each testcase
'''
self.new_us... | nilq/baby-python | python |
import unittest
import numpy as np
import theano
import theano.tensor as T
from daps.model import weigthed_binary_crossentropy
class test_loss_functions(unittest.TestCase):
def test_weigthed_binary_crossentropy(self):
w0_val, w1_val = 0.5, 1.0
x_val, y_val = np.random.rand(5, 3), np.random.randi... | nilq/baby-python | python |
''' Filters that operate on ImageStim inputs. '''
import numpy as np
from PIL import Image
from PIL import ImageFilter as PillowFilter
from pliers.stimuli.image import ImageStim
from .base import Filter
class ImageFilter(Filter):
''' Base class for all ImageFilters. '''
_input_type = ImageStim
class Ima... | nilq/baby-python | python |
#
# @lc app=leetcode.cn id=206 lang=python3
#
# [206] 反转链表
#
# https://leetcode-cn.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (58.01%)
# Total Accepted: 38.9K
# Total Submissions: 66.5K
# Testcase Example: '[1,2,3,4,5]'
#
# 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->N... | nilq/baby-python | python |
# encoding: utf-8
"""Test utility functions."""
from unittest import TestCase
import os
from viltolyckor.utils import parse_result_page
from requests.exceptions import HTTPError
DATA_DIR = "tests/data"
class TestUtils(TestCase):
def setUp(self):
pass
def test_parse_result_page(self):
file_p... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
*** Same as its parent apart that text baselines are reflected as a LineString (instead of its centroid)
DU task for ABP Table:
doing jointly row BIO and near horizontal cuts SIO
block2line edges do not cross another block.
The cut are based on baseli... | nilq/baby-python | python |
import pytest
from pybatfish.client.session import Session
from pybatfish.datamodel import PathConstraints, HeaderConstraints
from test_suite.sot_utils import (SoT, BLOCKED_PREFIXES, SNAPSHOT_NODES_SPEC, OPEN_CLIENT_PORTS)
@pytest.mark.network_independent
def test_no_forwarding_loops(bf: Session) -> None:
"""Ch... | nilq/baby-python | python |
"""Externalized strings for better structure and easier localization"""
setup_greeting = """Dwarf - First run configuration
Insert your bot's token, or enter 'cancel' to cancel the setup:"""
not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process."
choose_prefix = """Choose a prefix. A pref... | nilq/baby-python | python |
#coding=utf-8
from django.conf.urls import patterns, url, include
from cmdb.views import contract
urlpatterns = patterns('',
url(r'^$', contract.list_contract, name='contract_index'),
url(r'add/$', contract.add_contract, name='add_contract'),
url(r'del/(?P<contract_id>\d+)/$', contract.del_contract, na... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.