text
stringlengths
2
999k
""" TensorMONK :: layers :: RoutingCapsule """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from ..activations import Activations class RoutingCapsule(nn.Module): r""" Routing capsule from Dynamic Routing Between Capsules. Implemented -- https://arxiv.org/pdf/1710.098...
import os import logging import pandas as pd from pathlib import Path logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) DIR_PATH = Path(os.path.dirname(os.path.abspath(__file__))) SINCE_PATH = DIR_PATH / Path('data/since.txt') ARTICLES_PATH = DIR_PATH / Path('data/articles.csv') def reco...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Command: .react happy|thinking|waving|wtf|love|confused|dead|sad|dog """ from telethon import events import random import asyncio @borg.on(events.NewMessage(pattern=r"\.react (.*)", outgoing=True)) async def _(event): if event.fwd_from: return input_s...
import requests from allauth.account.models import EmailAddress from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from allauth.socialaccount.m...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
import numpy as np import matplotlib.pyplot as plt from scipy.signal import hamming, hanning, triang, blackmanharris, resample import math import sys, os, time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/')) import utilFunctions as UF import hpsModel as HPS (fs,...
#!/usr/bin/env python3 from __future__ import unicode_literals from builtins import bytes, dict, list, int, float, str import argparse import json import sys import unittest from reflectrpc.client import RpcClient from reflectrpc.testing import ServerRunner server_program = None class ConformanceTest(unittest.Test...
import os # Read version from VERSION file __version__ = open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'VERSION') ).read().rstrip()
class Car(object): def __ini__(self, name, model, car_doors, car_wheels, speed = 0): if not name: self.name = "General" else: self.name = name if not model: self.model = "Gm" else: self.mo...
from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Requirement#, CreateRequirement from django.forms.models import model_to_dict # Create your views here. class RequirementIn...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opencvFaceRec.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
''' (c) University of Liverpool 2020 All rights reserved. @author: neilswainston ''' # pylint: disable=invalid-name # pylint: disable=no-member # pylint: disable=wrong-import-order from rdkit import Chem import scipy from gae.tf import train_single import numpy as np import pandas as pd def _load_data(filename): ...
import math import rospy import tf2_ros as tf2 from geometry_msgs.msg import PointStamped from bitbots_head_behavior.actions.look_at import AbstractLookAt class SearchRecentBall(AbstractLookAt): """ This action looks at the last position the ball has been seen and starts searching it from this position o...
import tkinter as tk from tkinter import ttk import re import os import wikipedia import time import webbrowser import json import requests import ctypes import youtube_dl import random import urllib import ssl from bs4 import BeautifulSoup from urllib.request import urlopen import speech_recognition as sr import reque...
import bpy holeDepth=5 holeRadius=1.5 bpy.ops.mesh.primitive_cube_add() gearHole = bpy.context.selected_objects[0] gearHole.name="GearHole" bpy.ops.transform.resize(value=(9, 14, holeDepth/2.0)) gearHole.location = (0,0,2) bpy.ops.mesh.primitive_cube_add() rightWheel = bpy.context.selected_objects[0] rightWheel.name...
""" This test module has tests relating to t-plots All functions in /calculations/tplot.py are tested here. The purposes are: - testing the user-facing API function (tplot) - testing individual low level functions against known results. Functions are tested against pre-calculated values on real isotherms. Al...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import Collection from dataclasses import dataclass, field from typing import List from omegaconf import II from...
#!/usr/bin/python3 __version__ = '0.0.1' # Time-stamp: <2021-09-25T07:39:16Z> ## Language: Japanese/UTF-8 """Simulation Buddhism Prototype No.3 x.1 - Death 死亡関連 """ ## ## Author: ## ## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese)) ## ## License: ## ## The author is a Japanese. ## ...
import random import pandas as pd import numpy as np df1 = pd.read_csv('train.csv') df2 = pd.read_csv('train.csv') df3 = pd.read_csv('train.csv') df4 = pd.read_csv('train.csv') df5 = pd.read_csv('train.csv') for i in range(0,1000000): for k in range (1,5): x = 0 # Create Pre-Flop round ...
import frappe from frappe import _ from chat.utils import validate_token, get_admin_name, get_chat_settings, get_user_settings import json @frappe.whitelist(allow_guest=True) def settings(token): """Fetch and return the settings for a chat session Args: token (str): Guest token. """ config =...
import sys from taggedtree.repl import dispatch_subcommand from os.path import expanduser def main(): fname = expanduser("~/.tt.json") cmds = tuple(sys.argv[1:]) dispatch_subcommand(fname, cmds) if __name__ == "__main__": main()
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event log = logging.getLogger('manual') class ManualTask(object): """Only execute task when specified...
""" McsPy ~~~~~ McsPy is a Python module/package to read, handle and operate on HDF5-based raw data files converted from recordings of devices of the Multi Channel Systems MCS GmbH. :copyright: (c) 2020 by Multi Channel Systems MCS GmbH :license: see LICENSE for more details """ #p...
from pythoncalculator.JMuten_divide import divide def test_divide(): assert divide(10, 2) == 5
import numpy as np def build_local_integration_grid_circle(n_quad_points, r_c): # Guass-Legendre quadrature on the unit disk (by KyoungJoong Kim and ManSuk Song) if n_quad_points == 1: w_1 = 3.141592653589793 x_1 = 0.0 quad_point_x = np.array([x_1]) * r_c quad_point_y = np.a...
#!/usr/bin/env python """ Copyright 2016 ARM Limited 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 i...
# Copyright 2013 Evan Hazlett and contributors. # # 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...
import os import codecs from setuptools import setup def read(*paths): """Build a file path from *paths* and return the contents.""" with codecs.open(os.path.join(*paths), 'r', 'utf-8') as f: return f.read() version = '0.6.1' setup( name='deezer-python', version=version, description='A...
import sys from rpython.rtyper.lltypesystem.lltype import * from rpython.translator.translator import TranslationContext from rpython.translator.c.database import LowLevelDatabase from rpython.flowspace.model import Constant, Variable, SpaceOperation from rpython.flowspace.model import Block, Link, FunctionGraph from r...
# from twilio.rest import Client # # Your Account SID from twilio.com/console # account_sid = "AC4100c72954a1f9949fc4700a8d0594bb" # # Your Auth Token from twilio.com/console # auth_token = "e1529115d0f1a57b6b8e6b17644f6087" # client = Client(account_sid, auth_token) # message = client.messages \ # .create( # ...
# # Copyright 2017 Canonical 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 in writing,...
""" .. module:: volume :synopsis: Volume Indicators. .. moduleauthor:: Dario Lopez Padial (Bukosabino) """ import numpy as np import pandas as pd from ta.utils import IndicatorMixin, ema class AccDistIndexIndicator(IndicatorMixin): """Accumulation/Distribution Index (ADI) Acting as leading indicator o...
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Customer(models.Model): """create customer model based on the default user""" user = models.OneToOneField(User, on_delete=models.CASCADE) name...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `bitmex_trio_websocket` package.""" from bitmex_trio_websocket.exceptions import BitMEXWebsocketApiError import os from random import random import pytest from async_generator import aclosing import pendulum from trio_websocket import ConnectionRejected, Web...
""" Sopan Kurkute University of Saskatchewan plotwrf.py Python 2.x Python script to plot various WRF model output. Plots are saved as PNG. example usage: plotwrf.py --infile filename.nc --sfc --tunit C --ppn -punit mm --td Will plot surface chart and dewpoint in Celcius and precipitation in mm. Use plotwrf.py -...
# Copyright 2017 Hugh Salimbeni # # 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, s...
from .. import loader import logging, random logger = logging.getLogger(__name__) def register(cb): cb(InsultMod()) class InsultMod(loader.Module): """Shouts at people""" def __init__(self): self.commands = {'insult':self.insultcmd} self.config = {} self.name = "Insulter" as...
from . import mongo_status from . import mongo_connection __all__ = [ 'mongo_status', 'mongo_connection' ]
#!/bin/env python2.7 ## SCCwatcher 2.0 ## ## ## ## sccwatcher.py ## ## ## ## Everything starts here ## ############################ import sys import re from settings_ui import * from PyQt4 import QtGui, QtCore #This is required to override the closeEvent...
class NodeDisconnectException(Exception): """This exception is thrown when Protocoin detects a disconnection from the node it is connected.""" pass
# -*- coding: utf-8 -*- ''' File name: code\cyclical_figurate_numbers\sol_61.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #61 :: Cyclical figurate numbers # # For more information see: # https://projecteuler.net/problem=61 # Problem S...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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, ...
__author__ = 'renhao.cui' import utilities from sklearn import cross_validation import combinedMapping as cm import modelUtility def alchemyTrainInfer(alchemy_train, alchemy_test, label_train, label_test, trainProbFlag): # model from A to B: model[A] = {B: score} (model, cand, candProb) = cm.mappingTrainer4(al...
"""Tests for perfkitbenchmarker.providers.aws.aws_dynamodb.""" import json import unittest from absl import flags from absl.testing import flagsaver from absl.testing import parameterized import mock from perfkitbenchmarker import errors from perfkitbenchmarker.providers.aws import aws_dynamodb from perfkitbenchmarke...
# coding: utf-8 from __future__ import absolute_import # import models into model package from huaweicloudsdkcloudpipeline.v2.model.batch_show_pipelines_status_request import BatchShowPipelinesStatusRequest from huaweicloudsdkcloudpipeline.v2.model.batch_show_pipelines_status_response import BatchShowPipelinesStatusR...
import pytest import os import sys import json from click.testing import CliRunner from ...cli.main import cli from ...core.project import Project remotetest = pytest.mark.skipif('TEST_DSBFILE' not in os.environ, reason="Environment variable 'TEST_DSBFILE' is required") def get_te...
import unittest from queue import Queue from modi.module.input_module.ir import Ir class TestIr(unittest.TestCase): """Tests for 'Ir' package.""" def setUp(self): """Set up test fixtures, if any.""" self.send_q = Queue() mock_args = (-1, -1, self.send_q) self.ir = Ir(*mock_ar...
from datetime import timedelta import logging from django.apps import apps as django_apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.contrib.auth import get_user_model from django.db import transaction from django.utils import timezone from django.utils.module...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
# orm/strategies.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """sqlalchemy.orm.interfaces.LoaderStrategy implementations, and related Mappe...
from PyQt5.QtCore import pyqtSignal, QObject, pyqtSlot from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLineEdit, QLabel, QPushButton, QGroupBox, QSizePolicy, \ QFormLayout, QWidget, QCheckBox class MainFunctionAbstract(QGroupBox): send_data = pyqtSignal(str, dict) flag_update_signal = pyqtSignal(s...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Video.upload_url' db.add_column('videos_video', 'upload_url', self.gf(...
# -*- coding: utf-8 -*- ################################################################################ # Copyright (c), AiiDA team and individual contributors. # # All rights reserved. # # This file is part of the AiiDA-wannier90 code. ...
import torch.nn as nn from collections import OrderedDict class C1(nn.Module): def __init__(self): super(C1, self).__init__() self.c1 = nn.Sequential(OrderedDict([ ('c1', nn.Conv2d(1, 6, kernel_size=(5, 5))), ('relu1', nn.ReLU()), ('s2', nn.MaxPool2d...
#! /usr/bin/env python """API Wrapper for Bitcoin.de Trading API.""" import requests import time import json import hmac import hashlib import logging import codecs import decimal import inspect import urllib from future.standard_library import install_aliases install_aliases() from urllib.parse import urlencode lo...
ply_header = '''ply format ascii 1.0 element vertex %(vert_num)d property float x property float y property float z property uchar red property uchar green property uchar blue end_header ''' class PLY_Manip: def __init__(self, results_dir): self.dir = results_dir def insert_header(self, point_cl...
from ..de import Provider as AddressProvider class Provider(AddressProvider): city_formats = ('{{city_name}}', ) city_with_postcode_formats = ('{{postcode}} {{city}}', ) street_name_formats = ( '{{first_name}}-{{last_name}}-{{street_suffix_long}}', '{{last_name}}{{street_suffix_short}}'...
import discord from discord.ext import commands from discord.ext.commands import has_permissions, MissingPermissions import datetime import json class Kickban(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.has_permissions(kick_members=True) async def kick(...
import os import requests import shutil from download_util import download_file THIS_FILE_PATH = os.path.abspath(__file__) BASE_DIR = os.path.dirname(THIS_FILE_PATH) DOWNLOADS_DIR = os.path.join(BASE_DIR, "downloads") os.makedirs(DOWNLOADS_DIR, exist_ok=True) downloaded_img_path = os.path.join(DOWNLOADS_DIR, '1.jpg') ...
#!/usr/bin/env python3 """ Scripts to drive a donkey 2 car Usage: manage.py (drive) [--model=<model>] [--js] [--type=(linear|categorical)] [--camera=(single|stereo)] [--meta=<key:value> ...] [--myconfig=<filename>] manage.py (train) [--tubs=tubs] (--model=<model>) [--type=(linear|inferred|tensorrt_linear|tflit...
N, Q = map(int, input().split()) S = input() items = [] for i in range(Q): items.append(tuple(map(int, input().split()))) from itertools import accumulate prev = "" acc = [0] * N for i, s in enumerate(S): if s == "C" and prev == "A": acc[i] = 1 prev = s acc = list(accumulate(acc)) ans = [] for i ...
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="cone.colorbar.title.font", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name...
from __future__ import unicode_literals from sqlalchemy import Column from sqlalchemy import Unicode from sqlalchemy import Boolean from sqlalchemy.orm import relationship from .base import DeclarativeBase from .base import UTCDateTime from .base import now_func class Company(DeclarativeBase): """A Company is b...
import subprocess import sys import os DEFAULT_ARGS=[] if (os.path.exists("build")): dl=[] for r,ndl,fl in os.walk("build"): r=r.replace("\\","/").strip("/")+"/" for d in ndl: dl.insert(0,r+d) for f in fl: os.remove(r+f) for k in dl: os.rmdir(k) else: os.mkdir("build") if (os.name=="nt"): cd=os...
from django.apps import AppConfig class LostfoundConfig(AppConfig): name = 'lostfound'
"""rnn.py ~~~~~~~~~~~~~~ Written by Yong Yu Wen, 2018 (Built using tensorflow-gpu 1.6.0) A TensorFlow-based many-to-one recurrent neural network specifically for the classification of MBTI types based on social media posts. Raw un-processed dataset used for this task can be found at https://www.kaggle.com/da...
#!/usr/bin/env python3 # Copyright (c) 2016-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
import logging from django.apps import apps from django.conf import settings from zconnect import zsettings from zconnect.util.general import load_from_module logger = logging.getLogger(__name__) class Sender: """Abstract interface for sending messages to devices This will pass a generic Message to the s...
# -*- coding: utf-8 -*- import pytest from h.models import Organization from h.services.list_organizations import ( ListOrganizationsService, list_organizations_factory, ) from h.services.organization import organization_factory class TestListOrganizations: def test_returns_organizations_from_all_author...
import h5py import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import keras import h5py import numpy as np from keras.layers import Input, Dense, Conv1D, MaxPooling2D, MaxPooling1D, BatchNormalization from keras.layers.core import Dropout, Activation, Flatten from keras.layers.merge import...
''' Created on Nov 29, 2020 @author: manik ''' ''' File with classes and code which control how a particular person will move and to where ''' from src.population import Population import numpy as np import src.person_properties_util as idx class Movement(): """ Class providing abstraction into each movement o...
import os import urllib.request from osgeo import ogr from mapswipe_workers.definitions import DATA_PATH, CustomError, logger from mapswipe_workers.project_types.arbitrary_geometry import grouping_functions as g from mapswipe_workers.project_types.arbitrary_geometry.group import Group from mapswipe_workers.project_ty...
# 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...
# coding=utf8 # Copyright 2018 JDCLOUD.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 obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# Copyright 2020 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, ...
from appdirs import user_log_dir import os import logging.handlers # Normal base logging directory name log_directory_name = "irida-uploader" # When running tests, the Makefile creates an environment variable IRIDA_UPLOADER_TEST to 'True' # If it exists then we are running a test and should be logging to the test log...
# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101,W0141 import datetime import itertools import nose from numpy.random import randn import numpy as np from pandas.core.index import Index, MultiIndex from pandas import Panel, DataFrame, Series, notnull, isnull, Timestamp from pandas.util.testing import (asser...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
from flask import send_file from python_helper import Constant as c from python_helper import EnvironmentHelper, log from python_framework import ResourceManager, FlaskUtil, HttpStatus, LogConstant from queue_manager_api import QueueManager import ModelAssociation app = ResourceManager.initialize(__name__, ModelAss...
from fastapi import FastAPI from starlette.testclient import TestClient app = FastAPI() @app.put("/items/{item_id}") def save_item_no_body(item_id: str): return {"item_id": item_id} client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": {"title": "Fast API", "version": "0.1.0"}, ...
import threading from Utils.Utils_function import logMsg from Sharing.Sharing import sharing1ES, sharing2ES from Reconstruction.Reconstruction import reconstructionES1, reconstructionES2 from groups import parametres par = parametres() PATH_DATA_USERS = par.PATH_DATA_USERS CHAR_DATA_SPLIT = par.CHAR_DATA_SPLIT CHAR_M...
from plotly.basedatatypes import BaseTraceHierarchyType import copy class Tickfont(BaseTraceHierarchyType): # color # ----- @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string ...
from django.urls import path from .views import CriarInscricaoIndividual, CriarInscricaoColetiva urlpatterns = [ path('criarinscricaoindividual', CriarInscricaoIndividual, name='criar-inscricao-individual'), path('criarinscricaocoletiva',CriarInscricaoColetiva, name='criar-inscricao-coletiva'), ]
# Generated by Django 3.1.1 on 2020-10-09 12:30 from django.db import migrations class Migration(migrations.Migration): initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_length"), ] operations = [ migrations.CreateModel( name="GlobalPermission", ...
from collections import OrderedDict __author__ = 'kevin' import socket from threading import Lock class LithiumHelper(object): @staticmethod def recv_all(sock): read = '' try: data = sock.recv(1024) read += data except socket.error, e: if isinstance(...
#Author:Azrael import sys from PyQt5.QtWidgets import QApplication, QDialog, QStackedWidget,QListWidget,\ QTextEdit,QVBoxLayout,QListWidgetItem class MainPage(QDialog): def __init__(self, parent=None): super(MainPage, self).__init__(parent) self.initUI() def initUI(self): self.se...
# Copyright Ryan-Rhys Griffiths and Aditya Raymond Thawani 2020 # Author: Ryan-Rhys Griffiths """ Property prediction on the photoswitch dataset using Random Forest. """ import argparse import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from skle...
""" Tests the execution of forum notification tasks. """ import json import math from datetime import datetime, timedelta from unittest import mock import ddt from django.contrib.sites.models import Site from edx_ace.channel import ChannelType, get_channel_for_message from edx_ace.recipient import Recipient from edx...
from schematics.types import DictType, ListType, ModelType, PolyModelType, StringType from spaceone.inventory.connector.aws_sqs_connector.schema.data import QueData from spaceone.inventory.libs.schema.resource import CloudServiceMeta, CloudServiceResource, CloudServiceResponse from spaceone.inventory.libs.schema.dynami...
from dateutil.relativedelta import relativedelta from django.http import StreamingHttpResponse from django.utils import timezone from rest_framework import viewsets from rest_framework.settings import api_settings from .files import FileRenderCN, FileRenderEN from .models import CyclecountModeDayModel from . import ser...
from random import randint class Die(): def __init__(self, sides): self.sides = sides def roll_die(self): print(randint(1,self.sides))
#!/usr/bin/env python import json import os import shutil import subprocess import sys import tempfile # Utilities def listify(x): if type(x) == list or type(x) == tuple: return x return [x] def check_call(cmd, **args): if type(cmd) != list: cmd = cmd.split() print('running: %s' % cmd) subprocess...
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from turtlesim/Pose.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class Pose(genpy.Message): _md5sum = "863b248d5016ca62ea2e895ae5265cf9" _type = "turtlesim/Pose" ...
from __future__ import print_function import errno import os from PIL import Image import torch import torch.nn as nn import re import json import pickle as cPickle import numpy as np import utils import h5py import operator import functools from torch._six import string_classes import torch.nn.func...
# -*- coding: utf-8 -*- from django.conf import settings # modify reversions to match our needs if required... def reversion_register(model_class, fields=None, follow=(), format="json", exclude_fields=None): """CMS interface to reversion api - helper function. Registers model for reversion only if reversion...
#!/usr/bin/env python3 # # Copyright (c) 2021, NVIDIA CORPORATION. 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 # # ...
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Marker(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "box" _path_str = "box.marker" _valid_props = {"color", "line", "opacity", "outliercolor", "s...
# -*- coding: utf-8 -*- """Node grouping utilities.""" from collections import defaultdict from typing import Callable, Iterable, List, Mapping, Optional, Set, TypeVar from pybel import BELGraph, BaseEntity from pybel.constants import ANNOTATIONS, HAS_VARIANT, IS_A, ORTHOLOGOUS, PART_OF, RELATION from pybel.dsl impo...
""" This file offers the methods to automatically retrieve the graph Yersinia pestis CO92. The graph is automatically retrieved from the STRING repository. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime: 2021-0...
import string def z_array(s): # NOTE: # Use Z algorithm (Gusfield theorem 1.4.1) to preprocess s. assert len(s) > 1 z = [len(s)] + [0] * (len(s) - 1) # Initial comparison for s[1:] with prefix for i in range(1, len(s)): if s[i] == s[i - 1]: z[1] += 1 else: ...