content
stringlengths
5
1.05M
from flask import Flask, render_template,request,redirect,url_for # For flask implementation from bson import ObjectId # For ObjectId to work from pymongo import MongoClient import os app = Flask(__name__) title = "TODO with Flask" heading = "ToDo Reminder" @app.route("/") return "Hello World!" # define for IIS mod...
from rest_framework import serializers from dateflix_api.models import Movie class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ["id", "title", "netflix_url", "image", "description"]
import os import pprint import jsonref import numpy as np import cv2 import pydicom from pathlib import Path from logs import logDecorator as lD # ---------------------------------- config = jsonref.load(open("../config/config.json")) logBase = config["logging"]["logBase"] + ".modules.cropPreprocessing.cropPreprocess...
import os import sys root_path = os.path.abspath(os.path.dirname(__file__)).split('src') sys.path.extend([root_path[0] + 'src']) from sequence_process.DPCP import DPCP import numpy as np from sequence_process.sequence_process_def import get_cell_line_seq names = ['GM12878', 'HeLa-S3', 'HUVEC', 'IMR90', 'K562', 'NHEK...
from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin from flask_dance.consumer.storage.sqla import OAuthConsumerMixin from werkzeug.security import generate_password_hash, check_password_hash db = SQLAlchemy() class User(UserMixin, db.Model): __tablename__ = 'users' id = db....
from setuptools import setup, find_packages version = '1.0.11' setup(name='holland.lib.lvm', version=version, description="LVM support", long_description="""\ """, keywords='holland lib lvm', author='Rackspace', author_email='[email protected]', url='http:/...
# -*- coding: utf-8 -*- ############################################################################# # _________ ____________ ___ # # / _____// _____/\ \/ / ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # \_____ \/ \ ___ \ / THE E(X)TENDED (S)ELFISH (G)E...
import os, gnupg, time, ConfigParser class encrypt: def __init__(self): self.gpg = gnupg.GPG() self.key_data = open('backup_key.asc').read() self.import_result = self.gpg.import_keys(self.key_data) print(self.import_result.results) ...
from setuptools import setup, find_packages VERSION = '1.1.0' DESCRIPTION = 'The package allows to download, process and visualize climatological data from reliable sources' README = open('README.md', 'r', encoding='utf8').read() setup( name='cloupy', version=VERSION, description=DESCRIPTION, long_des...
# Distributed under MIT License # Copyright (c) 2021 Remi BERTHOLET """ Temperature homekit accessory """ from homekit import * class TemperatureSensor(Accessory): """ Temperature homekit accessory """ def __init__(self, **kwargs): """ Create temperature accessory. Parameters : name(string), temperature(float) and...
import sys sys.path.insert (0, '..') import unittest from categorizer_service import get_categorizer from constants import KNOWN_CATEGORIES class CategorizerServiceTest(unittest.TestCase): def tests_categorizer_returns_a_known_category(self): categorizer = get_categorizer() sample_product = { ...
import logging import argparse import os import shutil import yaml import glob import hashlib import errno import tarfile logging.getLogger("paramiko").setLevel(logging.WARNING) logger = logging.getLogger("deploy") deploy_modules = ['framework', 'common', 'controller', 'agent'] class mapconnect(object): SSHOPTIO...
from operator import and_, not_, or_, xor from typing import Dict, Iterator from parse_2d import Diagram, Index, TinyTokenizer, tokenize from samples.circuit_diagram.ast import OpNode __all__ = ["parse_logic_gates"] nand = lambda a, b: not a & b nor = lambda a, b: not a | b xnor = lambda a, b: not a ^ b const_0 = la...
from setuptools import find_packages, setup setup( name="yalexs", version="1.1.17", python_requires=">=3.6", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: Eng...
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class ParcelServiceType(Document): pass def match_parcel_service_type_alias(parcel_service_type, pa...
import marso def issues(code): grammar = marso.load_grammar() module = marso.parse(code) return grammar._get_normalizer_issues(module) def test_eof_newline(): def assert_issue(code): found = issues(code) assert len(found) == 1 issue, = found assert issue.code == 292 ...
from __future__ import division from functools import partial import numpy as np from menpofit.fitter import raise_costs_warning from menpofit.math import IRLRegression, IIRLRegression from menpofit.result import euclidean_bb_normalised_error from menpofit.sdm.algorithm.base import (BaseSupervisedDescentAlgorithm, ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not s or not t: return False ...
""" Contains custom asserts """ from ei_graph import EIGraph def assert_node_is_item(nodeId): if not EIGraph.nid_is_item(nodeId): raise ValueError( "Invalid item id: %d. Item ids are even." % nodeId ) def assert_node_is_entity(nodeId): if not EIGraph.nid_is_entity(nodeId): ...
# -*-coding:utf-8-*- print('hello world')
import numpy as np from cpymad.madx import Madx import xline # run MADX tests mad = Madx() mad.call("rf_multipole.madx") # create xline rfmultipole mad_sequence = mad.sequence["sequ_rfmultipole"] rf_mulitpole_mad = mad_sequence.elements[1] freq = rf_mulitpole_mad.freq * 1e6 # MAD units are MHz knl = rf_mulitpole_ma...
#!/usr/bin/env python3 # remove-duplicates.py: remove tweets with identical text from stdin # usage: remove-duplicates.py < file # 20201113 erikt(at)xs4all.nl import csv import re import sys seen_text = {} csvreader = csv.reader(sys.stdin) csvwriter = csv.writer(sys.stdout) for row in csvreader: text = row[4] ...
# Get information about the process's memory usage. Ideally this would just # be some simple calls to resource, but that library is almost useless. The # python standard library is usually good, but here it's terrible. # If we wanted to introduce an external dependency we could try psutil, # though I would avoid it if ...
import sys sys.path.append('../') import boto s3_conn = boto.connect_s3() import multiprocessing cores = multiprocessing.cpu_count() import pandas as pd from skills_utils.time import datetime_to_quarter from skills_ml.job_postings.common_schema import JobPostingGenerator from skills_ml.job_postings.corpora import D...
import os SORTS_DIR = os.path.join(os.path.dirname(__file__), 'sorts') TITLE = 'Python AlgoAnim'
# Generated by Django 3.1.1 on 2021-02-25 17:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ColDocApp', '0005_20201013_latex_macros'), ] operations = [ migrations.RemoveField( model_name='dcoldoc', name='editor', ...
VERSION = 0.1 print(f"VGE {VERSION}")
""" library to take autodiff and execute a computation graph """ from __future__ import absolute_import import numpy as np # import scipy.sparse from scipy.sparse import spmatrix, coo_matrix from .. import ndarray from .._base import DNNL_LIB from ..cpu_links import array_set as cpu_array_set from .Variable import Plac...
#!/usr/bin/env python ''' Gamma point Hartree-Fock/DFT for all-electron calculation The default FFT-based 2-electron integrals may not be accurate enough for all-electron calculation. It's recommended to use MDF (mixed density fitting) technique to improve the accuracy. See also examples/df/00-with_df.py examples/d...
from django.shortcuts import render, get_object_or_404 from .models import Listing from django.core.paginator import Paginator, EmptyPage from .choices import _price, _states, _bedroom # Create your views here. def index(request): # return render(request, 'listings/listings.jinja2', { # 'name': 'Machado...
import argparse import errno import time from io import StringIO from pavilion import arguments from pavilion import commands from pavilion import plugins from pavilion.unittest import PavTestCase class CancelCmdTests(PavTestCase): def setUp(self): plugins.initialize_plugins(self.pav_cfg) def tearD...
__author__ = "MetaCarta" __copyright__ = "Copyright (c) 2006-2008 MetaCarta" __license__ = "Clear BSD" __version__ = "$Id: SQLite.py 606 2009-04-24 16:25:41Z brentp $" import re import copy from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from vectorformats.Formats import WKT...
import os import shutil from pathlib import Path from timeit import default_timer as timer import h5py import librosa import numpy as np import pandas as pd import torch from methods.data import BaseDataset, collate_fn from torch.utils.data import DataLoader from tqdm import tqdm from utils.common import float_samples...
from __future__ import absolute_import # development system imports import datetime import os import random import uuid from datetime import date, timedelta from decimal import Decimal from hickup.users.managers import UsersManager # from django.db.models.fields.related import ManyToManyField # Third partie impor...
#!/usr/bin/env python from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import os import sys import re import json import argparse import traceback import socket # python 2 and 3 version compatibility if sys.version_inf...
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 8 12:47:46 2018 TODO: Convert this all to a class! @author: amirbitran """ import numpy as np import matplotlib.pyplot as plt import joblib class Kinetic_model: def __init__(self, protein_name, lengths, rates=[], connectivity=[], Tempe...
from django.shortcuts import render def index(request): return render(request, 'homepage/home.html') def about(request): return render(request, 'homepage/about.html') def signup(request): return render(request, 'homepage/signup.html') def signin(request): return render(request, 'homepage/signin.html...
from django.contrib import admin from django.core.exceptions import ValidationError from django.forms import ModelForm from django.utils.translation import ugettext as _ from freq.models import * admin.site.register(Client) admin.site.register(ProductArea) class FeatureRequestAdminForm(ModelForm): def clean_prio...
# -*- coding: utf-8 -*- from django.conf.urls import url from Instanssi.admin_base.views import index app_name = "admin_base" urlpatterns = [ url(r'^$', index, name="index"), ]
import json import argparse def write_jsonl(data, path): with open(path, 'w') as f: for example in data: json_data = json.dumps(example) f.write(json_data + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_path', required=True) parser.add_argument('...
from dataclasses import dataclass @dataclass(frozen=True) class Item: quantity: float measure: str name: str price: float def __str__(self): # ' 2 grain rice @ $1.0...$2.0' return f' {self.quantity} {self.measure} {self.name} @ ${self.price:.1f}...${self.price * ...
from numpy.testing.utils import assert_equal from kernel_exp_family.tools.xvalidation import XVal import numpy as np def test_xval_execute_no_shuffle(): x = XVal(N=10, num_folds=3, shuffle=False) for train, test in x: print train, test def test_xval_execute_shuffle(): x = XVal(N=10, num_fol...
import random import h5py import numpy as np from torch.utils.data import Dataset class TrainDataset(Dataset): def __init__(self, h5_file, patch_size, scale): super(TrainDataset, self).__init__() self.h5_file = h5_file self.patch_size = patch_size self.scale = scale @staticmet...
import factory from wallet.models import MINIMUM_ACCOUNT_BALANCE, Wallet class WalletFactory(factory.django.DjangoModelFactory): class Meta: model = Wallet django_get_or_create = ('name',) name = factory.Sequence(lambda n: "Wallet_%03d" % n) balance = MINIMUM_ACCOUNT_BALANCE
# crie um modulo moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). # faça tmb um programa que importe esse modulo e use algumas dessas funções def aumentar(v, p): res = v + (p*v)/100 return res def diminuir(v, p): res = v - (p*v)/100 return res def metade(v): ...
""" Main postgrez module """ import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import psycopg2 from .utils import read_yaml, IteratorFile, build_copy_query from .exceptions import (PostgrezConfigError, PostgrezConnectionError, PostgrezExecuteError, Post...
import azure.cognitiveservices.speech as speechsdk def get_text_from_input(input_audio_filename, speech_config): # Creates an audio configuration that points to an audio file. # Replace with your own audio filename. audio_input = speechsdk.AudioConfig(filename=input_audio_filename) # Creates a recogni...
import contextlib from collections.abc import Callable, Hashable, Iterable, Iterator from functools import partial from itertools import chain from types import SimpleNamespace from typing import Any, Optional, TypeVar, Union import attr from .lfu import LFU from .lru import LRU __all__ = [ "lru_cache_with_key"...
""" BOSH Client ----------- Based on https://friendpaste.com/1R4PCcqaSWiBsveoiq3HSy """ import gzip import socket import base64 import httplib import logging import StringIO from random import randint from urlparse import urlparse from xml.etree import ElementTree as ET from puresasl.client import SASLClient try...
from .group import Group from .node import Node __all__ = ["Node", "Group"]
# Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран final_mlt = 1 for number in range(1,11): final_mlt = final_mlt * number print('multiplication of {:*^d} numbers is {:*^d}'.format(number,final_mlt)) print('\nThe multiplication of all numbers from 1 to 10 is: {:d}'.format(final_ml...
from django.contrib.auth import get_user_model from django import forms from django.template.defaultfilters import slugify from djafforum.models import ForumCategory, Topic, Comment User = get_user_model() class CategoryForm(forms.ModelForm): class Meta: model = ForumCategory exclude = ('slug',...
import argparse import csv import glob import os import sys import random import numpy import torch from bokeh import plotting from PIL import Image from scipy.cluster.vq import kmeans, whiten from torchvision import transforms def my_function(x): t = [None] * 3 t[0] = x[0, :, :].add(10) t[1] = x[1, :, :...
# task 1 - "Fraction class" # implement a "fraction" class, it should provide the following attributes: # the class should offer suitable attributes to use the print and float functions. should ensure check that the values provided to _self_ are integers and respond with a suitable error message if they are...
# coding:utf-8 from user import User from privilege import Privileges class Admin(User): def __init__(self, first_name, last_name, **describes): super().__init__(first_name, last_name, **describes) self.privileges = ['add', 'delete', 'modify', 'inquire'] self.privilege = Privileges() ...
import json import unittest from unittest import mock from hexbytes.main import HexBytes from web3.utils.datastructures import AttributeDict from pyetheroll.constants import ChainID from pyetheroll.transaction_debugger import (TransactionDebugger, decode_contract_call) c...
from matplotlib import pyplot as plt import cv2 import matplotlib import os import random import torch from torch.autograd import Variable import torchvision.transforms as standard_transforms import misc.transforms as own_transforms import pandas as pd import glob from models.CC import CrowdCounter from config import ...
"""Subpackage logs.""" from . import log_operator
topic_model.visualize_barchart(topics=[0,1,2,3,4,5])
'''program to estimate the generalization error from a variety of AVMs Determine accuracy on validation set YYYYMM of various hyperparameter setting for elastic net. INVOCATION python val.py YYYYMM [-test] INPUT FILE: WORKING/samples-train-validate.csv OUTPUT FILE: WORKING/linval/YYYYMM.pickle ''' from __fut...
from django.contrib import admin from reports.models import Machine, MunkiReport class MachineAdmin(admin.ModelAdmin): list_display = ('hostname', 'mac', 'username', 'last_munki_update', 'last_inventory_update') class MunkiReportAdmin(admin.ModelAdmin): list_display = ('hostname', 'mac...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import syft as sy # Set everything up hook = sy.TorchHook(torch) alice = sy.VirtualWorker(id="alice", hook=hook) bob = sy.VirtualWorker(id="bob", hook=hook) james = sy.VirtualWorker(id="james", hook=hook) # A Toy Dataset d...
# 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. import os #os.environ["PYOPENGL_PLATFORM"] = "egl" import numpy as np from scipy.spatial.transform import Rotation as R import pyrender import ...
import docker import os, sys, yaml, copy, string, StringIO import maestro, template, utils from requests.exceptions import HTTPError from .container import Container class ContainerError(Exception): pass class Service: def __init__(self, conf_file=None, environment=None): self.log = utils.setupLogging() s...
from collections import namedtuple DB2Feature = namedtuple('DB2Feature', [ "dbCapacity", "dbVersion", "instanceName", "productName", "dbName", "serviceLevel", "instanceConn", "instanceUsedMem", "dbConn", "usedLog", "transcationInDoubt", "xlocksEscalation", "locksEsca...
from __future__ import absolute_import import logging import itertools from typing import List, Dict, Optional, Union from overrides import overrides from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data import Instance from allennlp.data.tokenizers import Token from allennlp.data.t...
# -*- coding: utf-8 -*- from django.conf.urls import url, include from . import views from rest_framework import routers routers = routers.DefaultRouter() routers.register('problem', views.ProblemView) routers.register('problemdata', views.ProblemDataView) routers.register('problemtag', views.ProblemTagView) urlpatte...
from __future__ import print_function from pylearn2.devtools.run_pyflakes import run_pyflakes __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" de...
import nagisa from seqeval.metrics import classification_report def main(): ner_tagger = nagisa.Tagger( vocabs='data/kwdlc_ner_model.vocabs', params='data/kwdlc_ner_model.params', hp='data/kwdlc_ner_model.hp' ) fn_in_test = "data/kwdlc.test" test_X, test_Y = nagisa.utils.load...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-22 05:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parkstay', '0012_campsiterate_update_level'), ] operations = [ migrations.C...
"""Test the frigate binary sensor.""" from __future__ import annotations import logging from typing import Any from unittest.mock import AsyncMock import pytest from pytest_homeassistant_custom_component.common import async_fire_mqtt_message from custom_components.frigate.api import FrigateApiClientError from custom...
# import cv2 as cv import numpy as np import matplotlib.pyplot as plt # def do_canny(frame): # gray = cv.cvtColor(frame, cv.COLOR_RGB2GRAY) # blur = cv.GaussianBlur(gray, (5, 5), 0) # canny = cv.Canny(blur, 50, 150) # return canny def do_segment(frame): # Since an image is a multi-directional arra...
from nose.tools import eq_ from mozillians.common.tests import TestCase from mozillians.users.models import IdpProfile, UserProfile from mozillians.users.tests import UserFactory from mozillians.phonebook.utils import get_profile_link_by_email class UtilsTests(TestCase): def test_link_email_by_not_found(self): ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
# coding: utf-8 """ 3Di API 3Di simulation API (latest version: 3.0) Framework release: 1.0.16 3Di core release: 2.0.11 deployed on: 07:33AM (UTC) on September 04, 2020 # noqa: E501 The version of the OpenAPI document: 3.0 Contact: [email protected] Generated by: https://openapi-gen...
import os from datetime import datetime from werkzeug.utils import secure_filename import app from app.base.models import FileInputStorage from app.SendStatements import blueprint from flask import render_template, request, redirect, flash from flask_login import login_required from config import * @blueprint.route...
# # HELLO ROUTES # from main import app @app.route('/hello', methods=['GET']) def get_hello(): return "Hello" @app.route('/goodbye', methods=['GET']) def get_goodbye(): return "Goodbye"
#!/usr/bin/python # coding=utf-8 from __future__ import with_statement try: import json json # workaround for pyflakes issue #13 except ImportError: import simplejson as json import subprocess from test import CollectorTestCase from test import get_collector_config from test import unittest from mock i...
from django.urls import path from crash_course import views from django.contrib.auth.decorators import login_required urlpatterns = [ path('courses', views.CrashCourseList.as_view()), path('course/<str:course_slug>/chapters', views.CourseChapterList.as_view()), path('course/<str:course_slug>/chapter/<str:c...
from app import socketio from flask.ext.socketio import emit from models import vehicles, tokens #Clean up / replace with Victors "Garage" stuff. def find_user_vehicles(email): for id, token in tokens.items(): if token['email'] == email: print('found user ', email) try: ...
# This example checks the current criteria of the active LOD object 'op'. # If it is "User LOD Level" the current level is set to the maximum level. import c4d # get current criteria from active LOD object criteria = op[c4d.LOD_CRITERIA] # check if User LOD Level if criteria == c4d.LOD_CRITERIA_MANUAL: # get max...
from django.conf import settings from django.http import HttpResponse from django.shortcuts import render import os from .models import * def home(request, game_name=None): filtered_game = None context = {} if settings.DEBUG: context["debug"] = ( f'< DB_HOST="{settings.DATABASES["de...
import discord import json import os import requests from discord.ext import commands, tasks from dotenv import load_dotenv from itertools import cycle from function import * #地震 load_dotenv() bot = commands.Bot(command_prefix = '-') status = cycle(['請使用:-help 查看指令','Python好難QQ','努力學習Python中']) bot.remove_command('...
# -*- coding: utf-8 -*- # Copyright (c) 2010-2016, MIT Probabilistic Computing Project # # 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/LICENS...
from django.apps import AppConfig class FHIRAppConfig(AppConfig): name = 'corehq.motech.fhir' def ready(self): from . import signals # noqa # pylint: disable=unused-import from . import serializers # noqa # pylint: disable=unused-import
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") # this just takes one arguement def print_one(arg1): ...
#!/usr/bin/env python3 ''' Developed with <3 by the Bishop Fox Continuous Attack Surface Testing (CAST) team. https://www.bishopfox.com/continuous-attack-surface-testing/how-cast-works/ Author: @noperator Purpose: Determine the software version of a remote PAN-OS target. Notes: - Requires version-table.tx...
#!/usr/bin/python # DQN implementation of https://github.com/matthiasplappert/keras-rl for Keras # was used with epsilon-greedy per-episode decay policy. import numpy as np import gym from gym import wrappers from tfinterface.utils import get_run from tfinterface.reinforcement import DQN, ExpandedStateEnv import rand...
import numpy as np print("Hoi","lekkkkahh") def surface_area(r): return np.pi*r**2 def circumference(r): return 2*np.pi*r #print("Circumference of circle with radius 1: ", circumference(1)) #print("Surface area of circle with radius 1: ", surface_area(1))
import numpy as np import pylab import mahotas as mh import search import image_split as split import UI import time """ f = open('sample.txt','w') for i in range(len(label)): f.write(' '.join(str(x) for x in label[i])+'\n') pylab.show() """ count = 0 while count <6: count+=1 RECT =UI.getOrigin() pi...
from .SdsBoundaryType import SdsBoundaryType from .SdsNamespace import SdsNamespace from .SdsSearchMode import SdsSearchMode from .SdsStream import SdsStream from .SdsExtrapolationMode import SdsExtrapolationMode from .SdsInterpolationMode import SdsInterpolationMode from .SdsStreamIndex import SdsStreamIndex from .Sds...
from sys import stdin def island(m): cont = 0 for i in range(len(m)): for j in range(len(m[0])): if m[i][j] == 1: cont += 4 if j > 0 and m[i][j - 1]: cont -= 2 if i > 0 and m[i - 1][j]: cont -= 2 re...
""" Testing package info """ import nibabel as nib def test_pkg_info(): """Simple smoke test Hits: - nibabel.get_info - nibabel.pkg_info.get_pkg_info - nibabel.pkg_info.pkg_commit_hash """ info = nib.get_info()
from django.db import models class KeyValueManager(models.Manager): def create_batch(self, **keys): return [ self.create(key=key, value=value) for key, value in keys.items() ] class KeyValue(models.Model): key = models.CharField(max_length=32, unique=True) value =...
import numpy as np class PointFeatureEncoder(object): def __init__(self, config, point_cloud_range=None): super().__init__() self.point_encoding_config = config assert list(self.point_encoding_config.src_feature_list[0:3]) == ['x', 'y', 'z'] self.used_feature_list = self.point_enco...
import h5py import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import argparse import os parser = argparse.ArgumentParser(description='Plot matching evaluation results') parser.add_argument('results_path', help='matching results file, source bag file, or working directory') a...
# Copyright (c) 2019 The Regents of the University of California. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this li...
def foo(a: float, b: float, c: float, d: float, cache=set()): cache.update([a, b, c, d]) return sum([a, b, c, d])/4, max(cache)
"""EnvSpec class.""" from garage import InOutSpec class EnvSpec(InOutSpec): """Describes the action and observation spaces of an environment. Args: observation_space (akro.Space): The observation space of the env. action_space (akro.Space): The action space of the env. """ def __in...