content
stringlengths
5
1.05M
''' Auth API 관련 테스트 케이스 ''' import unittest from json import loads from flask import current_app from app import create_app from flask_jwt_extended import create_access_token class AuthAPITestCase(unittest.TestCase): ''' Auth 테스트 케이스 클래스 ''' def setUp(self): '''전처리 메소드''' self.app = create_app...
""" Utilities to match ground truth boxes to anchor boxes. Copyright (C) 2018 Pierluigi Ferrari 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 re...
#pretrained_model = '/home/dzm44/Documents/projects/clinical-bert/clinical-bert-weights' #code_graph_file = '/home/dzm44/Documents/data/icd_codes/code_graph_radiology_expanded.pkl' pretrained_model = '/home/jered/Documents/projects/clinical-bert/clinical-bert-weights' code_graph_file = '/home/jered/Documents/data/icd_c...
from abc import ABC, abstractmethod class Cat(ABC): @abstractmethod def talk(self, meow_type): pass class BlackCat(Cat): pass black_cat = BlackCat()
# Generated by Django 2.0.4 on 2018-05-01 14:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zoo', '0012_auto_20180501_1406'), ] operations = [ migrations.RemoveField( model_name='exhibit', name='animals', ), ...
import os import sys import torch import tarfile import numpy as np from types import SimpleNamespace import pcam.datasets.modelnet40 as m40 from pcam.models.network import PoseEstimator from torch.optim.lr_scheduler import MultiStepLR from torch.utils.tensorboard import SummaryWriter from pcam.tool.train_util import t...
from bootiful_sanic.model.user import User class UserDAO(User): @classmethod async def get_user(cls, user_id): user = await cls.get_or_404(user_id) return user
from rest_framework import serializers class HelloSerializer(serializers.Serializer): """Serializers a name field for testing our APIView""" name = serializers.CharField(max_length= 10)
# -*- coding: utf-8 -*- from __future__ import absolute_import from enum import IntEnum class LiveAuthType(IntEnum): api = 0 password = 1 no_password = 2 class LiveTemplateType(IntEnum): video = 1 # 视频 video_chat_qa = 2 # 视频,聊天,问答 video_chat = 3 # 视频,聊天 3 video_doc_chat = 4 # 视频,文档,聊天 4...
import random as rnd import numpy as np import prettytable POPULATION_SIZE = 9 NUMB_OF_ELITE_SCHEDULES = 1 TOURNAMENT_SELECTION_SIZE = 3 MUTATION_RATE = 0.1 class Department: def __init__(self, name, courses): self._name = name self._courses = courses def get_name(self): return self...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ README: 轉換格式 從 臺灣生物分類階層樹狀名錄 Input: https://taibnet.sinica.edu.tw/AjaxTree/allkingdom.php? id detail: #https://taibnet.sinica.edu.tw/chi/taibnet_species_detail.php?name_code=201102&tree=y API by hack: https://taibnet.sinica.edu.tw/AjaxTree/xml.php?id=%s CSV 格式: id,l...
#!/usr/bin/env python import os import yaml from botocore.exceptions import ClientError, ProfileNotFound import boto3 from fabric.api import run, env, task, sudo, cd from fabric.contrib.files import exists from fabric.contrib.console import confirm from fabric.operations import require from fabric.utils import abort, ...
#!/usr/bin/python # -*-coding:utf-8 -*- u""" :创建时间: 2021/1/11 21:05 :作者: 苍之幻灵 :我的主页: https://cpcgskill.com :QQ: 2921251087 :爱发电: https://afdian.net/@Phantom_of_the_Cang :aboutcg: https://www.aboutcg.org/teacher/54335 :bilibili: https://space.bilibili.com/351598127 """ import logging import ast import astunparse from ...
"""Tkinter GUI chat client.""" import socket import threading import tkinter as tk firstclick = True client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP = "127.0.0.1" PORT = 33002 BUFFSIZE = 1024 ADDR = (IP, PORT) MSG_COUNT = 0 """ Address Family - internet, SOCK_STREAM is the TCP connection; reli...
from django.conf import settings from django.db import models from django.utils.functional import lazy from django.utils.translation import gettext_lazy as _ from djchoices import DjangoChoices, ChoiceItem from future.utils import python_2_unicode_compatible from bluebottle.utils.models import PublishableModel, get_la...
""" Script to generate suitesparse_graphblas.h, suitesparse_graphblas_no_complex.h, and source.c files. - Copy the SuiteSparse header file GraphBLAS.h to the local directory. - Run the C preprocessor (cleans it up, but also loses #define values). - Parse the processed header file using pycparser. - Cre...
from functools import partial as p import pytest from tests.helpers.util import ensure_always, wait_for pytestmark = [pytest.mark.kubernetes_events, pytest.mark.monitor_without_endpoints] def has_event(fake_services, event_dict): event_type = event_dict["reason"] obj_kind = event_dict["involvedObjectKind"] ...
# -*-coding:utf-8-*- from __future__ import print_function import numpy as np import pickle import os # Single Layer Restricted Boltzmann Machine class RBM: def __init__(self, num_visible, num_hidden, learning_rate=0.1, path=None): """ 初始化函数 Initial Function :param num_visible: 可...
import shutil import os import subprocess ''' Building Executables ''' print('Started build...') build = subprocess.Popen(["pyinstaller", "--onefile", "--windowed", "--icon=logo.ico", "Pic2Text.py"], stdin =subprocess.PIPE, stdout=subprocess.PIPE, ...
"""Plot a histogram.""" import pandas as pd import matplotlib.pyplot as plt from util import get_data, plot_data, compute_daily_returns def test_run(): # Read data dates = pd.date_range('2009-01-01', '2012-12-31') # date range as index symbols = ['SPY'] df = get_data(symbols, dates) # get data for e...
from rest_framework import serializers from .models import Posts class PostSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) create_by = serializers.CurrentUserDefault class Meta: model = Posts fields = ['id', 'title', 'content', 'image', 'create_by', ...
r"""*Single-source version number for* ``stdio_mgr``. ``stdio_mgr`` provides a context manager for convenient mocking and/or wrapping of ``stdin``/``stdout``/``stderr`` interactions. **Author** Brian Skinn (bskinn@alum.mit.edu) **File Created** 18 Mar 2019 **Copyright** \(c) Brian Skinn 2018-2019 **Sou...
import pyqt_designer_plugin_entry_points print("* pyqt_designer_plugin_entry_points hook *") globals().update(**pyqt_designer_plugin_entry_points.enumerate_widgets()) print(pyqt_designer_plugin_entry_points.connect_events())
# Generated by Django 2.1.2 on 2021-12-04 16:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instrumento', '0001_initial'), ] operations = [ migrations.AddField( model_name='evaluacion', name='puntaje', ...
''' Created on 2013-11-24 @author: Nich ''' import unittest from objects.component_manager import ComponentManager, ArrayComponentSource from objects.node_factory import NodeFactoryDB class TestComponent0(object): __compname__ = "test_component0" def __init__(self, entity_id, some_string=None): sel...
import os import time import numpy as np import pandas import pandas as pd from scripts.MADDPG.maddpg import MADDPG from scripts.MADDPG.buffer import MultiAgentReplayBuffer # from scripts.MADDPG_original.maddpg import MADDPG # from scripts.MADDPG_original.buffer import MultiAgentReplayBuffer from make_env import mak...
# -*- coding: utf-8 -*- from selenium import webdriver from fixture.session import Session from fixture.check_profile import Check class Fixture: def __init__(self, base_url, browser="Safari"): if browser == "Safari": self.driver = webdriver.Safari() elif browser == "Chrome": ...
from __future__ import absolute_import, print_function import argparse import json import logging import os import random import sys import boto log = logging.getLogger("nameq.dump") def dump_hosts(s3bucket, s3prefix, filter_features=None, single=False, s3options=None): if s3options is None: s3options ...
import json import matplotlib.pyplot as plt f_name = "pos_cur.json" data = None with open(f_name, 'r') as file: data = json.load(file) f = data["forward"] r = data["reverse"] print("len(f): %d\tlen(r): %d" % (len(f), len(r))) p_f = [] c_f = [] for d in f: p_f.append(d[0]) c_f.append(d[1]) plt.plot(p_f, c_f) p...
"""This script collates all of the hand sourced enthalpy of vaporization data.""" import pandas from nonbonded.library.models.datasets import Component, DataSetEntry from openff.evaluator import substances def source_enthalpy_of_vaporization() -> pandas.DataFrame: """Returns a list of hand sourced enthalpy of vap...
import numpy as np import tensorflow as tf from matcher import HungarianMatcher class DETRLosses(): def __init__(self,num_classes = 2): super(DETRLosses, self).__init__() self.weight_dict = {'loss_ce': 1, 'loss_bbox': 1, 'loss_giou': 2} self.matcher = HungarianMatcher() self.num_class...
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Global test counters initialization. """ from time import time from pypower.t.t_globals import TestGlobals def t_begin(num_of_tests, quiet=False): """In...
import logging from basics.base import Base as PyBase class Base(PyBase): def __init__(self, *args, disable_logging=False, **kwargs): # print(f"mlpug.Base(*args={args}, kwargs={kwargs})") super().__init__(*args, **kwargs) self._logging_disabled = None self._set_logging_disabled(d...
""" Definition of the :class:`PersonNameTestCase` class. """ from dicom_parser.data_elements.person_name import PersonName from tests.test_data_element import DataElementTestCase class PersonNameTestCase(DataElementTestCase): """ Tests for the :class:`~dicom_parser.data_elements.person_name.PersonName` ...
# -*- coding: utf-8 -*- """ * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available. * Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in co...
from flask import Flask, request, json from api.scrapper import API app = Flask(__name__) def are_valid_query_params(query_params): required_params = ["oci", "oco", "dci", "dco", "dd"] try: for param in required_params: assert param in query_params.keys() return True except A...
import pytest import numpy as np from numpy.testing import assert_array_almost_equal from context import fiberorient as fo def test_confidence(st_obj): test_conf = st_obj.confidence true_conf = np.array([[[0.10819485, 0.42774707, 0.42774707, 0.10819485], [0.42774707, 0.68832326, 0....
import unrealsdk from unrealsdk import * from ..OptionManager import Options import json import os class Viewmodel(BL2MOD): Name = "CVM" Description = "<B><U><font size='18' color='#e8131d'>Configurable Viewmodel</font></U></B>\n" \ "A mod that allows you to set your viewmodel the way you li...
# test_561.py import unittest from arrayPairSum_561 import arrayPairSum class sortArrayByParityTest(unittest.TestCase): def test_sort_array_by_parity_1(self): self.assertEqual(arrayPairSum([1,4,3,2]), 4) def test_sort_array_by_parity_2(self): self.assertEqual(arrayPairSum([]), 0) if __...
file = open("/Users/yuqil/Desktop/16fall/15688/final project/code/688proj/base_dir/original-data/AMiner-Author.txt") dict = {} cur_name = None cur_address = None read_name = False for line in file: if line.startswith("#n"): cur_name = line.rstrip()[3:] read_name = True elif line.startswith(...
_base_ = [ '../_base_/models/oscar/oscar_gqa_config.py', '../_base_/datasets/oscar/oscar_gqa_dataset.py', '../_base_/default_runtime.py', ] # cover the parrmeter in above files model = dict(params=dict(model_name_or_path='/home/datasets/mix_data/model/vinvl/vqa/base/checkpoint-2000000', )) data_root = '/...
""" View netCDF time series in an interactive timeseries plot with bokeh. Plot opens in a browser window. """ from bokeh.models import ColumnDataSource from bokeh.plotting import figure, show, output_file from bokeh.palettes import Category10 as palette import itertools import numpy import argparse import galene as ga...
import tensorflow as tf import numpy as np from tensorflow.python.framework import ops # from tensorflow.python.ops import array_ops # from tensorflow.python.ops import sparse_ops ani_mod = tf.load_op_library('ani.so'); @ops.RegisterGradient("AniCharge") def _ani_charge_grad(op, grads): """The gradients for `ani...
import clr import re regexString = IN[0] SheetNameList = IN[1] elementList = list() for item in SheetNameList: searchObj = re.search(regexString, item) elementList.append(searchObj.group()) OUT = elementList
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # NWI legend: https://www.fws.gov/wetlands/Data/Mapper-Wetlands-Legend.html def nwi_add_color(fc): emergent = ee.FeatureCollection( fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Emergent Wetland'...
''' This file sets up the titanic problem using kNN algorithm. Accuracy: 0.79904 ''' #import kNN import knn.kNN as knn #import model import data.TitanicParser as model #using pyplotlib to plot error with k import matplotlib.pyplot as plt #load trainer from knn trainer = knn.knn() #get train and test data X,...
import socket, ssl HOST, PORT = 'example.com', 443 def handle(conn): conn.write(b'GET / HTTP/1.1\n') print(conn.recv().decode()) def main(): sock = socket.socket(socket.AF_INET) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 ...
"""Contract test cases for ready.""" import json from typing import Any from aiohttp import ClientSession, hdrs, MultipartWriter import pytest from rdflib import Graph from rdflib.compare import graph_diff, isomorphic @pytest.mark.contract @pytest.mark.asyncio async def test_validator_with_file(http_service: Any) ->...
# pan_and_tilt_tracker.py # to run this program, type: # sudo python pan_and_tilt_tracker.py headed (GUI) # sudo python pan_and_tilt_tracker.py headless (no GUI (for embedded use)) # this program pans/tilts two servos so a mounted webcam tracks a red ball # use the circuit from "pan_and_tilt_tracker....
# Generated by Django 3.1.1 on 2020-10-15 17:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("carbon_quiz", "0058_auto_20201012_1444"), ("carbon_quiz", "0059_auto_20201014_1909"), ] operations = []
from rest_framework.test import APIClient from django.test import SimpleTestCase, TestCase, Client from django.urls import reverse, resolve from products.models import Product, Category, Comment import json from decimal import Decimal from django.contrib.auth.models import User #testing views class TestViews(TestCase...
# -*- coding: utf-8 -*- ############################################################################# # # Copyright © Dragon Dollar Limited # contact: contact@dragondollar.com # # This software is a collection of webservices designed to provide a secure # and scalable framework to build e-commerce websites. # # This s...
def data_parser(data): print 'Your name is {0}, you are {1} years old, and your username is {2}.'.format(data[0],data[1],data[2]) if 'y' in data[3]: f = open('data_logger.txt','w') f.write('Your name is {0}, you are {1} years old, and your username is {2}.'.format(data[0],data[1],data[2])) def data_retriev...
from settings import * import os PROJECT_HOME = os.path.dirname(os.path.dirname(__file__)) LOG_FOLDER=os.path.join(PROJECT_HOME, '..', 'logs') if os.path.exists(os.path.join(PROJECT_HOME,"local_settings.py")): from local_settings import * LOG_LEVEL="DEBUG" LOG_FILENAME="operations_management.log" LOGGING = ...
# hack to run multiple luigi tasks in one session import luigi import json import argparse from mc_luigi import LearnClassifierFromGt, PipelineParameter from mc_luigi import MulticutSegmentation, BlockwiseMulticutSegmentation def learn_rf(): ppl_parameter = PipelineParameter() ppl_parameter.read_input_file('...
import os import sys import threading import time from multiprocessing import Pool import requests from pyramid.config import Configurator from pyramid.response import Response # begin chdir armor up = os.path.dirname(os.path.abspath(__file__)) testdir = os.path.dirname(up) hendrix_app_dir = os.path.dirname(testdir) ...
__author__ = 'peeyush' from GCAM import FilesFolders import timeit, sys, os from GCAM import Fetch_pmids import pandas as pd def check_database_update(annoDB, cellDB, resource_path): ''' This function checks for update in annotation db and celltype db. If found then delete gene_occu_db. :param annoDB...
class ConfigurationError(Exception): """Error raised when a class constructor has not been initialized correctly.""" pass class ExecutionProviderException(Exception): """ Base class for all exceptions Only to be invoked when only a more specific error is not available. """ pass class Schedu...
# -*- coding:utf-8 -*- """ Description: Contract Parameter Type in neo.Wallets Usage: from neo.SmartContract.ContractParameterType import ContractParameterType """ class ContractParameterType(object): Signature = 0x00 # 签名 Boolean = 0x01 Integer = 0x02 # 整数 Hash160 = 0x03 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio Instrucciones 1. Elevar al cuadrado una lista dada por el usuario de 10 elementos, se debe de mostrar la lista original y la lista elevada al cuadrado. Ej. a = [1,2,3,4,5,6,7,8,9,10] R = [1,4...
import boto3 import os import json def lambda_handler(message, context): if ('body' not in message or message['httpMethod'] != 'PUT'): return { 'statusCode': 400, 'headers': {}, 'body': json.dumps({'msg': 'Bad Request'}) } table_name = os.envir...
from collections import defaultdict from helpers import get_input def main() -> int: bin_strings = [row.strip() for row in get_input(3)] N = len(bin_strings) bits = len(bin_strings[0]) sums = [sum(int(string[i]) for string in bin_strings)for i in range(bits)] gamma = int("".join(str(int(sum >= N/...
# # ⚠ Warning # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA...
# coding=utf-8 from __future__ import unicode_literals import django from ..compat import patterns if django.VERSION < (1, 6): from django.conf.urls.defaults import url, include else: from django.conf.urls import url, include urlpatterns = patterns( url(r'viewlet/', include('viewlet.urls')) )
import logging import multiprocessing import time import rdkit from rdkit.Chem.QED import qed from sqlalchemy import create_engine # logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def construct_problem(): # We have to delay all importing of tensorflow until the child processes laun...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys import jreadability_feedback as jf import unittest import tempfile import json class AppTestCase(unittest.TestCase): def setUp(self): self.db_fd, jf.app.config['DATABASE'] = tempfile.mkstemp() jf.app.config['TESTING'] = True self.app = jf....
#!/usr/bin/python3 import re, sys from Bio import SeqIO def read_gff(infile): f = open(infile, 'r') gff_dict = dict() trans_dict = dict() for line in f: line = line.strip() if line.startswith('#'): continue content = line.split() if content[2] == "transcript": ...
#! /usr/bin/env python import os import tornado.ioloop import tornado.options from tornado.options import define, options import tornado.web from api.controller.BaseStaticFileHandler import BaseStaticFileHandler from api.controller.ServerListController import ServerListController from api.controller.InfoController im...
from dataclasses import dataclass from datetime import datetime from dash.dash import Dash from dash.dependencies import Input, Output from dash.development.base_component import Component from plotly.missing_ipywidgets import FigureWidget from dash.exceptions import PreventUpdate from components.transaction_store_bloc...
#!/usr/bin/env python import os def mkdir_p(dir): '''make a directory (dir) if it doesn't exist''' if not os.path.exists(dir): os.mkdir(dir) job_directory = "%s/jobs" %os.getcwd() # Make top level directories mkdir_p(job_directory) script_path= "$HOME/projects/seasonal_forecasting/code/scripts/...
def fibonacci(num): fibs = [0,1] for i in range(num-2): fibs.append(fibs[-2]+fibs[-1]) print(fibs[num-1]) n = int(input()) for i in range(n): m = int(input()) fibonacci(m+1)
from __future__ import absolute_import, print_function, unicode_literals from validator.constants import BUGZILLA_BUG from ..regex.generic import FILE_REGEXPS from .jstypes import Global, Hook, Interfaces # SQL. SYNCHRONOUS_SQL_DESCRIPTION = ( 'The use of synchronous SQL via the storage system leads to severe ...
from helpers import read_data, get_settings, package_translation import api settings = get_settings() article_map = read_data('article_map') locales = ['de', 'es', 'fr', 'ja', 'pt-br'] for article in article_map: url = '{}/articles/{}/translations/missing.json'.format(settings['src_root'], article) missing_l...
from unittest.mock import Mock, call from pytest import fixture, mark from pyviews.binding import BindingContext from pyviews.binding.expression import ExpressionBinding, bind_setter_to_expression from pyviews.binding.tests.common import InnerViewModel, ParentViewModel from pyviews.expression import Expression, execu...
from django.urls import path from .views import my_works, my_works_detail, my_post_detail app_name = 'my_works_blog' urlpatterns = [ path('', my_works, name='index'), path("<int:pk>/", my_works_detail, name='project_detail'), path("<int:pk>/<int:pk1>", my_post_detail, name='post_detail'), ]
#!/usr/bin/python -i import numpy as np from NuclearNormMinimization import NuclearNormMinimization from sklearn.metrics import mean_squared_error U = np.random.random((10,10)) S = np.zeros((10,10)) S[0,0] = 500 S[1,1] = 100 S[2,2] = 50 V = np.random.random((10,20)) matrix = np.matmul(U, np.matmul(S, V)) incomplete_m...
""" TODO: *Choose which drink you want out of the top n *Exception when 0 mathces """ import sqlite3 def main(): ingredientList = []; matchDict = {}; print("""\nHello, I'm Cocky, and this is Cocky's Cocktail Shack. \nI'll help you make a cocktail."""); print("Please enter your ingredients and write \"done\" whe...
""" Factories for features and geometries """ from typing import Mapping, Union import keytree.compat from keytree.model import GEOM_TYPES, NSMAP, Feature, Geometry def feature(element, kmlns: Union[str, Mapping] = NSMAP) -> Feature: kid = element.attrib.get("id") name = element.findtext("kml:name", namespa...
# Copyright © 2020, Oracle and/or its affiliates. All rights reserved. # In this example, we specify and estimate a Bayes Factor for the 4-5th rule import torch from relax import * from relax.interface import BayesFactor import relax.estimators.importance.KDE_tips as Stan from data import data2 as data # Step 0: pre...
class UrlManager(object): def __init__(self): pass def get_main_seed_url(self): return 'https://www.meitulu.com/'
"""Library integration with Random123.""" from __future__ import division, absolute_import __copyright__ = "Copyright (C) 2016 Andreas Kloeckner" __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to dea...
import os import pytest import renderapi import json import mock import numpy as np from test_data import ( RAW_STACK_INPUT_JSON, render_params, montage_z, solver_montage_parameters, test_pointmatch_parameters as pointmatch_example, test_pointmatch_parameters_qsub as pointmatch_example_qsub) f...
import VIKOR as vikor import numpy as np from normalisation_fuc import omri_normalisation # Step 2*: change SR fucntion to adapt rim version def SR_omri(D, w, AB): nD = omri_normalisation(D, AB) S = np.zeros(nD.shape[0]) R = np.zeros(nD.shape[0]) for i in range(nD.shape[0]): for j in ran...
import functools import re import pathlib import timeit from typing import Union, List, Generator, Type from net_models.validators import normalize_interface_name from net_models.models.interfaces.InterfaceModels import InterfaceModel from net_models.models import VRFModel from net_models.models.services.ServerModels ...
import ConfigParser, os, uuid, subprocess cur_dir = os.path.dirname(__file__) couchdb_ini_file_path = os.path.join(cur_dir, 'etc/couchdb.ini') if os.path.isfile(couchdb_ini_file_path): config = ConfigParser.ConfigParser() config.read([couchdb_ini_file_path]) config.set('couchdb', 'uuid', uuid.uuid4().hex...
from cli.src.helpers.build_io import (get_inventory_path_for_build, load_inventory, load_manifest, save_inventory) from cli.src.helpers.data_loader import load_schema_obj from cli.src.helpers.data_loader import types as data_types from cli.src....
from flask import current_app from src.shared.entity import Session from src.shared.manage_error import ManageErrorUtils, CodeError, TError from .entities import InputOutput, InputOutputSchema class InputOutputDBService: @staticmethod def check_input_output_exists(input_output_id): session = None ...
import pandas as pd from IPython.display import display dt1 = { 'aa': ['j', 'b', 'e', 'g', 'i', 'c'], "ab": [4, 2, 5, 6, 1, 7], } dt2 = { 'aa': ['b', 'e', 'i', 'j', 'c', 'g'], "ac": [4, 9, 5, 8, 3, 4], } df1 = pd.DataFrame(dt1) # df1 = df1.set_index('aa') display(df1) df2 = pd.DataFrame(dt2) # df2 ...
""" A python program to plot a grade histogram Usage: python plot_grade_hist.py [filename] [colname] [maxy] ([nscorecols]) Required inputs: filename - text file containing either two columns (name total) or three columns (name, score_multiple-choice, score_short-answer) colname - the name of th...
from flask import jsonify def badrequest(message): response = jsonify({'status': 'BAD_REQUEST', 'error_message': message}) response.status_code = 400 return response
import csv datosStudents = sc.textFile("/home/leo/Files/studentsPR.csv") students=datosStudents.map(lambda x: [x]).map(lambda x : list(csv.reader(x))[0]) final=students.filter(lambda x: x[5] == 'F').filter(lambda x: x[2] == '71381') final.foreach(print)
# Generated by Django 2.2.12 on 2020-04-30 05:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations = [ migrations.AddField( model_name='event', ...
def get_warnings(connection): warnings = connection.show_warnings() if warnings: print('warnings:', warnings) def get_script_from_file(filename): f = open(filename, 'r') script = f.read() f.close() return script def get_report(mysql, script): conn = mysql.connect() get_warnin...
# from modules import ilmodule import requests import re import time from time import mktime from datetime import datetime import json import globals # # Try to determine the actual date of the picture. By metadata, filename, etc, # Assuming all the EXIF data was already extracted previously. # Place this step of proc...
# noinspection PyUnresolvedReferences import gc import ucomputer import utime def address(): return ucomputer.get_computer_address() def tmp_address(): return ucomputer.get_tmp_address() def free_memory(): return gc.mem_free() def total_memory(): return gc.mem_alloc() + gc.mem_free() def upti...
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO from enum import Enum import collections import zlib if parse_version(kaitaistruct.__version__) <...
"""Support for Konnected devices.""" import asyncio import copy import hmac import json import logging from aiohttp.hdrs import AUTHORIZATION from aiohttp.web import Request, Response import voluptuous as vol from homeassistant import config_entries from homeassistant.components.binary_sensor import DEVICE_CLASSES_SC...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ¹⁷O 2D DAS NMR of Coesite ^^^^^^^^^^^^^^^^^^^^^^^^^ """ # %% # Coesite is a high-pressure (2-3 GPa) and high-temperature (700°C) polymorph of silicon # dioxide :math:`\text{SiO}_2`. Coesite has five crystallographic :math:`^{17}\text{O}` # sites. The experimental datase...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RPopvar(RPackage): """PopVar: Genomic Breeding Tools: Genetic Variance Prediction andCross...
class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname self.address = [] def add_address(self, address): self.address.append(address) class Address: def __init__(self, street, number): self.street = street ...