content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import graphene
from .models import Media
from .service import MediaService
service = MediaService()
class MediaType(graphene.ObjectType):
'''
Media Type,
represents a GraphQL version of a media entity
'''
id = graphene.ID(required=True)
mime = graphene.String(required=True)
data ... | nilq/baby-python | python |
'''
This is Main class of RFCN Model
Contain the model's framework and call the backbone
'''
from KerasRFCN.Model.ResNet import ResNet
from KerasRFCN.Model.ResNet_dilated import ResNet_dilated
from KerasRFCN.Model.BaseModel import BaseModel
import KerasRFCN.Utils
import KerasRFCN.Losses
import keras.layers as KL
impo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Utilities for interacting with data and the schema."""
import json
import logging
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from typing import Dict, Mapping, Set, Union
from .constants import (
BIOREGISTRY_PATH,
COLLECTIONS_PATH,
... | nilq/baby-python | python |
from dataclasses import dataclass
from time import time
from typing import Union, Tuple
import psycopg2
from loguru import logger
from pony.orm import Database, Required, PrimaryKey, db_session
@dataclass()
class GetQuery:
mol_smi: str
search_type: str
fp_type: Union[bool, str] = False
sort_by_simila... | nilq/baby-python | python |
from substrateinterface import SubstrateInterface
import os
from utils import get_project_root_dir
# execution environment (for testing) --------------
main_script = os.path.join(get_project_root_dir(), "StakingManager.py")
# to get your python env, execute "which python" in CLI with env activated
# E.g. for anaconda ... | nilq/baby-python | python |
from aurora.amun.client.session import AmunSession
def main():
# Calling with no token in constructor will load one from an environment variable if provided
# or a file in HOME/.
session = AmunSession()
print("Getting Valuations")
valuations = session.get_valuations()
numToShow = 5
print... | nilq/baby-python | python |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch import Tensor
from models.convolutional_rnn import Conv2dLSTM
class RNNEncoder(nn.Module):
def __init__(self, num_layers: int = 2, hidden_size: int = 512, action__chn: int = 64, speed_chn: int = 64):
super(R... | nilq/baby-python | python |
# from .helpers.utils_ import *
# from .helpers.math_ import MathClass
# from .helpers.mm import MatrixMadness
from .main import *
| nilq/baby-python | python |
from __future__ import print_function
from __future__ import absolute_import
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
MSGS = {
'E1113': ('Import inside a function from shining is not allowed',
... | nilq/baby-python | python |
from selenium import webdriver
class Application:
def __init__(self):
self.wd = webdriver.Chrome(executable_path="C:\\chromedriver_win32\\chromedriver.exe")
self.wd.implicitly_wait(60)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/addressbook/grou... | nilq/baby-python | python |
"""protected and listed fields on Location
Revision ID: f8c342997aab
Revises: 5df6df91a533
Create Date: 2021-02-02 11:10:09.250494
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f8c342997aab'
down_revision = '5df6df91a533'
branch_labels = None
depends_on = No... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from click_captcha import ClickCaptcha
import fire
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
sys.stdout.write("Your content....")
def main(app_name, count=300, enable_dummy_word=False, font_path="extend/msyh.ttf", word_list_file_path... | nilq/baby-python | python |
from __future__ import absolute_import, print_function, unicode_literals
import sys
import binascii
import base64
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.authentication import CallbackAuthenticationPolicy, \
AuthTktAuthenticationPolicy
from py... | nilq/baby-python | python |
import indicators.indicator_settings as indicator_settings
settings = indicator_settings.global_settings['VAR_LB']
table_name = "VAR_LB"
for i in list(settings.keys()):
table_name += "_" + str(settings[i])
settings.update(
{
'db_path' : indicator_settings.indicators_root_path + "/var_lb/var_lb_db.sqlit... | nilq/baby-python | python |
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
from mymain import AAS
def main():
win = Tk()
app = Login_Window(win)
win.mainloop()
class Login_Window:
def __init__(self, root):
self.root = root
self.... | nilq/baby-python | python |
import pytest
from tests.compiler import compile_base
from thinglang.compiler.errors import SelfInStaticMethod
SELF_USE_IN_STATIC_METHOD = '''
thing Program
has number n1
static does something
{}
'''
def test_direct_self_use_in_static_function():
with pytest.raises(SelfInStaticMet... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import struct
SIZE = "I"
SIZEB = "B"
def stringToByteList(txt):
byteList = list()
for to in range(0, len(txt), 8):
byteList.append(int(txt[to:to + 8], 2))
return byteList
def byteListToString(byteList):
txt = ""
for element in byteList:
txt = txt + bin(ele... | nilq/baby-python | python |
#!/usr/bin/env python
# Import stuff for compatibility between python 2 and 3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
from future import standard_library
import os
import numpy as n... | nilq/baby-python | python |
from selenium import webdriver
from training_ground_page import TrainingGroundPage
from trial_page import TrialPage
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# Test Setup
... | nilq/baby-python | python |
import re
import subprocess
def read_model_list():
with open('latest_model_list.txt') as f:
return f.readlines()
records = read_model_list()
for record in records:
temp = re.search('test[0-9]+', record)
temp = temp.group(0)
temp = re.search('[0-9]+', temp)
test_map = temp.group(0)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2016 CERN.
#
# B2Share is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | nilq/baby-python | python |
"""Apps module for the orp_api app."""
# Third Party
from django.apps import AppConfig
class OrpApiConfig(AppConfig):
"""Configuration for application."""
default_auto_field = 'django.db.models.BigAutoField'
name = 'orp_apps.orp_api'
| nilq/baby-python | python |
# coding: utf-8
"""
Intersight REST API
This is Intersight REST API
OpenAPI spec version: 1.0.9-255
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class BiosPolicy(object):
"""
NOTE: This class is a... | nilq/baby-python | python |
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union
from vkbottle import ABCView, BaseReturnManager
from vkbottle.dispatch.handlers import FromFuncHandler
from vkbottle.framework.bot import BotLabeler
from vkbottle.modules import logger
from vkbottle_types.events import MessageEvent as _... | nilq/baby-python | python |
from sympl import (
PlotFunctionMonitor, AdamsBashforth, NetCDFMonitor
)
from climt import SimplePhysics, get_default_state
import numpy as np
from datetime import timedelta
from climt import EmanuelConvection, RRTMGShortwave, RRTMGLongwave, SlabSurface
import matplotlib.pyplot as plt
def plot_function(fig, stat... | nilq/baby-python | python |
from threading import Thread
from .data_writer import DataWriter, DataWriterException, PlayerList
from pathlib import Path
from PIL import Image
class ScoredImageWriterException(DataWriterException):
pass
class WriteThread(Thread):
def __init__(self, scored_player_list: PlayerList,
save_dir... | nilq/baby-python | python |
import numpy as np
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtWidgets import *
from xicam.core import msg
from xicam.core.data import load_header, NonDBHeader
from xicam.plugins import GUIPlugin, GUILayout, manager as pluginmanager
import pyqtgraph as pg
from functools import partial
from xicam.gu... | nilq/baby-python | python |
from pathlib import Path
from slugify import slugify
from watchdog.events import RegexMatchingEventHandler
from kart.miners import DefaultMarkdownMiner
from kart.utils import KartDict
try:
from yaml import CSafeLoader as YamlLoader
except ImportError:
from yaml import SafeLoader as YamlLoader
import importl... | nilq/baby-python | python |
from flask import session
session['var']='oi'
app.run()
app.secret_key = 'minha chave' (vai no main, tem q fazer isso antes de dar app.run)
#lista de funcionarios no depto
#objeto de depto no funcionario
#inserir admin no formulario (criar um admin padrao com TRUE ja)
#listar projetos > ver detalhes do projeto > (li... | nilq/baby-python | python |
from chalice import Chalice
import requests as rq
import boto3
import os
import json
from datetime import date, timedelta
NYCOD = os.environ.get('NYCOPENDATA', None)
BUCKET, KEY = 'philipp-packt', '311data'
resource = 'fhrw-4uyv'
time_col = 'Created Date'
def _upload_json(obj, filename, bucket, key):
S3 = boto3.c... | nilq/baby-python | python |
from django.shortcuts import render, get_object_or_404
from django.views.generic import (DetailView, UpdateView)
from django.contrib.auth.mixins import (LoginRequiredMixin,
PermissionRequiredMixin)
from .models import Company
class CompanyDetailView(LoginRequiredMixin, DetailView):
"""Detalle de una empresa... | nilq/baby-python | python |
import numpy as np
from skimage._shared import testing
from skimage._shared.testing import assert_equal
from skimage.util._label import label_points
def test_label_points_coords_dimension():
coords, output_shape = np.array([[1, 2], [3, 4]]), (5, 5, 2)
with testing.raises(ValueError):
label_points(co... | nilq/baby-python | python |
from mirage.libs import mosart,utils,io
from mirage.libs.common.hid import HIDMapping
from mirage.core import module
class mosart_keylogger(module.WirelessModule):
def init(self):
self.technology = "mosart"
self.type = "attack"
self.description = "Keystrokes logger module for Mosart keyboard"
self.args = {
... | nilq/baby-python | python |
import torch
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import transforms
# Set up the matplotlib figure
f, axes = plt.subplots(1, 2, figsize=(7, 7), sharex=True)
# Generate a random univariate dataset
img_data = Image.open("../data/Test/Snow100K-L/synthetic/beautiful_smile_00003.jpg").co... | nilq/baby-python | python |
#!/usr/bin/env python3
from olctools.accessoryFunctions.accessoryFunctions import combinetargets, filer, GenObject, MetadataObject, \
make_path, run_subprocess, write_to_logfile
from olctools.accessoryFunctions.metadataprinter import MetadataPrinter
from genemethods.typingclasses.resistance import ResistanceNotes
f... | nilq/baby-python | python |
'''
MIT License
Copyright (c) 2020 Georg Thurner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,... | nilq/baby-python | python |
import subprocess
import re
def subprocess_runner(cmd_list, exercise_dir):
with subprocess.Popen(
cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exercise_dir
) as proc:
std_out, std_err = proc.communicate()
return (std_out.decode(), std_err.decode(), proc.returncode)
def r... | nilq/baby-python | python |
import os
import time
import math
from tkinter import *
import tkinter.ttk as ttk
from ClientEdit import *
from ClientInsert import *
from ClientView import *
class ClientList(Tk):
def label_combo(self, text, frame=None):
if frame == None:
frame = self.__frame_border
frame = Frame(fra... | nilq/baby-python | python |
# coding=utf-8
from django.test import TestCase
from django.test.utils import override_settings
class SlugFieldTest(TestCase):
def test_slugfield_allow_unicode_kwargs_precedence(self):
from wshop.models.fields.slugfield import SlugField
with override_settings(WSHOP_SLUG_ALLOW_UNICODE=True):
... | nilq/baby-python | python |
#!/usr/bin/env python
"""Use to reset pose of model for simulation."""
import rospy
from gazebo_msgs.msg import ModelState
def set_object(name, pos, ori):
msg = ModelState()
msg.model_name = name
msg.pose.position.x = pos[0]
msg.pose.position.y = pos[1]
msg.pose.position.z = pos[2]
msg.pose.... | nilq/baby-python | python |
# pylint: disable=W0212
# type: ignore
"""深度封装Action方法
函数只能在群消息和好友消息接收函数中调用
"""
import sys
from .action import Action
from .collection import MsgTypes
from .exceptions import InvalidContextError
from .model import FriendMsg, GroupMsg
from .utils import file_to_base64
def Text(text: str, at=False):
"""发送文字
:p... | nilq/baby-python | python |
# coding:utf-8
# --author-- binglu.wang
import zfused_api
import zfused_maya.core.record as record
def get_assets():
_assets = {}
_project_id = record.current_project_id()
_project_assets = zfused_api.asset.project_assets([_project_id])
# print _project_assets
for _asset in _project_assets:
... | nilq/baby-python | python |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
filetext = ifile.read()
data = [chunk for chunk in filetext.strip().split("\n\n")]
from typing import Tuple
IntervalPair = Tuple[int, int, int, int]
def parse_rule(line: str) -> Tuple[str, IntervalPair]:
field, right = line.split... | nilq/baby-python | python |
from __future__ import print_function, with_statement, absolute_import
import shutil
import torch
import logging
import os
from warnings import warn
from ..version import __version__
from .deployer_utils import save_python_function
logger = logging.getLogger(__name__)
def create_pytorch_endpoint(clipper_conn,
... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-02-09 19:59
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DJIAIndexComposition',
fields=[
('id', mode... | nilq/baby-python | python |
import glob
import os
from Bio import SeqIO
from Bio.Seq import Seq
output_dir_merge = '/scratch/users/anniz44/genomes/donor_species/vcf_round2/merge/details'
genus_cutoff = 3 # >= 3 genera as core
allgenome = output_dir_merge + '/summary/all.genome.gene.faa'
allgenome_denovo = output_dir_merge + '/summary/all.denovo.... | nilq/baby-python | python |
from __future__ import print_function
import numpy as np
from scipy.sparse.linalg import gmres
import scipy.sparse.linalg as spla
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import os
import argparse
from tqdm import tqdm
cla... | nilq/baby-python | python |
import cv2
import numpy as np
from util import *
from copy import deepcopy
def get_horizontal_lines (img):
#=====[ Step 1: set parameters ]=====
num_peaks = 5
theta_buckets_horz = [-90, -89]
theta_resolution_horz = 0.0175 #raidans
rho_resolution_horz = 6
threshold_horz = 5
#=====[ Step 2: find lines in (rho, ... | nilq/baby-python | python |
from . import VEXObject
class IRStmt(VEXObject):
"""
IR statements in VEX represents operations with side-effects.
"""
__slots__ = ['arch', 'tag']
def __init__(self, c_stmt, irsb):
VEXObject.__init__(self)
self.arch = irsb.arch
# self.c_stmt = c_stmt
self.tag = in... | nilq/baby-python | python |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | nilq/baby-python | python |
# this is a python script because handling Ctrl+C interrupts in batch
# scripts seems to be impossible
#
# This should always run in the same python that Porcupine uses.
from __future__ import annotations
import subprocess
import sys
import colorama
colorama.init()
prog, directory, command = sys.argv
print(colorama... | nilq/baby-python | python |
import io
import os
import urllib
import boto3
import botocore
import shutil
import subprocess
import tempfile
from google.protobuf import json_format
from pathlib import Path
from threading import Timer
from urllib.parse import urlparse
class NotReadableError(Exception):
pass
class NotWritableError(Exception... | nilq/baby-python | python |
import random
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
class Point():
def __init__(self, x, y, label):
self.x = x
self.y = y
self.label = label
def get_x(self):
return self.x
def get_y(self):
retur... | nilq/baby-python | python |
import argparse
import sys
import csv
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
FLAGS = None
BATCH = 8000
Gs = 2 # num of dynamic dims
Gin= 2 # num of input signal dims
TIMESTEP = 0.25
time_points = 200
def Hill_model(x,b,K,links):
# x, current input and state [BATCH,Gin+... | nilq/baby-python | python |
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from numpy import mean
from sklearn.metrics import accuracy_score
from classifier_load_data import tokenizer, sequence_length
def prob_to_class(probs):
return [1 if p >= 0.5 else 0 for p in probs]
# Passing in the relati... | nilq/baby-python | python |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
from .schema_base import SchemaBase
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011, Sebastian Wiesner <lunaryorn@googlemail.com>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the... | nilq/baby-python | python |
## @ingroup Core
# DiffedData.py
#
# Created: Feb 2015, T. Lukacyzk
# Modified: Feb 2016, T. MacDonald
# Jun 2016, E. Botero
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from copy import deepcopy... | nilq/baby-python | python |
import json
from unittest import TestCase
from GeneralTests.EMInfraResponseTestDouble import ResponseTestDouble
from OTLMOW.Facility.FileFormats.EMInfraDecoder import EMInfraDecoder
from OTLMOW.Facility.OTLFacility import OTLFacility
from OTLMOW.OTLModel.Classes.Omvormer import Omvormer
class EMInfraDecoderTests(Tes... | nilq/baby-python | python |
import logging
import pathlib
class Endpoint:
def __init__(self, source_file, addr, port):
self.name = pathlib.Path(source_file).stem
self.addr = addr
self.port = port
def __repr__(self):
return f'{self.name}@{self.addr}:{self.port}'
class EndpointRegistry:
registry = di... | nilq/baby-python | python |
"""Plugin for emitting ast."""
__all__ = [
"DebugAstOptions",
"DebugAstEmitter",
"debug_ast",
]
from dataclasses import dataclass
from beet import Context, configurable
from beet.core.utils import required_field
from pydantic import BaseModel
from mecha import AstRoot, CompilationDatabase, Mecha, Visi... | nilq/baby-python | python |
#!/usr/bin/env python
"""
CREATED AT: 2021/9/14
Des:
https://leetcode.com/problems/reverse-only-letters
https://leetcode.com/explore/item/3974
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
"""
from tool import print_results
class Solution:
@print_results
def reverseOnlyLetters(self, s: str) -... | nilq/baby-python | python |
import pytest
# Local Functions
from fexception.util import set_caller_override
# Local Methods
from fexception.util import KeyCheck
__author__ = 'IncognitoCoding'
__copyright__ = 'Copyright 2022, test_util'
__credits__ = ['IncognitoCoding']
__license__ = 'MIT'
__version__ = '0.0.2'
__maintainer__ = 'IncognitoCodin... | nilq/baby-python | python |
from math import sqrt
class SomeClass:
'''Some class that certainly does things.
Args:
foo (str): Some string.
'''
def __init__(self, foo: str = 'foo'):
self.msg = f'Here comes {foo}!'
def is_msg_large(self, msg: str):
msg_size = len(msg)
is_large = msg_size > 256... | nilq/baby-python | python |
from fractions import Fraction
def roll(dices, times):
counter = {}
for d in dices:
counter[d] = 1
for t in range(1, times):
acc = {}
for k, v in counter.items():
for d in dices:
acc[k + d] = acc.get(k + d, 0) + v
counter = acc
return counter
... | nilq/baby-python | python |
__author__ = 'faisal'
| nilq/baby-python | python |
import os
import importlib
from functools import partial
KNOWN_MODULES = {
# datasets
'opencv_video_seq_dataset': 'hyperseg.datasets.opencv_video_seq_dataset',
'img_landmarks_transforms': 'hyperseg.datasets.img_landmarks_transforms',
'seg_transforms': 'hyperseg.datasets.seg_transforms',
'transform... | nilq/baby-python | python |
"""Module that provides a data structure representing a quantum system.
Data Structures:
QSystem: Quantum System, preferred over QRegistry (can save a lot of space)
Functions:
superposition: join two registries into one by calculating tensor product.
"""
import numpy as np
from qsimov.structures.qstructure im... | nilq/baby-python | python |
from panoramic.cli.husky.service.select_builder.graph_search import (
sort_models_with_heuristic,
)
from panoramic.cli.husky.service.utils.taxon_slug_expression import TaxonSlugExpression
from tests.panoramic.cli.husky.test.mocks.husky_model import (
get_mock_entity_model,
get_mock_metric_model,
)
from test... | nilq/baby-python | python |
import unittest
import_error = False
try:
from ...tables.base import Base
except ImportError:
import_error = True
Base = None
class TestCase00(unittest.TestCase):
def test_import(self):
self.assertFalse(import_error)
class TestCase01(unittest.TestCase):
def setUp(self):
self.bas... | nilq/baby-python | python |
"""Utility functions."""
import pycountry
def eu_country_code_to_iso3(eu_country_code):
"""Converts EU country code to ISO 3166 alpha 3.
The European Union uses its own country codes, which often but not always match ISO 3166.
"""
assert len(eu_country_code) == 2, "EU country codes are of length 2, yo... | nilq/baby-python | python |
from info import *
from choice import *
from rich.console import Console
from rich.table import Table
import time
from rich import print
from rich.panel import Panel
from rich.progress import Progress
def banner():
print(r"""
_ ___ ____ ____ __ _ _
| | | \ \/ /\ \ / / \/ | __ _/ |... | nilq/baby-python | python |
import os
import sys
from copy import deepcopy
from distutils.version import LooseVersion
import h5py
import numpy as np
import pytest
from ...util.functions import random_id
from ...model import Model
from ...model.tests.test_helpers import get_realistic_test_dust
from .. import (CartesianGrid,
Spher... | nilq/baby-python | python |
class Config:
redis = {
'host': '127.0.0.1',
'port': '6379',
'password': None,
'db': 0
}
app = {
'name': 'laravel_database_gym',
'tag': 'swap'
}
conf = Config()
| nilq/baby-python | python |
# Copyright 2018 ZTE 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | nilq/baby-python | python |
#!/usr/bin/python
"""
Broker for MQTT communication of the agent.
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
import logging
import json
from typing import Optional
from diagnostic.ibroker import IBroker
from diagnostic.diagnostic_checker import DiagnosticChecker
fro... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: https://github.com/monero-project/mininero
# Author: Dusan Klinec, ph4r05, 2018
# see https://eprint.iacr.org/2015/1098.pdf
import logging
from monero_glue.xmr import common, crypto
from monero_serialize import xmrtypes
logger = logging.getLogger(__name__)
de... | nilq/baby-python | python |
import os
from dataclasses import dataclass, field
from di import Container, Dependant
@dataclass
class Config:
host: str = field(default_factory=lambda: os.getenv("HOST", "localhost"))
class DBConn:
def __init__(self, config: Config) -> None:
self.host = config.host
async def controller(conn: DB... | nilq/baby-python | python |
from beaker._compat import pickle
import logging
from datetime import datetime
from beaker.container import OpenResourceNamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError
from beaker.synchronization import null_synchronizer
log = logging.getLogger(__name__)
db = None
class GoogleNa... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-05-01 09:50
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_depende... | nilq/baby-python | python |
parrot = "Norwegian Blue"
letter = input('Enter a char: ')
if letter in parrot:
print('it is in there')
else:
print('not there')
activity = input("What would you like to do today? ")
# I want to go to Cinema
if "cinema" not in activity.casefold(): # casefold handles some languages better
print("But I wa... | nilq/baby-python | python |
from __future__ import absolute_import
from .node import Node
from .edge import Edge
from .domain import URI, Domain
from .file import File, FileOf
from .ip_address import IPAddress
from .process import Launched, Process
from .registry import RegistryKey
from .alert import Alert
__all__ = [
"Node",
"Edge",
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Advent of Code 2016 - Day 13, Part One & Two
import sys
from itertools import chain, combinations, product
# test set
# start = (1, 1)
# goal = (7, 4)
# magic = 10
# part one & two
start = (1, 1)
goal = (31, 39)
magic = 1352
def is_valid(coord):
x, y = coord
if x < 0 or y < 0:
... | nilq/baby-python | python |
def extractWwwScribblehubCom(item):
'''
Parser for 'www.scribblehub.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if len(item['tags']) == 2:
item_title, item_id = item['tags']
if item_id.isdigit():
... | nilq/baby-python | python |
from taichi.profiler.kernelprofiler import \
KernelProfiler # import for docstring-gen
from taichi.profiler.kernelprofiler import get_default_kernel_profiler
| nilq/baby-python | python |
from setuptools import setup
# Convert README.md to README.rst because PyPI does not support Markdown.
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst', format='md')
except:
# If unable to convert, try inserting the raw README.md file.
try:
with open('README.md', enco... | nilq/baby-python | python |
from sanic import Sanic
from sanic.response import text
from sanic_plugin_toolkit import SanicPluginRealm
#from examples.my_plugin import my_plugin
from examples import my_plugin
from examples.my_plugin import MyPlugin
from logging import DEBUG
app = Sanic(__name__)
# mp = MyPlugin(app) //Legacy registration example
... | nilq/baby-python | python |
from time import sleep
from procs.makeTree import rel2abs
# 수행부
def loadSet(): # 유저가 구성한 매크로 불러오기 코드
try:
f = open("macro.brn", 'r')
except FileNotFoundError:
return
try:
lines = f.readlines()
for line in lines:
spite_line = line.split()
list_make = ... | nilq/baby-python | python |
from __future__ import print_function
import math, json, os, pickle, sys
import keras
from keras.callbacks import CSVLogger, EarlyStopping, ModelCheckpoint, LambdaCallback
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Conv2... | nilq/baby-python | python |
#This is an exercise program which shows example how while loop can be utilized.
password = ''
while password != 'python123':
password = input("Enter password:")
if password == 'python123':
print("You are logged in!")
else:
print("Try again.") | nilq/baby-python | python |
import argparse
import random
from typing import Any, Dict, List, Sequence, Tuple
import segmentation_models_pytorch as smp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms.functional import (InterpolationMode, hflip,
resized_... | nilq/baby-python | python |
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"]}
base="Win32GUI"
setup( name="NPSerialOscilloscopeGUI",
version="1.0",
description="potato",
options = {"build_exe": build_exe_options},
executables = [Executable("oscilloscope_gui.py", base=base)]) | nilq/baby-python | python |
"""
Problem Statement:
Implement a function, `find_first_unique(lst)` that returns
the first unique integer in the list.
Input:
- A list of integers
Output:
- The first unique element in the list
Sample Input:
[9,2,3,2,6,6]
Sample Output:
9
"""
def find_first_unique(lst):
is_unique = {}
for i, v in enum... | nilq/baby-python | python |
#!/usr/bin/env python
import itertools
with open('input') as f:
serial_number = int(f.read())
# Puzzle 1
def get_power_level(x, y, serial_number):
rack_id = x + 10
power_level = ((rack_id * y) + serial_number) * rack_id
power_level = (power_level // 100 % 10) - 5
return power_level
def get_total_... | nilq/baby-python | python |
import os
import nose
import ckanext.dcatapit.interfaces as interfaces
from ckanext.dcatapit.commands.dcatapit import DCATAPITCommands
eq_ = nose.tools.eq_
ok_ = nose.tools.ok_
class BaseOptions(object):
def __init__(self, options):
self.url = options.get("url", None)
self.name = options.get("... | nilq/baby-python | python |
from .Solver import Solver
| nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... | nilq/baby-python | python |
"""Location cards."""
import logging
from onirim.card._base import ColorCard
from onirim import exception
from onirim import util
LOGGER = logging.getLogger(__name__)
class LocationKind(util.AutoNumberEnum):
"""
Enumerated kinds of locations.
Attributes:
sun
moon
key
"""
... | nilq/baby-python | python |
import logging
import argparse
import transaction
from pyramid.paster import bootstrap
from .actions import proceed_contest
from .db import Config
def process_queue():
parser = argparse.ArgumentParser()
parser.add_argument("config", help="config file")
args = parser.parse_args()
logging.basicConfig()... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.