content
stringlengths
5
1.05M
from ztag.annotation import * class WindowsMEI(Annotation): protocol = protocols.MODBUS subprotocol = protocols.MODBUS.DEVICE_ID port = None def process(self, obj, meta): product_code = obj["mei_response"]["objects"]["product_code"].lower() if product_code.startswith("win"): ...
import asyncio import aiohttp import json from datetime import datetime async def get_json(client, url): async with client.get(url) as response: assert response.status == 200 return await response.read() async def get_reddit_top(subreddit, client, num_posts): data = await get_json(client, 'h...
import pulsar as psr def load_ref_system(): """ Returns l-methionine as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 0.9150 -0.8621 -0.5784 N 2.3355 -0.4447 -0.6037 C 0.02...
import numpy as np import mxnet as mx from mxnet import nd from mxnet.gluon.data import DataLoader from rdkit import Chem import utils from mx_mg.data import data_struct __all__ = ['MolLoader', 'MolRNNLoader', 'CMolRNNLoader'] class MolLoader(DataLoader): """Load graph based molecule representation from SMILES"...
#!/usr/bin/env python3 """ Import the physical tile information from Project X-Ray database files. Project X-Ray specifies the connections between tiles and the connect between tiles and their sites. prjxray_tile_type_import generates a VPR tile that has the correct tile pin location, switchblock location and fc info...
import cv2 import numpy as np while 1: img = cv2.imread('C:\\Users\\Denni\\Desktop\\1200px-Road_in_Norway.jpg')#location gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) edge = cv2.Canny(blur,50,150,apertureSize=3)#Changes to canny image height = edge.shape[...
# -*- coding: utf-8 -*- """ flask_apputils.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~ Useful decorators to enhance route handlers """ from functools import wraps from flask import request, redirect, Response, render_template, jsonify from .helpers import json_value __all__ = ( 'after_this_request', 'as...
""" Package containing sysObjects that sysi uses. Mainly for classes users should inherit from/use when making universes/sessions. Modules: Container Data Objects Profiles Scene Session SessionDirectory Tagable Taskable Universe """
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
import os import sys def get_instance_path(): if os.environ.get("KARP5_INSTANCE_PATH"): instance_path = os.path.abspath(os.environ.get("KARP5_INSTANCE_PATH")) else: instance_path = os.path.abspath(os.getcwd()) # print("INSTANCE_PATH = {}".format(instance_path), file=sys.stderr) # asser...
#!/usr/bin/env python """ ZMQ Publisher for office sensor information Queue: INF """ import wiringpi2 as wiringpi import datetime import time import json import Adafruit_DHT import traceback import sys import zmq # this is the socket where we publish zmqSocket = "tcp://*:5551" # do an additional analog read doAnal...
#!/usr/bin/python import sys #============================================================================= # # Copyright (c) Kitware, Inc. # All rights reserved. # See LICENSE.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS ...
from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect from django.http import Http404 from .models import Product from .forms import ProductForm def product_list_view(request): queryset = Product.objects.all() context = { "object_list": queryset } retur...
from .action import * from .column import * from .filter import * from .listing import * from .renderer import * from .sort import * from .mongo import * __all__ = ( action.__all__ + column.__all__ + filter.__all__ + listing.__all__ + renderer.__all__ + sort.__all__ + mongo.__all__ )
import requests class TestCase: def get(self, url): self.response = requests.get(url) return self def assertStatus(self, status): assert self.response.status_code == status
import datetime import os import matplotlib.pyplot as plt import numpy as np import progressbar import scipy.interpolate import scipy.special import cluster import particlefilter import util from utils import * import poles_extractor np.random.seed(0) mapinterval = 1.5 mapdistance = 1.5 n_mapdetections = 6 n_locdete...
import numpy as np HW = [bin(n).count("1") for n in range(0, 256)] def hw(n): if isinstance(n, str): return HW[ord(n)] return HW[n] hw_vec = np.vectorize(hw) # fmt: off SBOX = [ # 0 1 2 3 4 5 6 7 8 9 a b c d e f 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x...
""" Parser ------ This module parses data from the BaseCapture module and assembles them into slices that encompass a range of data representative of Zeo's current status. There are two different callbacks. One for slice callbacks and one that the module will pass events to. """ #System Libraries from math import s...
""" SC101 Baby Names Project Adapted from Nick Parlante's Baby Names assignment by Jerry Liao. Using data of babynames.py to create searching chart. """ import tkinter import babynames import babygraphicsgui as gui FILENAMES = [ 'data/full/baby-1900.txt', 'data/full/baby-1910.txt', 'data/full/baby-1920.txt',...
"""Adapted from: @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn Licensed under The MIT License [see LICENSE for details] """ from __future__ import print_function import argparse import os import pickle imp...
class A: def __init__(self, a, b): self.a = a self.b = b class B(A): def __init__(self, a, b): A.__init__(self, a, b) self.x = None def foo(self): return self.x
from belief_propagation import belief_propagation, calculate_gradient, calculate_belief_sum,\ max_product, get_best_tags from itertools import product from utils.math import logsumexp import torch as tr class Model(object): """ Class to get distribution p(m|T) """ def __init__(self, tags): ...
from setuptools import setup, find_packages BUILDBOTVERSION = '3.4.0' setup( name='autobuilder', version='3.7.0', packages=find_packages(), license='MIT', author='Matt Madison', author_email='matt@madison.systems', include_package_data=True, package_data={ 'autobuilder': ['temp...
import numpy import keras import math import keras.backend as K import theano.tensor as T from keras.layers import Input, Lambda, merge def window(w, n): w = w + list(reversed(w)) w = numpy.asarray(w) layer = Lambda(lambda x: x * w) layer.build((n,)) return layer def hann(n): w = [0.5 - 0.5*mat...
import streamlit as st def write(): st.image("data/stock-market.webp", width=600) st.title("NSE India Stock Prediction WebApp Using Machine Learning") st.markdown("---") st.subheader("A simple webapp to predict next day stock's High-Low-Open-Close price using machine learning") st.markdown("...
from selenium import webdriver from time import sleep class TinderBot: def __init__(self): self.driver = webdriver.Chrome(executable_path='chromedriver.exe') self.driver.get('https://www.tinder.com') sleep(4) def login(self): botao_login = self.driver.find_element...
""" Module implementing multiple types of defences against adversarial attacks. """ from art.defences.adversarial_trainer import AdversarialTrainer, StaticAdversarialTrainer from art.defences.feature_squeezing import FeatureSqueezing from art.defences.gaussian_augmentation import GaussianAugmentation from art.defences....
import logging from typing import Dict, List, Union, Any from checkov.common.util.type_forcers import convert_str_to_bool from checkov.terraform.parser_utils import eval_string, split_merge_args, string_to_native, to_string # # Functions defined in this file implement terraform functions. # # Inputs: # - First arg ...
from ctypes import ( c_int, c_void_p, c_char_p, c_float, c_size_t, py_object, Structure, CFUNCTYPE ) from ctypes import POINTER as _P from .dll import _bind, SDLFunc, AttributeDict from .stdinc import Uint16, Uint32, SDL_bool from .rect import SDL_Point, SDL_Rect from .surface import SDL_Surface __all__ = [ # ...
def numberWays(hats): n = len(hats) # Number of people nhats = 40 h2p = [[] for _ in range(nhats+1)] mod = 10**9+7 for i in range(n): for hat in hats[i]: h2p[hat].append(i) dp = [[0 for _ in range( 2**n)] for _ in range(nhats+1)] dp[0][0] = 1 for hat in range(1, nhats+1): for s in range...
from .iperf_module import *
''' 给出一个区间的集合,请合并所有重叠的区间。 示例 1: 输入: [[1,3],[2,6],[8,10],[15,18]] 输出: [[1,6],[8,10],[15,18]] 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. 示例 2: 输入: [[1,4],[4,5]] 输出: [[1,5]] 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-intervals ''' class Solution: def merge(self, intervals...
#!/usr/bin/env python import agatecharts agatecharts.patch()
import string import logging NORTH = 0 EAST = 1 WEST = 2 SOUTH = 3 def parse(data): ret = '' steps = 0 data = data.splitlines() x = data[0].index('|') y = 0 direction = SOUTH while True: steps += 1 assert direction in (NORTH, EAST, WEST, SOUTH) if direction == ...
#! /usr/bin/python # Matthias Klose # Modified to only exclude module imports from a given module. # Copyright 2004 Toby Dickenson # # 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 ...
#!/usr/bin/env python # ## VOLDEMORT (VDM) VistA Comparer, command line driver # # (c) 2012 Caregraf, Ray Group Intl # For license information, see LICENSE.TXT # """ VOLDEMORT (VDM) -h, --help: this help text -v, --vista: name of VistA. Defaults to "CGVISTA", Caregraf's publicly hosted demo VistA -f, --fmqlep: FMQL e...
import pymongo def find_top(db): blog = db['blog'] count = 0 result = [] for i in blog.find(): if count >= 10: break result.append(i) return result def user_blogs(db,username): blog = db['blog'] return blog.find({'username' : username}) def blog(db,username,tit...
# -*- coding: utf-8 -*- # CalculadoraFunciones módulo de funciones. from __future__ import print_function import sympy as spp import numpy as np import re import pkgutil import matplotlib.pyplot as plt from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show from mpl_toolkits.mplot3d import Axes3D f...
# -*- coding: utf-8 -*- """\ Caleus SCons build rules """ import os import utils def build_lib(baseenv, target, sources, caelus_inc, caelus_libs, prepend_args=None, append_args=None, install_dir=None, lib_type="shared"): """Build a shared libr...
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.conf import settings from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.decorators import api_view @login_required def index(request): context = {} ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request class WebsiteSlidesSurvey(http.Controller): @http.route(['/slides_survey/certification/search_read'], type='json', auth='user', methods=['POST'], website=True) ...
import os import csv def combine_logs(domain, csv_stat, summary_path, csv_prefix, csv_postfix): combined_dict = {} combined_header1 = [] combined_header2 = [] with open(csv_stat, 'r') as fp: csv_reader = csv.reader(fp) header = next(csv_reader) combined_header1 += ['', "stats"]...
""" Context ==================================== The *Context* is the core part of the Contextual Encoders library. It is used to measure the similarity or dissimilarity of attributes. So far, two different Context-Types are implemented: :class:`.GraphContext` and :class:`.TreeContext`. However, it is very likely that ...
import osa_cli_releases.releasing as releasing from prettytable import PrettyTable from ruamel.yaml import YAML def test_parse_requirements(): req = list(releasing.parse_requirements("pip==18.0"))[0] assert req.name == "pip" assert req.specs == [("==", "18.0")] assert req.extras == [] # TODO(evrardj...
#!/usr/bin/env python3 try: import os from scapy.all import Ether, ARP, srp, send, get_if_hwaddr import argparse import time import sys import re import random import ipaddress import socket from core.colors import * from pwn import log from subprocess import call imp...
import sportsdataverse as sdv def main(): print(sdv.wbb.espn_wbb_calendar(season=2020)) print(sdv.wbb.espn_wbb_schedule(dates=2020)) print(sdv.wnba.espn_wnba_calendar(season=2020)) print(sdv.wnba.espn_wnba_schedule(dates=2020)) print(sdv.mbb.espn_mbb_calendar(season=2020)) print(sdv.mbb.espn_mb...
""" Problem Statement Given a linked list, swap the two nodes present at position i and j. The positions are based on 0-based indexing. Note: You have to swap the nodes and not just the values. Example: linked_list = 3 4 5 2 6 1 9 positions = 3 4 output = 3 4 5 6 2 1 9 Explanation: The node at position 3 has the va...
import logging import requests from jinx.base import _JinxBase from jinx.exceptions import JinxSymbolError log = logging.getLogger(__name__) class Stock(_JinxBase): """Base class for obtaining data abouot a stock from IEX. Attributes ---------- symbol: str Ticker symbol """ def __ini...
import logging import numpy as np from scipy.ndimage import map_coordinates def find_coords_in_undef_conf(xs, ys, disp_func, tol=1e-7, maxit=20): """ Solves x = X + u(X) for X for a given u(). This is done by solving x - X - u(X) = 0 using a Newton scheme with numerically calculated gradients. Para...
from collections import namedtuple from typing import List class Stack: ElementWithCachedMax = namedtuple('ElementWithCachedMax', ('element', 'max')) def __init__(self) -> None: self._element_with_cached_max: List[Stack.ElementWithCachedMax] = [] def empty(...
import normalize
from maintenance_calendar.parser.json.json_parser import JSONParser class JSONExceptionParser(JSONParser): def __init__(self): super(JSONExceptionParser, self).__init__()
from django import test from localground.apps.site.views.pages import PublicView from localground.apps.site import models from localground.apps.site.tests import ViewMixin from rest_framework import status import urllib class PresentationTest(test.TestCase, ViewMixin): def setUp(self): ViewMixin.setUp(se...
# encoding: utf-8 """ @author: jemmy li @contact: zengarden2009@gmail.com """ from config import config import argparse import os, sys from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from IPython import embed def cocoval(detected_json): eval_json = config.eval_json eval_gt = COCO(e...
#!/usr/bin/env python3 def warn(*args, **kwargs): pass import os, warnings warnings.warn = warn from ecradplot import plot as eplt def main(input_srcfile, reference_output_srcfile, output_srcfiles, dstdir): """ Plot input files """ import os if not os.path.isdir(dstdir): os....
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import json import os import mock import pytest import six from bravado_core.operation import Operation from swagger_spec_compatibility.cli.common import uri from swagger_spec_...
from rest_framework.serializers import ModelSerializer from profiles_api.models import UserProfile, ProfileFeedItem class UserProfileSerializer(ModelSerializer): """serializes a user profile object""" class Meta: model = UserProfile fields = ('id', 'email', 'name', 'password') extra_...
__author__ = "Animikh Aich" __copyright__ = "Copyright 2020, Animikh Aich" __credits__ = ["Animikh Aich"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Animikh Aich" __email__ = "animikhaich@gmail.com" from misc import logging import requests, os, json def download_file(source_url, filename=None, folde...
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat class Channel_Seq_Small_Attention(nn.Module): def __init__(self, query_dim, modalities = 8, context_dim = None, heads = 8, dim_head = 64, dropout = 0.): super().__init__() inner_dim = di...
from xml.etree import ElementTree from bs4 import BeautifulSoup as scrape from pytube import YouTube import requests import sys import yaml import os import memoryStore # disable insecure http warning - we dont need heaps of callouts on networks that use their own self signing key. import urllib3 urllib3.disable_war...
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from suika.models.common import Common class Price(Common): __tablename__ = "price" id = Column(Integer, primary_key=True, autoincrement=True) product_id = Column(Integer, ForeignKey("product.id"), nullable=False, ...
from ..utils.RestApiClient import RestApiClient class APIClient(): def __init__(self, connection, configuration): self.client = "data source API client" def ping_data_source(self): # Pings the data source return "async ping" def create_search(self, query_expression): # Q...
from django.core.management.base import BaseCommand from django.utils import timezone from kulkunen.models import AccessControlGrant, AccessControlSystem class Command(BaseCommand): help = 'Creates and removes Kulkunen access control grants' def sync_system(self, system): system_grants = AccessContr...
#Reverso do número. Faça uma função que retorne o reverso de um número inteiro informado. Por exemplo: 127 -> 721. def reverso(numero): return str(numero)[::-1] print(reverso(12345)) print(reverso(127))
from __future__ import absolute_import import string import random import unittest from .OAuthUtils import OAuthUtils from factern_client import FactsApi from factern_client import ApiClient from factern_client import Configuration from factern_client import ApiEndpoint from factern_client import FilterStatement fro...
#!/pxrpythonsubst # # Copyright 2018 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
from django.db import models def HospitalBedsField(*args, **kwargs): """ Default values for Hospital Beds Fields """ return models.PositiveSmallIntegerField(*args, **kwargs)
# -*- coding: utf-8 -*- # # Copyright 2016 Ricequant, 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 ...
from rest_framework import serializers from filemetadata_app.models import FileUpload class FileUploadSerializer(serializers.ModelSerializer): class Meta: model = FileUpload fields = ('datafile', 'created')
import time import plac class FakeImporter(object): "A fake importer with an import_file command" mpcommands = ['import_file'] def __init__(self, dsn): self.dsn = dsn def import_file(self, fname): "Import a file into the database" try: for n in range(10000): ...
""" Example hook file """
from pathlib import Path import sys import yaml import asdf def test_resources(): resources_root = Path(__file__).parent.parent / "resources" resource_manager = asdf.get_config().resource_manager for resource_path in resources_root.glob("**/*.yaml"): with resource_path.open("rb") as f: ...
from functools import wraps from flask import g, request, redirect, url_for def login_required(f): @wraps(f) def decoreted_function(*args, **kwargs): if g.user is None: return redirect(url_for('login', next=request.url)) return f(*args, *kwargs) return decoreted_function @ap...
import torch import torch.nn as nn import torch.nn.functional as F class AlexNet(nn.Module): def __init__(self, num_classes=1000, Kbits=32): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplac...
from django.http import HttpResponse from django_distill import distill_path from django.urls import get_urlconf app_name = 'test' def test_url_in_deep_namespace_view(request): return HttpResponse(b'test', content_type='application/octet-stream') def test_no_param_func(): return None urlpatterns = [ ...
import os from copy import deepcopy from enum import Enum import requests from lxml.cssselect import CSSSelector from lxml.html import fromstring from firebase_admin import _apps, initialize_app, get_app, firestore from datetime import datetime from common.config import korea_timezone from firebase.firebase_...
""" License: Apache 2.0 Author: Perry Deng E-mail: perry.deng@mail.rit.edu """ import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.python import debug as tf_debug # for debugging import numpy as np import time import sys import os import re # for regular expressions from config import FL...
from unicodedata import name from scapy.all import * import time class MyPacket(): def __init__(self) -> None: # ether loopback self.packTimne = None self.lens = None self.packet = None self.tcptrace = None self.layer_4 = {'name' : None, 'src': None, 'dst': None,'in...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, print_function import frappe import getpass from frappe.utils.password import update_password def before_install(): frappe.reload_doc("core", "doctype", "docfield") frappe.re...
data = ( 'Xiang ', # 0x00 'Nong ', # 0x01 'Bo ', # 0x02 'Chan ', # 0x03 'Lan ', # 0x04 'Ju ', # 0x05 'Shuang ', # 0x06 'She ', # 0x07 'Wei ', # 0x08 'Cong ', # 0x09 'Quan ', # 0x0a 'Qu ', # 0x0b 'Cang ', # 0x0c None, # 0x0d 'Yu ', # 0x0e 'Luo ', # 0x0f 'Li ', # 0x10 'Z...
import aiofiles import hashlib from hashlib import algorithms_available __all__ = ("get_checksum_from_picture", "algorithms_available", "save_picture") def get_checksum_from_picture(picture: bytes, method: str = "md5") -> str: """Calculate the checksum of the provided picture, using the desired method. Avail...
# Copyright 2020 Connor Ferster # 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 agre...
import numpy as np import openmdao.api as om from mphys.multipoint import Multipoint from mphys.scenario_aerostructural import ScenarioAeroStructural from vlm_solver.mphys_vlm import VlmBuilder from tacs.mphys import TacsBuilder from mphys.solver_builders.mphys_meld import MeldBuilder from struct_dv_components import...
#pil300KW for waxs, pil1M for saxs def cd_saxs(th_ini, th_fin, th_st, exp_t=1): sample = ['cdsaxs_ech03_defectivity_pitch128', 'cdsaxs_ech03_defectivity_pitch127', 'cdsaxs_ech03_defectivity_pitch124', 'cdsaxs_ech03_defectivity_pitch121', 'cdsaxs_ech03_defectivity_pitch118', 'cdsaxs_ech03_defectivity_pitch115', 'c...
import matplotlib.pyplot as plt fontsize=44 ticksize=36 def distributed_hsq(): percents = [0, 77, 90, 0] x = [0, 0.65, 2.35, 3] plt.bar(x, percents, width=1.15, tick_label=["", "HSQ-SGD", "SGD", ""], fc='dimgray') plt.xlabel('Optimizer', fontsize=fontsize) plt.ylabel(...
import os import requests from requests import ReadTimeout import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_webserver_connected_via_localhost(host): scks = host.socket("tcp://127.0.0.1:80")...
############################################################################## # # Copyright (c) 2001 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
import ipfsapi try: ipfs_gateway_api = ipfsapi.connect('127.0.0.1', 5001) except Exception as e: # should be more specific ConnectionRefusedError, NewConnectionError, MaxRetryError not sure print("Automatic Mode A Public Gateway will be used as a fallback") ipfs_gateway_api = ipfsapi.connect('https://i...
class Product(): def __init__(self, name, price, weight, flammability, identifier): self.name = name self.price = 10 self.weight = 20 self.flammability = 0.5 self.identifier = random.randint(1000000,9999999) def stealability(self): ''' calculates the pri...
import itertools import uuid import warnings from collections import OrderedDict, defaultdict from collections.abc import MutableSequence from django import forms from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django.forms.utils import ErrorList from django.utils.functional import cached_pr...
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField, PasswordField from wtforms.validators import InputRequired, Length, Email, EqualTo class BlogForm(FlaskForm): title = StringField('Title', validators=[InputRequired()]) body = TextAreaField("Type your desired quote?",valida...
import numpy as np import matplotlib.pyplot as plt IMAGE_ARRAY = np.load('../../data/tidy/preprocessed_images/size128_exp5_Pr_Po_Im.npy',allow_pickle = True) def plotSelectedProcessedImages(image_array): ## Generates the subfigures in Figure 2 in the paper. example_image_list = [1790, 1792, ...
import cv2, time, numpy fps = 25 filename = "recordedvideo.avi" def record(filename1):#,filename2,filename3): vid = cv2.VideoCapture(0) re,fram = vid.read() out = cv2.VideoWriter(filename1, cv2.VideoWriter_fourcc(*'DIVX'), fps, (numpy.shape(fram)[1],numpy.shape(fram)[0])) ti = 10 # recording length of video to be...
class SharedVariables: database = None movie_col = ['Id', 'Name', 'Rating'] projection_col = ['Id', 'Movie_ID', 'Type', 'Projections Date Time', 'Available Spots'] options = ['show movies', 'show movie projection <movieid> ' '[<projection date>]', 'make reservation...
"""Main configuration file, loads configs/config.yaml.""" import os.path as op import yaml from jinja2 import Environment from box import Box with open( op.join( op.abspath(op.join(__file__, op.pardir, op.pardir)), "configs/config.yaml", ), "r", ) as fp: raw_config = yaml.full_load(fp...
#!/usr/bin/env python3 # 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 attr import numpy as np import quaternion import habitat_sim.bindings as hsim from typing import Dict from habita...
from smarts import db from smarts.models import Message from pathlib import Path import json from datetime import datetime from smarts.commands import db_manage_bp @db_manage_bp.cli.group() def db_manage(): """ Database management commands """ pass @db_manage.command() def add_data(): """ Add sample dat...
import json import os def load_config(): global CONFIG with open(config_file, 'r') as configfile: CONFIG = json.load( configfile ) return CONFIG def save_config(): with open(config_file, 'w') as configfile: json.dump(CONFIG, configfile, indent=4,ensure_ascii=False) config_file = 'my.j...
"""Class to dectect edges in a picture""" import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) import matplotlib.image as img import matplotlib.pyplot as plt # sample user interaction idea # img = library.image('pic1.png') # img_contour = img.draw_contours() class Picture: """ Picture class. ...
import math from typing import Dict, Optional from pytorch_lightning.loggers import WandbLogger class WandbWithBestMetricLogger(WandbLogger): def __init__( self, name: Optional[str] = None, save_dir: Optional[str] = None, offline: Optional[bool] = False, id: Optional[str] ...