content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 02/03/2020
"""
from enum import Enum
__all__ = ["UpscaleMode", "MergeMode"]
class MergeMode(Enum):
Concat = 0
Add = 1
class UpscaleMode(Enum):
FractionalTranspose = ... | nilq/baby-python | python |
"""Refiner is the refinement module public interface. RefinerFactory is
what should usually be used to construct a Refiner."""
import copy
import logging
import math
import psutil
import libtbx
from dxtbx.model.experiment_list import ExperimentList
from libtbx.phil import parse
import dials.util
from dials.algorit... | nilq/baby-python | python |
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat.mock import pa... | nilq/baby-python | python |
import torch
from enum import Enum
from experiments import constants
class OptimizerType(Enum):
SGD = 0
Adam = 1
class SchedulerType(Enum):
MultiStep = 0
class SingleNetworkOptimization(object):
def __init__(self, network: torch.nn.Module, n_epochs: int,
lr=1e-4, weight_decay=1e-3... | nilq/baby-python | python |
import sys
import random
import time
from cnn import utils
import logging
import warnings
warnings.filterwarnings("ignore")
import argparse
import torch.utils
import torch.backends.cudnn as cudnn
from utils.scheduler import Scheduler
from torchvision.transforms import transforms
import torchvision.datasets as datasets
... | nilq/baby-python | python |
#!/usr/bin/env python3
import base64
import os
import subprocess
import sys
import yaml
EDITOR = os.environ.get('EDITOR', 'vi')
class NoDatesSafeLoader(yaml.SafeLoader):
@classmethod
def remove_implicit_resolver(cls, tag_to_remove):
"""
Remove implicit resolvers for a particular tag
... | nilq/baby-python | python |
#!/usr/bin/python
"""
Basic class for communication to Parrot Bebop
usage:
./bebop.py <task> [<metalog> [<F>]]
"""
import sys
import socket
import datetime
import struct
import time
import numpy as np
import math
from navdata import *
from commands import *
from video import VideoFrames
# this will be in ... | 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 |
import numpy as np
import csv
import json
import argparse
import pickle
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--method", help="vote Method to learn from")
ap.add_argument("-r", "--row", help="data row joined by comma")
ap.add_argument("-f", "--filename", help="filename of dataset")
args = vars(ap.parse_... | nilq/baby-python | python |
# Copyright (C) Izumi Kawashima
#
# json2oscimv4 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# json2oscimv4 is distributed in the... | nilq/baby-python | python |
load(
"@bazel_tools//tools/jdk:toolchain_utils.bzl",
"find_java_toolchain",
)
load(
"@rules_scala_annex//rules:providers.bzl",
_ScalaConfiguration = "ScalaConfiguration",
_ZincConfiguration = "ZincConfiguration",
_ZincInfo = "ZincInfo",
)
load(
"@rules_scala_annex//rules/common:private/utils... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import numpy as np
import timeit
import json
from operator_benchmark import benchmark_utils
"""Performance microbenchmarks.
This module contains core ... | nilq/baby-python | python |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | nilq/baby-python | python |
import abc
import numpy as np
class ErrFunc(abc.ABC):
"""Base class for classification model error functions."""
@abc.abstractmethod
def apply(self, prediction, y):
"""Apply the nonconformity function.
Parameters
----------
prediction : numpy array of shape [n_samples, n_... | nilq/baby-python | python |
import bpy
from math import pi
# ----------------------------------------------------------------------------------------
# Start - copied functions
# ----------------------------------------------------------------------------------------
def sun_light(
location, rotation, power=2.5, angle=135, name="Light_sun"... | nilq/baby-python | python |
#!/bin/python
#python
import sys
import os
import shutil
import numpy
import time
import math
import threading
from scipy import ndimage
#appion
from appionlib import appionScript
from appionlib import apStack
from appionlib import apDisplay
from appionlib import appiondata
from appionlib import apEMAN
from appionlib ... | nilq/baby-python | python |
# terrascript/provider/josenk/esxi.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:15:57 UTC)
import terrascript
class esxi(terrascript.Provider):
"""Terraform-provider-esxi plugin"""
__description__ = "Terraform-provider-esxi plugin"
__namespace__ = "josenk"
__name__ = "esxi"
... | nilq/baby-python | python |
from .db import session_scope, Server
from datetime import datetime, timedelta
class Gateway:
def get_all_servers(self):
with session_scope() as session:
raw_servers = session.query(Server)
raw_servers_dict = []
if raw_servers:
for raw_server in raw_se... | nilq/baby-python | python |
"""Utility functions."""
from typing import typevar, List, Any
T = typevar('T')
def short_type(obj: object) -> str:
"""Return the last component of the type name of an object.
If obj is None, return 'nil'. For example, if obj is 1, return 'int'.
"""
if obj is None:
return 'nil'
t = str... | nilq/baby-python | python |
from abc import ABC
from abc import abstractmethod
class DatabaseQuery(ABC):
@staticmethod
def query_invoke(func):
def wrapper_method(self_instance, *args, **kwargs):
try:
self_instance.create_connection()
result = func(self_instance, *args, **kwargs)
... | nilq/baby-python | python |
# coding: utf-8
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
import os
sys.path.append('.\src')
sys.path.append('..\src')
from src.main_functions import *
updateInput='u'
fullupdateInput='fu'
downloadInput='d'
statusInput='s'
compressInput='c'
def check_env():
try:
os.... | nilq/baby-python | python |
import json
from collections import defaultdict
from typing import List, Tuple, Dict
from commands.snapshot import snapshot
from drive.api import DriveFile, Snapshot, resolve_paths, ResourcePath, Resource
from drive.http import ErrorHandlingRunner, GAPIBatchRunner
from drive.misc import eprint
from drive.serializers i... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: UTF-8
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import bs4
import requests
import re
from urllib.request import urlretrieve
import os.path
import csv
if __name__ == "__main__":
base__url = "http://pesquisa.memoriasreveladas.gov.br/mrex/consulta/"
first_url = "... | nilq/baby-python | python |
# 20412 - [Job Adv] (Lv.100) Mihile 4rd job adv
sm.setSpeakerID(1101002)
if sm.sendAskYesNo("Are you ready, are you okay to leave?"):
sm.warp(913070100, 0)
sm.setInstanceTime(300, 130000000) | nilq/baby-python | python |
##############################################################################
# Written by: Cachen Chen <cachen@novell.com>
# Date: 09/25/2009
# Application wrapper for Moonlight combobox
# Used by the combobox-*.py tests
##############################################################... | nilq/baby-python | python |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
"""
Copyright (c) Open Carbon, 2020
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
backend/tools.py
Provides range of backend tools that can be run from command line:
importlocations: Imports location data from file that is used to geolocate s... | nilq/baby-python | python |
"""This module contains definitions and data structures for 2-, 4-, and 8-valued logic operations.
8 logic values are defined as integer constants.
* For 2-valued logic: ``ZERO`` and ``ONE``
* 4-valued logic adds: ``UNASSIGNED`` and ``UNKNOWN``
* 8-valued logic adds: ``RISE``, ``FALL``, ``PPULSE``, and ``NPULSE``.
T... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 14:46:51 2020
@author: gabriel
"""
#%% MATLAB Code to reproduce
# function thresh_calc(nbeg,nend,n_noise,sig_fact,necdf_flag,nlbound)
# % Calculate the threshold using one of two methods
# % P=mean|W| + c sigma
# % P is computed from the e... | nilq/baby-python | python |
from torch.utils import data
import yaml
from argparse import ArgumentParser
from typing import Any, List, Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.distributions as dist
from torch.utils.data import DataLoader, Ran... | nilq/baby-python | python |
"""
Code for defining the architecture of the Encoder and the Decoder blocks.
"""
import tensorflow as tf
class Encoder():
def __init__(self, vocab_size, embedding_dim, encoder_units):
# print(vocab_size, embedding_dim, encoder_units, "##########################################ENCODER#####################... | nilq/baby-python | python |
'''
Created on Mar 13, 2018
@author: abelit
'''
import os
import json
from utils import filepath
project_settings = {
# 项目信息配置
'package': 'dev',
'version':'3.14',
'name':'__dbreport__.py',
'author':'abelit',
'email':'ychenid@live.com',
'description':'',
}
path_settings = {
'image'... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# jvparidon@gmail.com
from .timer import timer
| nilq/baby-python | python |
import base64
import json
import cv2
import numpy as np
from decouple import config
from flask import Flask, request
from api.face import FaceVerification
from db.mongo import FaceEncodings
app = Flask(__name__)
face_verification = FaceVerification(
FaceEncodings(
config("DATABASE_URI")
)
)
@app.r... | nilq/baby-python | python |
import pocketcasts as pc
import requests
import re
import configparser
from pathlib import Path
def get_valid_filename(s):
s = str(s).strip()
return re.sub(r"(?u)[^-\w. ]", "", s)
def get_extension(url):
if "?" in url:
url, _ = url.split("?", 1)
return url.split(".")[-1]
print("Reading con... | nilq/baby-python | python |
import numpy as np
from config import handTrackConfig as htconf
from math import sin, cos, sqrt, atan2, radians
import cv2
# 8 12 16 20
# | | | |
# 7 11 15 19
# 4 | | | |
# | 6 10 14 18
# 3 | | | |
# | 5---9---13--17
# 2 \ /
# \ ... | nilq/baby-python | python |
"""
This module provides various utility functions.
"""
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
from typing import Tuple
import numpy as np
# -------------------------------------------... | nilq/baby-python | python |
"""
Based on https://github.com/ikostrikov/pytorch-a2c-ppo-acktr
"""
import gym
import torch
import random
from environments.env_utils.vec_env import VecEnvWrapper
from environments.env_utils.vec_env.dummy_vec_env import DummyVecEnv
from environments.env_utils.vec_env.subproc_vec_env import SubprocVecEnv
from environm... | nilq/baby-python | python |
"""
Sets permission for the API (ONLY)
"""
from rest_framework import permissions
# TODO: Add restriction to users (get token, refresh token, verify token, post request)
class IsReadOnly(permissions.DjangoModelPermissions):
"""
Custom permission to only allow reading.
"""
def has_object_permission(se... | nilq/baby-python | python |
###############################################################################
##
## Copyright 2011 Tavendo GmbH
##
## 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
##
## ht... | nilq/baby-python | python |
from typing import Set, List, Tuple, Dict
def fibonacci(n: int) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raise a ValueError.
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(10)
55
>>> fibonacci(-2)
Tracebac... | nilq/baby-python | python |
from functools import wraps
from . import environment as env
import wx, os
class VirtualEnvMustExistDecorator:
"""装饰器:虚拟环境必须存在!!!"""
def __init__(self, *args, **kwargs): ...
def __call__(self, func, e=None):
@wraps(func)
def decorator(obj, *args, **kwargs):
env_path = env.getPyt... | nilq/baby-python | python |
import os, json, sys, shutil, distutils
from distutils import dir_util
if_block_template = '\tif(!strcmp(cmd, "{}")){{\n\
\t\treturn {}(argv, argc);\n\
\t}}else '
ending = '{\n\
\t\tstde("Not a command:");\n\
\t\tstde(argv[0]);\n\
\t}'
set_driver_template = "\tdrivers[{}] = &{};\n"
include_template = '#include... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from typing import Dict
import torch
from torch import optim
from datasets import Dataset
from models i... | nilq/baby-python | python |
# Author : BIZZOZZERO Nicolas
# Completed on Sun, 24 Jan 2016, 23:11
#
# This program find the solution of the problem 5 of the Project Euler.
# The problem is the following :
#
# 2520 is the smallest number that can be divided by each of the
# numbers from 1 to 10 without any remainder.
# What is the smallest ... | nilq/baby-python | python |
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
from communication import Communication
import math
from dataBase import data_base
from PyQt5.QtWidgets import QPushButton
pg.setConfigOption('background', (33, 33, 33))
pg.setConfigOption('foreground', (197, 198, 199))
# Interface variab... | nilq/baby-python | python |
import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, SharedMemoryFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import Mo... | nilq/baby-python | python |
"""
This module performs all basic DFA operations.
It is an interface for pyfst.
"""
# /usr/bin/python
from operator import attrgetter
import fst
from alphabet import createalphabet
EPSILON = fst.EPSILON
def TropicalWeight(param):
"""
Returns fst TropicalWeight
Args:
param (str): The input
Re... | nilq/baby-python | python |
from singlecellmultiomics.universalBamTagger.digest import DigestFlagger
from singlecellmultiomics.tagtools import tagtools
class NlaIIIFlagger(DigestFlagger):
def __init__(self, **kwargs):
DigestFlagger.__init__(self, **kwargs)
def addSite(self, reads, strand, restrictionChrom, restriction... | nilq/baby-python | python |
#!/usr/bin/env python2
import sys
import time
import logging
import argparse
def main():
"""
Tumor Map Calc Agent
"""
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument("-i", "--interval", type=int, default=0,
help="Minutes between calc, default ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""SOG run processor.
Do various operations related to running the the SOG bio-physical
model of deep estuaries. Most notably, run the model.
This module provides services to the SOG command processor.
:Author: Doug Latornell <djl@douglatornell.ca>
:License: Apache License, Version 2.0
Copy... | nilq/baby-python | python |
import datetime
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from enum import Enum
from typing import List
from typing import Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pglet import BarChart
from pglet ... | nilq/baby-python | python |
from .home import bp as home
from .dashboard import bp as dashboard
from .api import bp as api
# the .home syntax direct the program to find the module name home then import BP routes.
| nilq/baby-python | python |
"""A class to hold data parsed from PDFs."""
import dataclasses
@dataclasses.dataclass
class Datum:
"""A class to hold data parsed from PDFs."""
text: str = ""
traits: list[dict] = dataclasses.field(default_factory=list)
reject: bool = False
| nilq/baby-python | python |
import sounddevice as sd
from scipy.io import wavfile
from scipy import signal
import sys
import matplotlib.pyplot as plt
import os
import subprocess as sp
from collections import defaultdict, Counter
import pyprind
import numpy as np
import random
from .utils import readwav
output_seconds = 5
n_gram = 2
fname = 'Nigh... | nilq/baby-python | python |
#!/usr/bin/python3.7
import subprocess
import sys
v = sys.argv[1]
subprocess.call(["amixer", "sset", "Speaker", v + "%"]) | nilq/baby-python | python |
from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox, \
QLabel, QVBoxLayout, QSizePolicy, \
QCheckBox, QLineEdit, QPushButton, QHBoxLayout, \
QSpinBox, QTabWidget, QMessageBox
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtG... | nilq/baby-python | python |
import twoLSTMcuda as t
model = t.torch.load(open("twoLSTMentireModel.npy", 'rb'))
print(t.checkAcc(model, t.data, t.labels))
print(t.checkAcc(model, t.valData, t.valLabels))
| nilq/baby-python | python |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
import os
@slash.requires(have_ffmpeg)
@slash.requires(have_ffmpeg_vaapi_accel)
class TranscoderTest(slash.Test):
def before(self):
self.refctx = []
def transcode_1to... | nilq/baby-python | python |
from django.shortcuts import *
from django.http import *
from django.shortcuts import *
from django.urls import *
import traceback
import json
from .models import *
from django.db.utils import IntegrityError
from django.db.models import F
from .crypto import *
import math
from account_info.models import User
from walle... | nilq/baby-python | python |
#!/usr/bin/python
import unittest
from utils.logger import Logger
class UtLogger(unittest.TestCase):
def setUp(self):
self.logger = Logger().getLogger("test.utils.UtLogger")
def testLogger(self):
self.logger.debug("1")
self.logger.info("2")
self.logger.warn("3")
... | nilq/baby-python | python |
from base_n_treble import db, auth
from base_n_treble.models.user import User
def setup_admin():
from tests.fixtures import TEST_ADMIN
db._adapter.reconnect()
admins = auth.id_group("admin") if auth.id_group("admin") else auth.add_group("admin")
print("Admin group id: '{}'".format(admins))
db._ada... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
# configuration
DATABASE = "/tmp/flaskr.db"
DEBUG = True
SECRET_KEY = "development key"
USERNAME= "admin"
PASSWORD = "default... | nilq/baby-python | python |
#! /usr/bin/env python
import sys
import os
import disttools
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from strparser import *
from filehdl import *
from pyparser import *
def make_string_slash_ok(s):
sarr = re.split('\n', s)
rets = ''
for l in sarr:
l = l.rstrip('\r\n')
... | nilq/baby-python | python |
import pytest
import abjad
import abjadext.nauert
class Job:
### INITIALIZER ###
def __init__(self, number):
self.number = number
### SPECIAL METHODS ###
def __call__(self):
self.result = [
x for x in abjad.math.yield_all_compositions_of_integer(self.number)
]
... | nilq/baby-python | python |
"""
===========
04. Run ICA
===========
This fits ICA on epoched data filtered with 1 Hz highpass,
for this purpose only using fastICA. Separate ICAs are fitted and stored for
MEG and EEG data.
To actually remove designated ICA components from your data, you will have to
run 05a-apply_ica.py.
"""
import itertools
imp... | nilq/baby-python | python |
import logging
import typing
import copy
from typing import Any, Dict, List, Text
from rasa.nlu.components import Component
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer
from rasa.nlu.training_data import Message, TrainingData
logger = logging.getLogger(__na... | nilq/baby-python | python |
import datetime
import enum
from sqlalchemy import (
Column,
Integer,
String,
Enum,
TIMESTAMP,
ForeignKey,
Index,
Float,
)
from sqlalchemy.orm import relationship
from .base import Base
class SystemUpdate(Base):
__tablename__ = "system_update"
pk = Column(Integer, primary_ke... | nilq/baby-python | python |
from italian_csv_type_prediction.simple_types import IntegerType
import numpy as np
def test_integer_type():
predictor = IntegerType()
valids = [
3,
6,
0,
"1.000.000.00"
]
invalids = [
"ciao",
"12.12.94",
"12.12.1994",
False,
Tru... | nilq/baby-python | python |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
... | nilq/baby-python | python |
"""Parameters for the model of marine particle microbial degradation
and coupling of degradation with sinking speed, part of the paper
"Sinking enhances the degradation of organic particle by marine bacteria"
Uria Alcolombri, François J. Peaudecerf, Vicente Fernandez, Lars Behrendt, Kang Soo Lee, Roman Stocker
Na... | nilq/baby-python | python |
import os
import json
import shutil
import grp
from pathlib import Path
def change_key(my_json, old_key, new_key):
if old_key in my_json:
# store the value
val = my_json[old_key]
# delete the old key/value pair
del my_json[old_key]
# error checking
if new_key in my_j... | nilq/baby-python | python |
from pytari2600.pytari2600 import new_atari
emulator = new_atari("../../roms/dragster.a26", headless=False)
while True:
emulator.core.step()
# print("---AFTER EXECUTION---" + str(emulator.stella.clocks.system_clock))
# print(emulator.stella.display_cache) | nilq/baby-python | python |
# # -*- coding: utf-8 -*-
# """
# Created on Fri May 8 17:08:43 2020
#%%
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import pi, c
from numpy.fft import fft, ifft, fftshift
#%%
def calculate_spectrum(z, E, H, f=3.7e9):
k0 = 2*pi*f/c
lambda0 = c/f
# fourier domain points
B = ... | nilq/baby-python | python |
from dataclasses import dataclass
from bindings.csw.animate_type import AnimateType
__NAMESPACE__ = "http://www.w3.org/2001/SMIL20/Language"
@dataclass
class Animate1(AnimateType):
class Meta:
name = "animate"
namespace = "http://www.w3.org/2001/SMIL20/Language"
| nilq/baby-python | python |
import unittest
import electricity
class VersionTestCas(unittest.TestCase):
def test_version(self):
self.assertEqual(electricity.__version__, '0.1')
| nilq/baby-python | python |
from keris.layers.merge import Concatenate, Sum
from keris.layers.core import Input, Dense
from keris.layers.convolution import Conv2D
from keris.layers.dropout import Dropout
from keris.layers.pool import MaxPooling2D, GlobalAveragePooling2D
| nilq/baby-python | python |
from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
"""returns some text"""
retur... | nilq/baby-python | python |
import os
import torch
import numpy as np
from torch.autograd import Variable
from .base_trainer import BaseTrainer
from model import networks
from model.loss import AttnDiscriminatorLoss, AttnGeneratorLoss, KLLoss
from utils.util import convert_back_to_text
from collections import OrderedDict
dirname = os.path.dirname... | nilq/baby-python | python |
import os
from setuptools import setup
from pip.req import parse_requirements
# parse requirements
reqs = [str(r.req) for r in parse_requirements("requirements.txt", session=False)]
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README fi... | nilq/baby-python | python |
from packetbeat import BaseTest
"""
Tests for trimming long results in pgsql.
"""
class Test(BaseTest):
def test_default_settings(self):
"""
Should store the entire rows but only
10 rows with default settings.
"""
self.render_config_template(
pg... | nilq/baby-python | python |
# Generated by Django 2.0.3 on 2018-03-16 19:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nps', '0021_auto_20180316_1239'),
]
operations = [
migrations.RenameField(
model_name='rawresults',
old_name='role_type',
... | nilq/baby-python | python |
# Import Abaqus and External Modules
from abaqusConstants import *
from abaqus import *
import random
import regionToolset
import mesh
import step
import part
randomSeed=[41557]
for eachModel in range(0,1):
#
# Create Model Database
VerFile=Mdb(pathName="MStructure")
VerModel=VerFile.models['Model-1']... | nilq/baby-python | python |
'''
@author: Jakob Prange (jakpra)
@copyright: Copyright 2020, Jakob Prange
@license: Apache 2.0
'''
import sys
import json
import argparse as ap
from pathlib import Path
from .mode import Mode
argparser = ap.ArgumentParser()
mode = argparser.add_subparsers(help='mode', dest='mode')
def str2bool(v):
if isinst... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
"""
`adafruit_matrixportal.network`
================================================================================
Helper library for the MatrixPortal M4 or Adafruit RGB Matrix Shield + Met... | nilq/baby-python | python |
"""Tests for the NumericValue data class."""
from onyx_client.data.animation_keyframe import AnimationKeyframe
from onyx_client.data.animation_value import AnimationValue
from onyx_client.data.numeric_value import NumericValue
class TestNumericValue:
def test_create(self):
expected = NumericValue(
... | nilq/baby-python | python |
from .config_diff import Config
import yaml
def save(filename: str, config: Config):
"""Save configuraion to file"""
with open(filename, 'w') as fh:
yaml.dump(config, fh, default_flow_style=False)
| nilq/baby-python | python |
import os
SPREEDLY_AUTH_TOKEN = os.environ.get('SPREEDLY_AUTH_TOKEN','asdfasdf')
SPREEDLY_SITE_NAME = 'jamesr-c-test'
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 25, Part 1
"""
def main():
with open('in.txt') as f:
card_key, door_key = map(int, f.readlines())
subject_number = 7
value = 1
card_loop = 0
while True:
card_loop += 1
value *= subject_number
... | nilq/baby-python | python |
import threading
from time import sleep
lock = threading.Lock()
# funcao que espera 1 segundo
def wait():
global lock
while True:
sleep(1)
lock.release()
def LerVelocidade():
global lock
while True:
lock.acquire()
print('Leitura da Velocidade')
print('cheguei'... | nilq/baby-python | python |
print('gunicorn hook')
hiddenimports = ['gunicorn.glogging', 'gunicorn.workers.sync']
| nilq/baby-python | python |
from unittest import mock
from bx_py_utils.test_utils.datetime import parse_dt
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db.utils import IntegrityError
from django.test import TestCase
from django.utils import timezone
from bx_django_utils.models.m... | nilq/baby-python | python |
import bge
scn = bge.logic.getCurrentScene()
def CamAdapt(cont):
lum = scn.objects['und.lum1']
nab = scn.objects['Naball_gerUnderground']
def LoadPart1(cont):
loadObj = [] | nilq/baby-python | python |
#!/usr/bin/env python3
'''Written by Corkine Ma
这个模块的大部分是子类化了一个QDialog,用来接受用户的输入,并且将其保存到daily.setting文件夹中
除此之外,还有一个函数,这个函数负责从daily.setting读取数据,并且使用checkandsend.py模块中的
两个函数来判断在数据库位置是否存在监视文件夹中符合正则表达式规则的文件,如果文件夹中有这样的文件
但是数据库中没有,就判定是一篇新日记,然后调用邮件发送程序发送邮件,其会返回一个bool值,大部分情况,
只要参数文件和日志文件不出问题,返回的都是true,至于发送邮件出错,依旧会返回true(因为考虑到可... | nilq/baby-python | python |
from flask import Blueprint
from flask import Blueprint
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_,and_
from .form import *
from utils import *
from decorators import admin_required, permission_required
# from .. import app
from flask import current_app
from wtforms import ValidationError, vali... | nilq/baby-python | python |
#!/usr/bin/env python
from distutils.core import setup
import uritemplate
base_url = "http://github.com/uri-templates/uritemplate-py/"
setup(
name = 'uritemplate',
version = uritemplate.__version__,
description = 'URI Templates',
author = 'Joe Gregorio',
author_email = 'joe@bitworking.org',
url = base_ur... | nilq/baby-python | python |
#
# Copyright (C) 2019 Luca Pasqualini
# University of Siena - Artificial Intelligence Laboratory - SAILab
#
#
# USienaRL is licensed under a BSD 3-Clause.
#
# You should have received a copy of the license along with this
# work. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
# Import scripts
from .pass... | nilq/baby-python | python |
from appcontroller import AppController
class CustomAppController(AppController):
def __init__(self, *args, **kwargs):
AppController.__init__(self, *args, **kwargs)
def start(self):
print "Calling the default controller to populate table entries"
AppController.start(self)
def sto... | nilq/baby-python | python |
import json
import os, re
import numpy as np
import pandas as pd
from scipy.stats import describe
from tqdm import tqdm
# Open a file
path = "/home/ubuntu/model-inference/rayserve/gpt-optim"
dirs = os.listdir(path)
# This would print all the files and directories
latency_list = []
requests = {}
for file in dirs:
... | nilq/baby-python | python |
# Crei um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
"""for contador in range(1, 51):
if contador % 2 == 0:
if contador == 50:
print(f'{contador}.')
else:
print(f'{contador}, ', end='')
"""
for contador in range(2, 51, 2):
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.