content stringlengths 5 1.05M |
|---|
"""
testreport.py -
NOTE: this module should not be run as a standalone scripts, excepts for
built-in tests.
"""
# HISTORY ####################################################################
#
# 1 Apr11 MR # Initial version
# 2 Dec14 MR # Ported to Py3
# ... |
"""
pygluu.kubernetes.terminal.testenv
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains helpers to interact with user's inputs for terminal test environment prompts.
License terms and conditions for Gluu Cloud Native Edition:
https://www.apache.org/licenses/LICENSE-2.0
"""
import click
from pygluu.kubernetes.t... |
"""Information about the Lares satellite
Description:
Useful constants for the Lares satellite.
References:
https://ilrs.cddis.eosdis.nasa.gov/missions/satellite_missions/current_missions/lars_general.html
"""
# Standard library imports
import math
# Midgard imports
from midgard.dev import plugins
# Where i... |
import copy
import time as _time
import math as _math
import numpy as np
import scipy.sparse as _sp
import numpy as _np
from mdptoolbox.mdp import QLearning as MDPQLearning, \
_MSG_STOP_UNCHANGING_POLICY, _MSG_STOP_MAX_ITER, \
_MSG_STOP_EPSILON_OPTIMAL_POLICY
from mdptoolbox.mdp import PolicyIteration as MDPPo... |
#hardware platform: pyboard V1.1
from pyb import Timer
from time import sleep
import pyb
tim=pyb.Timer(5,freq=100) #create Timer object
tchannel=tim.channel(1,Timer.PWM,pin=pyb.Pin.board.X1,pulse_width=0) #init and return a timer channel object
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (PHYS-581-2021)
# language: python
# metadata:
# debugger: t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import twid
from setuptools import setup, find_packages
setup(
name = "twid",
version = twid.__version__,
description = "The relevant functions about Taiwan Identification Card system.",
author = "Plenty Su",
author_email = "plenty.su@gmail.com",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is the main executable of Ironworks. It parses the command line arguments, does init and calls the start function of Ironworks."""
import sys
import os
from flask import Flask
from ironworks import server
from ironworks import preferences
app = Flask(__name__)
app... |
# Generated by Django 2.0.7 on 2018-08-06 12:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0021_auto_20180806_1206'),
]
operations = [
migrations.RenameField(
model_name='articlepage',
old_name='category'... |
from ..models.models import Usuario
from .db import session
from ..models.exceptions import UserAlreadyExists, UserNotFound
from typing import Optional
def register_user(usuario: Usuario) -> Usuario:
"""Agrega un nuevo usuario a la tabla y lo devuelve"""
if user_exists(usuario):
raise UserAlreadyExis... |
#!/usr/bin/python3
import serial
import time
from datetime import datetime
import os
import logging
import paramiko
import traceback
from config import ConsoleConfig
from common import utc_str
class Console:
def __init__(self):
self.iteration = 0
self.logfile = 'console.log' # TODO: Make this per ... |
#!/usr/bin/env python
#
# Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
import os
import shutil
import sys
import pytest
from sos import execute_workflow
@pytest.mark.skipif(
not shutil.which('singularity'),
reason='Ski... |
from recalibrate.nothing import much
def test_nothin():
assert much(20)==40
if __name__=='__main__':
test_nothin() |
from time import sleep
from pycrunch_trace.client.api import trace
def alternative_ways_to_trace():
sleep(0.25)
print('You can use Trace object to manually start and stop tracing')
print(' Or by applying @trace decorator to the method')
print(' See examples bellow')
def example_without_decorators():... |
from SilverstackAccess.SilverstackAccess import findSilverstackInstances, getProjectList, Project |
import sys,os,time
class Folder:
"""
A class that holds info about a folder, which can be accessed via attributes
- folderpath must be the full path incl drive letter, or a list of path name elements to be joined together
- **exists is optional boolean that must be set to false if dealing with imaginar... |
from pprint import pp, pprint
def main(args=None):
from functools import wraps
def debug(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Full name of this method:", func.__qualname__)
return func(*args, **kwargs)
return wrapper
stack = []
# th... |
def largestRectangle(h):
s = []
ans = len(h)
h.append(0)
for i in range(len(h)):
left_index = i
while len(s) > 0 and s[-1][0] >= h[i]:
last = s.pop()
left_index = last[1]
ans = max(ans, h[i] * (i + 1 - last[1]))
ans = max(ans, last[0] * ... |
import argparse
from os import path, mkdir
import sys
import logging
import pprint
import time
import uuid
from states import TankSize
import simulation
import environment
DIVIDER_CHOICES = (
('RANDOM_SIZE', simulation.randomize_subset_variable_limited_size),
('UNIFORM_SIZE', simulation.randomize_subset_cons... |
# coding=utf-8
#Copyright (C) 2017. Huawei Technologies Co., LTD. All rights reserved.
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of Apache License, Version 2.0.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even t... |
from app.github.client import *
from app.github.repository import *
ORGANIZATION_URI = 'https://github.com/{0}'
API_ORGANIZATION_REPOSITORIES_URI = 'https://api.github.com/orgs/{0}/repos'
class GithubOwner(GithubClient):
def __init__(self, name, http_compression=True):
super().__init__(http_compression... |
import torch
import itertools
import numpy as np
from numbers import Number
from typing import Any, Optional
import graphgallery as gg
__all__ = ['asarray', 'index_to_mask',
'repeat', 'get_length']
def asarray(x: Any, dtype: Optional[str] = None) -> np.ndarray:
"""Convert `x` to interg... |
"""
NOTE: The Serverless directory was written as a proof of concept extension of our library
that involves no servers, with clients communicating with each other directly.
"""
import sys
sys.path.append('..')
import config
import datetime
import numpy as np
import pickle
from client_agent_serverless import Client... |
# 公用配置
DEBUG = True
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ENCODING = "utf8mb4"
SECRET_KEY = "root"
|
"""Testing the login page of saucedemo.com"""
import pytest
import lib.LoginCreds as LoginCreds
from lib.Constants import CHROME_MOBILE, CHROME_HEADLESS
from pages.LoginPage import LoginPage
@pytest.mark.parametrize(
"browser,mode,device, username, password",
[
(*CHROME_MOBILE, LoginCreds.STANDARD_USE... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import math
import random
import copy
import logging
import pickle
import numpy as np
from age_iter import FaceImageIter
from age_iter import FaceImageIterList
import mxnet as mx
from mxnet... |
class Solution:
def XXX(self, numRows: int) -> List[List[int]]:
res = [[1]]
for i in range(1, numRows):
print(i)
temp = [1]
for j in range(i - 1):
temp.append(res[i-1][j] + res[i-1][j + 1])
temp.append(1)
res.append(temp)
... |
import pickle
from django.db.models import fields
from django.db.models.fields.subclassing import SubfieldBase
class SerializedObjectField(fields.TextField):
description = "SerializedObject"
__metaclass__ = SubfieldBase
def get_internal_type(self):
return "TextField"
@classmethod
def get... |
"""merge - deeply merge mappings"""
import itertools
from collections.abc import Mapping
__all__ = ["merge"]
def merge(*args: Mapping, _depth: int = 0, **kwargs) -> Mapping:
"""Compose one or more mappings with kwargs.
If ``args`` are given, the first is used as the base mapping. Otherwise,
the base is ... |
import chalice
import unittest
import datetime
import json
import os
import sys
import time
import boto3
from chalicelib.app import set_stage
from foursight_core import (
fs_connection,
s3_connection,
es_connection,
exceptions,
check_schema,
stage,
environment,
sqs_utils,
run_result,... |
# Copyright (c) 2019-2020 Idein Inc.
#
# 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, di... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
import logging
... |
"""
Copyright (c) 2020, 2021, Oracle Corporation and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""
import java.util.logging.Level as Level
from oracle.weblogic.deploy.aliases import AliasException
from wlsdeploy.aliases.aliases import Alia... |
# -*- encoding: utf-8 -*-
from __future__ import print_function
__author__ = 'kotaimen'
__date__ = '31/12/2016'
from troposphere import Base64, FindInMap, GetAtt, Join, Select, Sub
from troposphere import ImportValue, Export
from troposphere import Condition, And, Equals, If, Not, Or
from troposphere import Template... |
from datetime import datetime
from django.test import TestCase
from ..validator import NIDValidator
class TestNIDValidator(TestCase):
def setUp(self):
pass
def test_valid_nid(self):
"""Test Case: Send valid NID number
Expected:
- Return True
- message is 'val... |
#!/usr/bin/python
import numpy
from sys import argv
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
#added this so i can fiddel around with the model from one pl... |
# Update a single file in Git repository with generated commit message.
import git
import sys
from os import path
# Starting from directory, walk upwards until Git repository is found
def find_git_repo(root):
folder = root
while True:
candidate = path.join(folder, '.git')
if path.isdir(candid... |
from __future__ import print_function
from ThreesBoard import ThreesBoard
from ThreesBoard import _swipe_left, _swipe_right, _swipe_up, _swipe_down
from TileDeck import TileDeck
from random import randint, choice
from copy import copy
MOVES = {
"left":0,
"right":1,
"up":2,
"down":3,
0:"... |
# -*- coding: utf-8 -*-
"""Component that manages application state.
"""
import copy
from collections import defaultdict
from typing import Optional, Literal, TypeVar, Union
from colorama import Fore
from diamond_eye.utils import MetaSingleton
T = TypeVar('T')
class State(metaclass=MetaSingleton):
"""Componen... |
'''This module contains the elements needed to set up the listen attend and
spell network.'''
from __future__ import absolute_import, division, print_function
from copy import copy
import collections
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops.rnn_ce... |
import os
import pytest
import numpy as np
import segmentation_models_pytorch as smp
def _test_preprocessing(inp, out, **params):
preprocessed_output = smp.encoders.preprocess_input(inp, **params)
assert np.allclose(preprocessed_output, out)
def test_mean():
inp = np.ones((32, 32, 3))
out = np.zero... |
import os
import tempfile
import cv2
import numpy as np
import onnxruntime
import pytest
import tensorflow as tf
from doctr.models import classification
from doctr.models.classification.predictor import CropOrientationPredictor
from doctr.models.utils import export_classification_model_to_onnx
@pytest.mark.parametr... |
from .analyser import Analyser
__all__=['Analyser']
|
from binascii import hexlify, unhexlify
one = "1c0111001f010100061a024b53535009181c"
two = "686974207468652062756c6c277320657965"
a = unhexlify(one)
b = unhexlify(two)
def xor(a, b):
#bitwise XOR of bytestrings
return bytes([ x^y for (x,y) in zip(a, b)])
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 20:45:32 2021
@author: Braxton Brown
Librosa - ISC License
Copyright (c) 2013--2017, librosa development team.
https://github.com/librosa/librosa/blob/main/LICENSE.md
Numpy - Copyright (c) 2005-2020, NumPy Developers.
All rights reserved.
https://numpy.org/doc/stable... |
import pytest
class Assertions:
@staticmethod
def assert_not_member(name, obj):
assert name not in dir(obj), 'Property {} found'.format(name)
@staticmethod
def assert_member(name, obj):
assert name in dir(obj), 'Property {} not found'.format(name)
@staticmethod
def assert_ass... |
from .utils import string_to_bits
def break_repeating_key_xor(ciphertext):
return ""
def hanning_distance(string1, string2):
if len(string2) != len(string1):
raise Exception("Two strings must be the same length")
hanning_distance_score = 0
i = 0
string1_bits = string_to_bits(string1)
... |
import unittest
from datalabs.tasks.text_pair_classification import (
NaturalLanguageInference,
TextPairClassification,
)
class MyTestCase(unittest.TestCase):
def test_something(self):
# text pair classification
self.assertEqual(TextPairClassification().task, "text-pair-classification")
... |
import pykickstart.parser
import pykickstart.sections
class KickstartParser(pykickstart.parser.KickstartParser):
def setupSections(self):
pykickstart.parser.KickstartParser.setupSections(self)
def get_packages(self, dnf_obj):
packages = set()
conditional_packages = []
package... |
from mlrampup.supervisedlearning.utils import fileProcessor as fp
from mlrampup.supervisedlearning.utils import dataProcessor as dp
from mlrampup.supervisedlearning.plot import scatter as sct
import numpy as np
import logging
logger = logging.getLogger('tofile')
def main():
matReturn, classLabelVectorReturn = fp.... |
#
# Copyright (c) 2020 Seagate Technology LLC and/or 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 ap... |
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
from pydantic.tools import lru_cache
from fastapi.templating import Jinja2Templates
import config
templates = Jinja2Templates(directory="core/themes")
@lru_cache()
def get_settings():
return config.SettingsApp()
|
def soma(a, b):
result = float(a) + float(b)
return result
def sub(c, d):
result = ( c-d )
return result
def mult(e, f):
result = ( e*f )
return result
def div(g, h):
result = ( g/h )
return result
|
import discord
from discord.ext import commands
import aiosqlite
import random
from datetime import datetime
import sqlite3
new_acc_query = """CREATE TABLE IF NOT EXISTS bank (
user_id INT(18) PRIMARY KEY,
wallet INTEGER,
bank INTEGER,
created_at VARCHAR
);"""
class accmanager(commands.C... |
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Copyright (c) 2017 FlashX, LLC
#
# 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, distrib... |
# Copyright (c) 2014 VMware, Inc. 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 b... |
from collections import deque
from antlr4 import *
from COOL import *
from src import COOLParser
class COOLClass:
def __init__(self, name: str, parent: str, created: bool, sealed: bool):
self.Name = name
self.Parent = parent
self.Created = created
self.Sealed = sealed
self.... |
import pathlib
import logging.config
from pythonjsonlogger import jsonlogger
from example.middlewares import error_middleware
PROJECT_ROOT = pathlib.Path(__file__).parent.parent
PROJECT_NAME = PROJECT_ROOT.name
DEBUG = False
INSTALLED_APPS = [
"demo",
]
DATABASES = {
'default': {
"drivername": "my... |
from contractor.tscript.runner import ExternalFunction, ParamaterError
class Constant( ExternalFunction ):
@property
def value( self ):
return 42
class Multiply( ExternalFunction ):
def __init__( self, *args, **kwargs ):
super().__init__( *args, **kwargs )
self._value = 0
def setup( self, parms... |
from . import app
from flask import render_template, request, redirect, abort
from datetime import datetime
from rfeed import *
from .syncdb import get_essay, get_all_titles, get_tag_links
from .models import get_resources_url_path, random_slogan
from .backward import OLD_TITLES
@app.errorhandler(404)
def page_not_fo... |
import os
from typing import IO
def write_file(filename: str, content: str, mode: str = "w") -> IO:
"""Save content to a file, overwriting it by default."""
with open(filename, mode) as file:
file.write(content)
return file
def read_file(filename: str, mode: str = "r") -> str:
"""Read conten... |
import numpy as np
import matplotlib.pyplot as plt
def generate_checkerboard(img_width, img_height, grid_size):
ck = np.kron([[255, 0] * int(grid_size/2), [0, 255] * int(grid_size/2)]*int(grid_size/ 2) , np.ones((int(img_height / grid_size), int(img_width/ grid_size))))
#ck = np.expand_dims(ck, axis=2)
... |
class BadDataSet(Exception):
"""Raised if data set is empty or incorrect."""
class NotReady(Exception):
"""Raised if we can't extract data yet, i.e. Scrapinghub job is not finished."""
|
# Copyright 2018 Tensorforce Team. 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 la... |
import torch
import torch.nn as nn
from models.Net import AlexNet, Uniform_D
from dataset.customData import MyCustomDataset
from loss.contrast import Contrast_Loss, Quantization_Loss
import numpy as np
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import DataLoader
from ut... |
# Copyright (c) OpenMMLab. All rights reserved.
import math
import os.path as osp
import tempfile
from mmocr.datasets.ocr_dataset import OCRDataset
def _create_dummy_ann_file(ann_file):
ann_info1 = 'sample1.jpg hello'
ann_info2 = 'sample2.jpg world'
with open(ann_file, 'w') as fw:
for ann_info i... |
import numpy as np
from numpy.linalg import matrix_power
def solve(data, days = 81):
fishes = {i:0 for i in range(-1, 9)}
for d in data:
fishes[d] += 1
for day in range(1,days):
next_fishes = {k - 1: v for k, v in fishes.items()}
for i in range(0, 8):
fishes[i] = next_... |
"""
SQLAlchemy attribute annotations
--------------------------------
Annotations are strings attached to attributes that serve as a programmer
reference on how those attributes are meant to be used. They can be used to
indicate that a column's value should be :attr:`immutable` and should never
change, or that it's a ... |
import tkinter as tk
from tkinter import *
def sel():
selection = "Data = " + str(var.get())
label.config(text = selection)
tks = tk.Tk()
var = DoubleVar()
sc = Scale( tks, variable = var )
sc.pack(anchor=CENTER)
bt = Button(tks, text="Get Scale Data", command=sel)
bt.pack(anchor=CENTER)
label = Label(tks... |
"""
======================================================================
Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)
======================================================================
This example demonstrates the different time-frequency estimation methods
on simulated data. It shows ... |
def Div(*Tags,classname="",style=""):
HtmlTagsList = [*Tags]
DivTags = ""
for ele in HtmlTagsList:
DivTags+=ele
return f"<div style='{style}' class='{classname}'>{DivTags}</div>"
|
from django.contrib import admin
from .models import Profile, Image, Rating
admin.site.site_header = "Awards Admin"
admin.site.site_title = "Awards Admin Area"
admin.site.index_title = "Welcome to Awards admin"
# Register your models here.
admin.site.register(Profile)
admin.site.register(Image)
admin.site.register(R... |
# Generated by Django 2.2.3 on 2019-07-12 06:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('aipsite', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='publickey',
name='semaster',
... |
from numpy import ones
def get_Nr(self, Time=None):
"""Create speed in function of time vector Nr
Parameters
----------
self : OutElec
An OutElec object
Time : Data
a time axis (SciDataTool Data object)
Returns
-------
Nr: ndarray
speed in function of time
... |
# -*- coding: utf-8 -*-
"""
Note that this benchmark also supports a multi-GPU setup. If you run it on
a system with multiple GPUs make sure that you kill all the processes when
killing the application. Due to the way we setup this benchmark the distributed
processes might continue the benchmark if one of the nodes is... |
def propaga(lista):
buffer_1 = []
buffer_0 = []
for index,i in enumerate(lista):
if i==1:
buffer_1.append(index)
elif i==0:
buffer_0.append(index)
else:
continue
for i in buffer_1:
if (i+1) in buffer_0:
buffer_1.a... |
# -*- coding: utf-8 -*-
import copy
import torch
from torch_geometric.utils import from_networkx
from torch_geometric.loader import DataLoader
def build_dataloader(G, set_x, set_y, batch_size, shuffle):
data = []
master_graph = from_networkx(G)
for x, y in zip(set_x, set_y):
graph = copy.de... |
from ginn.core import *
from ginn import utils
from ginn import models
|
"""Create posts table
Revision ID: 13387d511936
Revises: f54ad347fde1
Create Date: 2021-09-21 10:43:08.617429
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "13387d511936"
down_revision = "f54ad347fde1"
branch_labels = None
depends_on = None
def upgrade():
... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
... |
from typing import Any, Dict, List, Optional
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
class EventBridgeEvent(DictWrapper):
"""Amazon EventBridge Event
Documentation:
--------------
- https://docs.aws.amazon.com/eventbridge/latest/userguide/aws-events.html
"""
... |
import os
import pandas as pd
import csv
from nltk.corpus import wordnet as wn
from pyjarowinkler import distance as ds
def get_file_extension(input_file):
file_name, file_extension = os.path.splitext(input_file)
if file_extension == '.png' or file_extension == '.jpg':
return 0
elif file_extension... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from django.contrib import admin
from venue.models import Venue
admin.site.register(Venue)
|
from django.db import models
from .aluno import Aluno
from .atividadevinculada import Atividadevinculada
from .professor import Professor
from.disciplinaofertada import Disciplinaofertada
from.solicitacaomatricula import Solicitacaomatricula
class Entrega(models.Model):
#id = models.IntegerField(db_column='ID', un... |
def linearsearch(llist,key):
for i in range(len(llist)):
if llist[i]==key:
return i+1 #return the position of the key in the list
return -1 #return -1 if key not found
llist=[int(x) for x in input().split()]
key=int(input())
position=linearsearch(llist,key)
if position>0:
print(key,"fou... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from shellfoundry.utilities.standards.consts import STANDARD_NAME_KEY, VERSIONS_KEY
def standard_transformation(fetch):
def wrapper(self, **kwargs):
result = fetch(self, **kwargs)
return {i[STANDARD_NAME_KEY].lower().lstrip('cloudshell').rstrip('standard'... |
from django.db import models
from django.utils import timezone
import math
from twilio.rest import Client
class Plant(models.Model):
plantID = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
soilMoisture = models.FloatField(default=70)
temperature=models.FloatField(default=25)
humidi... |
def BFS(graph,root,k):
checked = []
visited=[]
level=[]
l=[]
l.append(root)
level.append(l)
count =0
checked.append(root)
while len(checked)>0:
v = checked.pop(0)
visited.append(v)
l=[]
for edge in graph[v]:
#l=list(set(graph[... |
import tkinter as tk
from tkinter import ttk
from time import time, localtime, strftime
class ToolTip(tk.Toplevel):
''' ToolTip widget for Tkinter '''
def __init__(self, wdgt, msg=None, func=None, delay=1.0, follow=True):
''' Initialize the ToolTip.
Arguments:
wdgt: The wi... |
import os
from fabric.contrib.files import exists
from fabric.api import run, put
CONFIG_TEMPLATES_FOLDER = 'sysconf'
def send_file(abs_path, use_sudo=True, mod='755'):
"""
send local file to remote host
"""
put(get_config_file(abs_path), abs_path, use_sudo=use_sudo)
run('sudo chmod %s %s' % (mod... |
import cv2
def empty(value): # just an empty function
pass
pathToImage = "../resources/orange-lamborghini.jpg"
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars", 640, 240)
cv2.createTrackbar("Hue Min", "TrackBars", 0, 179, empty)
img = cv2.imread(pathToImage)
"""
task: detect orange color from the image... |
import sys, signal, os
# code to handle Ctrl+C, convenience method for command line tools
def signal_handler( signal, frame ):
print( "You pressed Ctrl+C. Exiting...")
sys.exit( 0 )
signal.signal( signal.SIGINT, signal_handler )
import logging, warnings, qtmodern.styles, qtmodern.windows
from urllib.parse impor... |
#!usr/bin/env python
"""
This module contains basic configuration parameters for Mimic Analysis UI.
"""
# AXIS TOGGLES
# Default checked states for axis toggles
# You can add any axis numbers to the dictionary below that you use frequently
# e.g. 'Axis 7': True, 'Axis 9': True
AXIS_STATES = {'Axis 1': True,
... |
# -*- coding:utf-8 -*-
"""
general exception used in this module
"""
class CoinCheckApiException(Exception):
def __init__(self, message):
super(CoinCheckApiException, self).__init__(message)
|
import boto3
import logging
import cfnresponse
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
lambda_ = boto3.client('lambda')
def handler(event, context) -> str:
layer_name = str(event['ResourceProperties']['LayerName'])
try:
latest_version_arn = get_latest_layer_version(layer_name)
... |
# -*- coding: utf-8 -*-
###############################################################################
#
# MoneyReceived
# Retrieves a list of successful charge events.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
class RealSolution(object):
def __init__(self, dim):
self.f = float('nan')
self.x = np.zeros([dim, 1])
class NelderMead:
def __init__(self, dim, f, simplex, **kwargs):
self.dim = dim
self.f = f
self.sim... |
from deltasherlock_server import models
from rest_framework import serializers
class QueueItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.QueueItem
fields = ('url', 'id', 'status', 'last_updated', 'submission_time', 'result_labels')
class EventLabelSerializer(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.