content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from django.contrib import admin from django.contrib.admin import register from bbbs.main.models import Main from bbbs.users.utils import AdminOnlyPermissionsMixin from .forms import MainAdminForm @register(Main) class MainAdmin(AdminOnlyPermissionsMixin, admin.ModelAdmin): empty_value_display = "-пу...
nilq/baby-python
python
""" uTorrent migration to qBittorrent module """ from tkinter import Tk, StringVar, N, W, E, S, filedialog, messagebox, HORIZONTAL from tkinter.ttk import Frame, Entry, Button, Label, Progressbar from shutil import copy from os import path from hashlib import sha1 from time import time from re import compile as ...
nilq/baby-python
python
#!/usr/bin/env python3 import argparse import logging import logging.config import os import sys import time import yaml from cluster_manager import setup_exporter_thread, \ manager_iteration_histogram, \ register_stack_trace_dump, \ update_file_modification_time sys.path.append( os.p...
nilq/baby-python
python
import itertools from numbers import Number from graphgallery.utils.type_check import is_iterable def repeat(src, length): if src is None: return [None for _ in range(length)] if src == [] or src == (): return [] if isinstance(src, (Number, str)): return list(itertools.repeat(src, l...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import unicode_literals import inspect import logging LOG = logging.getLogger(__name__) def is_generator(func): """Return True if `func` is a generator function.""" return inspect.isgeneratorfunction(func)
nilq/baby-python
python
#! /usr/bin/python # -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (C) 2012 by Xose Pérez # # 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, ei...
nilq/baby-python
python
def countPattern(genome, pattern): """ Find the number of specific pattern in a genome sequence """ count = 0 for index in range(0, len(genome)-len(pattern)+1): if genome[index:index+len(pattern)] == pattern: count += 1 return count def findPattern(genome, pattern): "...
nilq/baby-python
python
import logging import asyncio from ..Errors import * from ..utils import Url logger = logging.getLogger(__name__) class Commander: """ Manages looping through the group wall and checking for commands or messages Attributes ----------- prefix: :class:`str` The command prefix """ ...
nilq/baby-python
python
"""Class implementation for the scale_x_from_center interface. """ from typing import Dict from apysc._animation.animation_scale_x_from_center_interface import \ AnimationScaleXFromCenterInterface from apysc._type.attr_linking_interface import AttrLinkingInterface from apysc._type.number import Number fr...
nilq/baby-python
python
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.shell.lint.shfmt.rules import ShfmtFieldSet, ShfmtRequest from pants.backend.shell.lint.s...
nilq/baby-python
python
#!/usr/bin/env python __author__ = "Yaroslav Litvinov" __copyright__ = "Copyright 2016, Rackspace Inc." __email__ = "yaroslav.litvinov@rackspace.com" from os import system import psycopg2 import argparse import configparser from pymongo import DESCENDING from collections import namedtuple from datetime import datetim...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.urls import path,re_path from . import views app_name = 'ajunivel' urlpatterns = [ path('', views.index, name='index'), path('index.html', views.index, name='index'), path('index', views.index, name='index'), path('menu', views.menu, name='menu'), ]
nilq/baby-python
python
import os import socket from pathlib import Path class Config(object): """ Basic configuration, like socket default timeout, headers """ def __init__(self): super(Config, self).__init__() self.socket_timeout = 20 # set socket layer timeout as 20s socket.setdefaulttimeout(self.socket_timeout) # self.hea...
nilq/baby-python
python
from dataclasses import dataclass @dataclass class ModelException: pass
nilq/baby-python
python
import numpy as np from torchmeta.utils.data import Task, MetaDataset class Relu(MetaDataset): """ Parameters ---------- num_samples_per_task : int Number of examples per task. num_tasks : int (default: 2) Overall number of tasks to sample. noise_std : float, optional ...
nilq/baby-python
python
# flake8: noqa CLOUDWATCH_EMF_SCHEMA = { "properties": { "_aws": { "$id": "#/properties/_aws", "properties": { "CloudWatchMetrics": { "$id": "#/properties/_aws/properties/CloudWatchMetrics", "items": { "$...
nilq/baby-python
python
import torch from torchvision import transforms, datasets import numpy as np from PIL import Image from skimage.color import rgb2lab, rgb2gray, lab2rgb def count_params(model): ''' returns the number of trainable parameters in some model ''' return sum(p.numel() for p in model.parameters() if p.requir...
nilq/baby-python
python
from datetime import date ano = int (input ('Digite o ano de nascimento: ')) idade = date.today().year - ano if idade <= 9: print ('Sua idade {}, Até 9 anos: Mirim'.format(idade)) elif idade > 9 and idade <= 14: print ('Sua idade {}, Até 14 anos: Infantil'.format(idade)) elif idade > 14 and idade <= 19: pri...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ """ from flask import flash, redirect, url_for, render_template, request from sayhello import app, db from sayhello.forms import HelloForm from sayhello.models import Message @app.route('/', methods=['GET', 'POST']) def index(): """ # TODO 分页BUG未解决 """ form = HelloForm() ...
nilq/baby-python
python
from aws_google_auth import exit_if_unsupported_python try: from StringIO import StringIO except ImportError: from io import StringIO import unittest import sys import mock class TestPythonFailOnVersion(unittest.TestCase): @mock.patch('sys.stdout', new_callable=StringIO) def test_python26(self, moc...
nilq/baby-python
python
import json from django.contrib.auth import login, logout, authenticate from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import JsonResponse from django.shortcuts import render, redirect import re import loggi...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: variable Author: ken CreateDate: 5/21/2018 AD Description: ------------------------------------------------- """ __author__ = 'ken'
nilq/baby-python
python
import chess from .external_chess_player import ExternalChessPlayer MAX_RETRIES = 3 class ChessPlayer(object): def __init__(self, external_player): """ :param external_player: :type external_player: ExternalChessPlayer """ self.ext_player = external_player def end_ga...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt from matplotlib import rc from meanfield import MeanField def d_tanh(x): """Derivative of tanh.""" return 1. / np.cosh(x)**2 def simple_plot(x, y): plt.plot(x, y) plt.xlim(0.5, 3) plt.ylim(0, 0.25) plt.xlabel('$\sigma_\omega^2$', fontsize=1...
nilq/baby-python
python
from tests.conftest import JiraTestCase class PrioritiesTests(JiraTestCase): def test_priorities(self): priorities = self.jira.priorities() self.assertEqual(len(priorities), 5) def test_priority(self): priority = self.jira.priority("2") self.assertEqual(priority.id, "2") ...
nilq/baby-python
python
""" Please implement a `test` (e.g. pytest - this is up to you) for the method `compute_phenotype_similarity()` - The details are up to you - use whatever testing framework you prefer. """
nilq/baby-python
python
# Aula 10 - Desafio 31: Custo da viagem # Pedir a distancia de uma viagem em seguida: # se a viagem for até 200Km de distancia, o valor da passagem será de R$0,50 por Km rodado # se for maior que 200 Km, o valor sera de R$0,45 por Km rodado d = int(input('Informe a distancia em Km da sua viagem: ')) if d <= 200: ...
nilq/baby-python
python
import os,shutil from .ExtensibleFileObject import ExtensibleFileObject def file_list_dedup(file_list): new_list=list(set(file_list)) new_list.sort(key=file_list.index) return new_list def relpath(a,b): pass def check_vfile(func): pass def refresh_directory(path): if os.path.exists...
nilq/baby-python
python
import nuke t=nuke.menu("Nodes") u=t.addMenu("Pixelfudger", icon="PxF_Menu.png") t.addCommand( "Pixelfudger/PxF_Bandpass", "nuke.createNode('PxF_Bandpass')", icon="PxF_Bandpass.png" ) t.addCommand( "Pixelfudger/PxF_ChromaBlur", "nuke.createNode('PxF_ChromaBlur')", icon="PxF_ChromaBlur.png") t.addCommand( "Pixelfud...
nilq/baby-python
python
BOT_NAME = 'naver_movie' SPIDER_MODULES = ['naver_movie.spiders'] NEWSPIDER_MODULE = 'naver_movie.spiders' ROBOTSTXT_OBEY = False DOWNLOAD_DELAY = 2 COOKIES_ENABLED = True DEFAULT_REQUEST_HEADERS = { "Referer": "https://movie.naver.com/" } DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.useragent.U...
nilq/baby-python
python
import asyncio import uvloop from apscheduler.schedulers.asyncio import AsyncIOScheduler from scrapper import scrap asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) if __name__ == "__main__": scheduler = AsyncIOScheduler() scheduler.add_job(scrap, 'interval', seconds=5) scheduler.start() ...
nilq/baby-python
python
from ..classes import WorkflowAction class TestWorkflowAction(WorkflowAction): label = 'test workflow state action' def execute(self, context): context['workflow_instance']._workflow_state_action_executed = True
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair and Paul Rougieux. JRC biomass Project. Unit D1 Bioeconomy. """ # Built-in modules # import os # Third party modules # # First party modules # from autopaths import Path from autopaths.auto_paths import AutoPaths from autopaths...
nilq/baby-python
python
import numpy as np import interconnect import copy # # VARIABLES N = 3001 # max clock cycles +1 FW = 16 # flit width FPP = 32 # flits per packet def get_header(FW=16): ''' generates a random header for a flit-width of FW) ''' return np.random.random_integers(0, (1 << FW)-1) # data, day = np.loa...
nilq/baby-python
python
from py_db import db import NSBL_helpers as helper # Re-computes the team hitting tables db = db('NSBL') def process(): print "processed_team_hitting" db.query("TRUNCATE TABLE `processed_team_hitting_basic`") db.query("TRUNCATE TABLE `processed_team_hitting_advanced`") yr_min, yr_max = db.query("...
nilq/baby-python
python
""" The MIT License (MIT) Copyright (c) 2020-Current Skelmis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
nilq/baby-python
python
# -*- coding: utf-8 -*- try: import mdp use_mdp = True except ImportError: print 'mdp (modular data processing) module not installed. Cannot do PCA' use_mdp = False import numpy as np from neuropype import node from itertools import imap, repeat from copy import deepcopy, copy from neuropype import par...
nilq/baby-python
python
import json import codecs import tldextract urls = dict() duplicates = list() with codecs.open('/home/rkapoor/Documents/ISI/data/Network/intersecting-urls.jsonl', 'r', 'utf-8') as f: for line in f: doc = json.loads(line) url = doc['url'] if url in urls: urls[url] += 1 el...
nilq/baby-python
python
import subprocess from uuid import uuid1 import yaml from jinja2 import Environment, PackageLoader from sanetrain.workflow_builder import generate_training def test_generate_training(): env = Environment(loader=PackageLoader('sanetrain', 'templates')) template = env.get_template('test_template.py') wit...
nilq/baby-python
python
#!/usr/bin/python import time fact_arr = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] class memoize: def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args): try: return self.memoized[args[0]] except KeyError: ...
nilq/baby-python
python
#! /usr/bin/env python def condense(w): return w[0] + str(len(w)-2) + w[-1:] def expand(w): length = int(w[1:-1]) + 2 for word in get_words(length): if word.startswith(w[0]) and word.endswith(w[-1:]): print word def get_words(length, filename = '/usr/share/dict/words'): return (wor...
nilq/baby-python
python
# # # Use: genKey(5) # => "xmckl" # # import math, random def genKey(n): alphabet = list("abcdefghijklmnopqrstuvwxyz") out = "" for i in range(n): out += alphabet[math.floor(random.randint(0, 25))] return out
nilq/baby-python
python
linha1 = input().split(" ") linha2 = input().split(" ") cod1, qtde1, valor1 = linha1 cod2, qtde2, valor2 = linha2 total = (int(qtde1) * float(valor1)) + (int(qtde2) * float(valor2)) print("VALOR A PAGAR: R$ %0.2f" %total)
nilq/baby-python
python
# https://github.com/dannysteenman/aws-toolbox # # License: MIT # # This script will set a CloudWatch Logs Retention Policy to x number of days for all log groups in the region that you exported in your cli. import argparse import boto3 cloudwatch = boto3.client("logs") def get_cloudwatch_log_groups(): kwargs...
nilq/baby-python
python
from backend.util.crypto_hash import crypto_hash HEX_TO_BINARY_CONVERSION_TABLE ={ '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', ...
nilq/baby-python
python
import numpy as np from numpy.linalg import inv, cholesky from scipy.stats import norm, rankdata from synthpop.method import NormMethod, smooth class NormRankMethod(NormMethod): # Adapted from norm by carrying out regression on Z scores from ranks # predicting new Z scores and then transforming back def ...
nilq/baby-python
python
from caty.core.spectypes import UNDEFINED from caty.core.facility import Facility, AccessManager class MongoHandlerBase(Facility): am = AccessManager()
nilq/baby-python
python
nome=input('digite seu nome completo =') nomeup=nome.upper() nomelo=nome.lower() nomese=nome.strip() dividido=nome.split() print('em maiusculas = {}'.format(nomeup.strip())) print('em minusculas = {}'.format(nomelo.strip())) print('o seu nome tem {} letras'.format(len(nomese)-nomese.count(' '))) print('o seu primeiro n...
nilq/baby-python
python
from flask import render_template, request from sqlalchemy import desc from app.proto import bp from app.models import Share @bp.route('/', methods=['GET', 'POST']) @bp.route('/index', methods=['GET', 'POST']) def index(): user_id = request.args.get('user_id') shares = Share.query.filter_by(user_id=user_id).o...
nilq/baby-python
python
import ProblemFileHandler as handler import OJTemplate # 生成一个题目文件 # 第一种方法:problem_text_file + test_cases_file text_file1 = '../resources/OJ/demo_problem1_text.txt' test_cases_file1 = '../resources/OJ/demo_problem1_test_cases.txt' output_file1 = '../resources/OJ/Problems/Problem1.plm' handler.generate_problem(p...
nilq/baby-python
python
import random import os import time import server import discord import ctypes import server from discord.ext import commands from cogs.musiccog import Music from cogs.funcog import Fun find_opus = ctypes.util.find_library('opus') discord.opus.load_opus(find_opus) TOKEN = os.getenv("DISCORD_TOKEN") # Silence useless...
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch.nn as nn from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer from maskrcnn_benchmark.layers.non_local import init_nl_module from .generalized_rcnn import GeneralizedRCNN import torch from maskrcnn_benchmark.layers i...
nilq/baby-python
python
# Copyright 2017 ForgeFlow S.L. # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountPaymentMode(models.Model): _inherit = "ac...
nilq/baby-python
python
''' FUNCTIONS Functions are pieces(block) of code that does something. '''
nilq/baby-python
python
from classifiers.base_stance_classifier import BaseStanceClassifier from classifiers.random_stance_classifier import RandomStanceClassifier from classifiers.greedy_stance_classifier import MSTStanceClassifier from classifiers.maxcut_stance_classifier import MaxcutStanceClassifier
nilq/baby-python
python
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # import threading import time from opentelemetry.context import attach, detach, set_value from opentelemetry.sdk.metrics import Meter from opentelemetry.sdk.metrics.export import MetricsExportResult from azure_monitor.sdk.a...
nilq/baby-python
python
from art import logo import os clear = lambda: os. system('cls') def new_bidder(): global greater_bid bidder = input("What's your name?: ") bid = int(input("What's your bid?: ")) new_bidder_dict = {"Bidder": bidder, "Bid": bid} if bid > greater_bid["Bid"]: greater_bid = new_bidder_dict ...
nilq/baby-python
python
from geocoder import main from geocoder import STARTTIME, NUM_DOCS import re import os from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer from datetime import datetime #for testing time of script execution RE_URLS = 'http[s]?:\/\/(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+' RE_AT_M...
nilq/baby-python
python
#Making List l l = [11, 12, 13, 14] #Using append function on list l.append(50) l.append(60) print("list after adding 50 & 60:- ", l) #Using remove function on list l.remove(11) l.remove(13) print("list after removing 11 & 13:- ", l) #Using the sort function with their parameters changed #Implementing sorting in a...
nilq/baby-python
python
budget_wanted = float(input()) total = 0 money_full = False command = input() while command != "Party!": drink_name = command number_of_drinks = int(input()) price = int(len(drink_name)) drinks_price = price * number_of_drinks if drinks_price % 2 == 1: drinks_price -= drinks_price * 25 / ...
nilq/baby-python
python
#!/usr/bin/env python # coding:utf-8 #DESCRICAO #Esse script foi desenvolvido para facilitar a forma como cadastramos, #alteramos ou excluímos os principais ativos em dois ou mais servidores zabbix. #A ideia é utilizar esse script para ambientes onde os eventos não estão sincronizados, #permitindo uma ótima facilida...
nilq/baby-python
python
# ToggleButton examples. import os from ocempgui.widgets import * from ocempgui.widgets.Constants import * def _create_vframe (text): frame = VFrame (Label (text)) frame.spacing = 5 frame.align = ALIGN_LEFT return frame def create_button_view (): states = ("STATE_NORMAL", "STATE_ENTERED", "STATE_A...
nilq/baby-python
python
from sys import stdin def print_karte(karte): for i in range(len(karte)): liste = [str(x) for x in karte[i]] print(''.join(liste)) zeilen = [] max_x = 0 max_y = 0 for line in stdin: eingabe = line.strip() eingabe = eingabe.split(" ") eins = [int(x) for x in eingabe[0].split(",")] zw...
nilq/baby-python
python
from django.apps import apps from .models import State, Workflow def create_builtin_workflows(sender, **kwargs): """ Receiver function to create a simple and a complex workflow. It is connected to the signal django.db.models.signals.post_migrate during app loading. """ if Workflow.objects.exi...
nilq/baby-python
python
import os from codecs import open from setuptools import setup import suit_rq here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) set...
nilq/baby-python
python
import os import wget ## Verify if directory exists. Create if it doesnt exist. def check_dir(file_path): directory = os.path.dirname(file_path) if not os.path.exists(directory): os.makedirs(directory) ## Download source Files from urls def download_files(urls, out_path='downloads/', silent=False): for url ...
nilq/baby-python
python
"""Morse code handling""" from configparser import ConfigParser import os from pathlib import Path import sys import warnings import numpy as np import sklearn.cluster import sklearn.exceptions from .io import read_wave from .processing import smoothed_power, squared_signal class MorseCode: """Morse code ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from sklearn.preprocessing import StandardScaler X = [[0, 15], [1, -10]] # scale data according to computed scaling values print(StandardScaler().fit(X).transform(X))
nilq/baby-python
python
#!/usr/bin/env python3 #Author: Stefan Toman if __name__ == '__main__': print("Hello, World!")
nilq/baby-python
python
from l_00_inventory import inventory import json with open("m02_files/l_00_inventory.json", "w") as json_out: json_out.write(json.dumps(inventory)) with open("m02_files/l_00_inventory.json", "r") as json_in: json_inventory = json_in.read() print("l_00_inventory.json file:", json_inventory) print("\njson pre...
nilq/baby-python
python
import datetime import time as samay try: from pac import voice_io except ModuleNotFoundError: import voice_io def date(): x = datetime.datetime.now().strftime("%d/%m/%Y") voice_io.show(f"Today's date is {x} (DD/MM/YYYY)") def time(): #x=datetime.datetime.now().strftime("%H:%M:%S") loca...
nilq/baby-python
python
from settings import settings from office365.graph.graph_client import GraphClient def get_token_for_user(auth_ctx): """ Acquire token via user credentials :type auth_ctx: adal.AuthenticationContext """ token = auth_ctx.acquire_token_with_username_password( 'https://graph.microsoft.com',...
nilq/baby-python
python
import os import pytest import responses from ewhs.client import EwhsClient @pytest.fixture(scope="function") def client(): client = EwhsClient("test", "testpassword", "9fc05c82-0552-4ca5-b588-c64d77f117a9", "ewhs") return client @pytest.fixture(scope="session") def authenticated_client(): client = Ewhs...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ chanjo.cli ~~~~~~~~~~~ Command line interface (console entry points). Based on Click_. .. _Click: http://click.pocoo.org/ """ from __future__ import absolute_import, unicode_literals from pkg_resources import iter_entry_points import click from . import __version__ from ._compat import t...
nilq/baby-python
python
# coding: utf-8 # # Copyright 2019 The Oppia 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 requi...
nilq/baby-python
python
from random import SystemRandom import pytest from cacheout import LFUCache parametrize = pytest.mark.parametrize random = SystemRandom() @pytest.fixture def cache(): _cache = LFUCache(maxsize=5) return _cache def assert_keys_evicted_in_order(cache, keys): """Assert that cache keys are evicted in th...
nilq/baby-python
python
pessoaslist = [] dicionario = {} pessoastotal = 0 soma = media = 0 mulheres = [] acimamedia = [] while True: dicionario['Nome'] = str(input("Nome: ")) dicionario['Sexo'] = str(input("Sexo: [M/F] ")) dicionario['Idade'] = int(input("Idade: ")) resp = str(input("Continuar?: [S/N]")) pessoaslist.appe...
nilq/baby-python
python
from ..utils import Object class MessageSchedulingStateSendAtDate(Object): """ The message will be sent at the specified date Attributes: ID (:obj:`str`): ``MessageSchedulingStateSendAtDate`` Args: send_date (:obj:`int`): Date the message will be sentThe date must be w...
nilq/baby-python
python
'''Desarrollar un programa que cargue los datos de un triángulo. Implementar una clase con los métodos para inicializar los atributos, imprimir el valor del lado con un tamaño mayor y el tipo de triángulo que es (equilátero, isósceles o escaleno).''' import os class Triangulo(): def __init__(self, lado1, lado2...
nilq/baby-python
python
import ldap import pandas import datetime.datetime from ldap_paged_search import LdapPagedSearch host = 'ldaps://example.com:636' username = 'domain\\username' password = 'password' baseDN = 'DC=example,DC=com' filter = "(&(objectCategory=computer))" #attributes = ['dn'] attributes = ['*'] #ldap.set_option(ldap.OPT_...
nilq/baby-python
python
"""Custom pandas accessors.""" import numpy as np import plotly.graph_objects as go from vectorbt import defaults from vectorbt.root_accessors import register_dataframe_accessor from vectorbt.utils import checks from vectorbt.utils.widgets import CustomFigureWidget from vectorbt.generic.accessors import Generic_DFAcc...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: npu_utilization.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 google.prot...
nilq/baby-python
python
#!/usr/bin/env python import fire from lib.dsv.commands.dsv_command import DSVCommand if __name__ == '__main__': fire.Fire(DSVCommand)
nilq/baby-python
python
import predpy from predpy.predpy import * #from predpy.predpy import predpy from predpy.predpy import cleandata from predpy.predpy import galgraphs
nilq/baby-python
python
# # Copyright 2020 Logical Clocks 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 ag...
nilq/baby-python
python
from rest_framework import serializers from rest_framework.reverse import reverse from onadata.apps.fsforms.models import FieldSightXF from onadata.apps.logger.models import XForm from onadata.libs.utils.decorators import check_obj class XFormListSerializer(serializers.ModelSerializer): class Meta: mode...
nilq/baby-python
python
import numpy as np from torch import nn, tensor import torch from torch.autograd import Variable class time_loss(nn.Module): def __init__(self, margin=0.1, dist_type = 'l2'): super(time_loss, self).__init__() self.margin = margin self.dist_type = dist_type if dist_type == 'l2': self.dist = nn.MS...
nilq/baby-python
python
from types import FunctionType import pygame from pygame.locals import * from pygame.font import Font from pygameMenuPro.event import Event COLOR_BLACK = Color(0, 0, 0) COLOR_WHITE = Color(255, 255, 255) class InputManager: def __init__(self): self.last_checked_input = [] self.last_mouse_positio...
nilq/baby-python
python
# Define player object class Player: def __init__(self, name, house): self.name = name self.house = house self.hasNumber = False # Method for setting users phonenumbers def setPhonenumber(self, phoneNumber): self.phoneNumber = phoneNumber self.hasNumber = True # 12...
nilq/baby-python
python
# =============================================================================== # Copyright 2020-2021 Intel Corporation # # 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.ap...
nilq/baby-python
python
from data.station_number_data import StationNumberData from states_machine.state_context import State from states_machine.states.on_which_sum import OnWhichSum class StationNumber(State): def __init__(self): pass def income_handle(self) -> None: # TODO: # print(f"income_handl...
nilq/baby-python
python
class Transformer: def transform(self, message): yield from map(self.map, (message,)) def map(self, message): raise NotImplementedError('Transformer is an abstract class.')
nilq/baby-python
python
import socket import struct from struct import * import sys def ethernet_head(raw_data): dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14]) dest_mac = get_mac_addr(dest) src_mac = get_mac_addr(src) proto = socket.htons(prototype) data = raw_data[14:] return dest_mac, src_mac, pro...
nilq/baby-python
python
import unittest import random import numpy as np import pyquil from cirq import GridQubit, LineQubit, X, Y, Z, PauliSum, PauliString from openfermion import ( QubitOperator, IsingOperator, FermionOperator, get_interaction_operator, get_fermion_operator, jordan_wigner, qubit_operator_sparse,...
nilq/baby-python
python
"""UseCase for updating a metric entry's properties.""" import logging from argparse import Namespace, ArgumentParser from typing import Final, Optional import jupiter.command.command as command from jupiter.domain.adate import ADate from jupiter.use_cases.metrics.entry.update import MetricEntryUpdateUseCase from jup...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ USD Opinion Editor widget implementations """ from __future__ import print_function, division, absolute_import __author__ = "Tomas Poveda" __license__ = "MIT" __maintainer__ = "Tomas Poveda" __email__ = "tpovedatd@gmail.com" from Qt.QtCore import * from Qt.QtWidgets...
nilq/baby-python
python
# 000 # 999 # a=['one','two','three','four'] b=range(5) c=(9,-1,2) #one 0 9 #... #four 4 2 S = [4,5,3] def next_value(current, S): "[0,0,0] -> next one [1,0,0]" N = current[:] i = 0 N[i] += 1 while N[i]==S[i]: N[i] = 0 i += 1 if i==len(N): break N[i]...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # This file is part of the pyfixp project hosted at https://github.com/chipmuenk/pyfixp # # Copyright © Christian Muenker # Licensed under the terms of the MIT License # (see file LICENSE.txt in root directory for details) """ Store the version number here for setup.py and pyfixp.py """ __ve...
nilq/baby-python
python
class Card(): def __init__(self, id: int, img: str, owner, position: int): """ Card defines a card. Args: id (int): card id (incremental int) img (str): path of the card img owner (int): card owner player, or None if in the deck/used position (int): when it is played, the position to vote removed...
nilq/baby-python
python
from django.urls import path from .views import ( RideListView, RideDetailView, RideCreateView, RideUpdateView, RideDeleteView, OwnerRideListView, ShareCreateView, SharePickRideListView, ShareRideListView, ...
nilq/baby-python
python