text
stringlengths
1
927k
# Copyright 2013-2019 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.main import SpackCommand import os.path import pytest import spack.util.spack_yaml as s_yaml activate = Spack...
from PyQt5 import QtWidgets, uic from PyQt5.QtGui import QImage, QPixmap, QPalette, qRgb, qGray import sys import numpy as np from typing import Callable from numbers import Number def process_image( input_image: np.array, kernel_size: int, kernel_fn: Callable[[np.array], float]) -> np.array: ...
__author__ = '1' from model.project import Project import pytest import random import string def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + string.punctuation + " "*10 return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) testdata =[ ...
import pytest from ants.users.forms import UserCreationForm from ants.users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestUserCreationForm: def test_clean_username(self): # A user with proto_user params does not exist yet. proto_user = UserFactory.build() ...
#!/usr/bin/python import sys import os import subprocess from os.path import join, isdir import torch #************************************************************************************************************************* ####### Loading the Parser and default arguments #import pdb;pdb.set_trace() #sys.path.inser...
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import numpy as np import fileutility app = dash.Dash(__name__, suppress_callback_exceptions=True) app.title = 'Tunnusluvut' # For Heroku serve...
import dash_html_components as html import dash_bootstrap_components as dbc import dash_core_components as dcc import pandas as pd import plotly.express as px import plotly.graph_objects as go from models import Forecast as ForecastModel class Forecast: def __init__(self, team_name, remaining_issues=None): ...
#!/usr/bin/env python # This file is part of Diamond. # # Diamond is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
#!/usr/bin/python import csv, sys import numpy dialect = csv.excel_tab multi_file=len(sys.argv[1:])>1 inputs = map(lambda x: csv.DictReader(x, dialect=dialect), map(open, sys.argv[1:])) rows = map(csv.DictReader.next, inputs) headers = inputs[0].fieldnames output = csv.writer(sys.stdout, dialect=dialect) output.writ...
#!/usr/bin/env python # # # FreeType 2 glyph name builder # # Copyright 1996-2017 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to u...
import os import sys from math import pi import numpy as np import param from bokeh.plotting import figure from bokeh.models import ColumnDataSource from tqdm.asyncio import tqdm as _tqdm from ..layout import Column, Row from ..models import ( HTML, Progress as _BkProgress, TrendIndicator as _BkTrendIndicator )...
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OnPrem class _Proxmox(_OnPrem): _type = "proxmox" _icon_dir = "resources/onprem/proxmox" class Pve(_Proxmox): _icon = "pve.png" # Aliases PVE = ProxmoxVE
'''Faça um programa que leia um valor pelo teclado e mostre na tela seu sucessor e seu antesessor''' n1 = int(input('Digite um numero inteiro: ')) print(f'O valor digitado foi {n1} seu sucessor é {n1 + 1} e seu antecessor é {n1 - 1}')
import pandas import pdb from datetime import datetime import matplotlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import glob import sys from matplotlib.ticker import MultipleLocator testcase = sys.argv[1] # K80_vgg19_32 print(testcase) base_dir = '/scratch/li.baol/GPU...
# coding: utf-8 """ Deals No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v3 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from hubspot...
from typing import Any, Optional from jstools.screeps import * __pragma__('noalias', 'name') __pragma__('noalias', 'undefined') __pragma__('noalias', 'Infinity') __pragma__('noalias', 'keys') __pragma__('noalias', 'get') __pragma__('noalias', 'set') __pragma__('noalias', 'type') __pragma__('noalias', 'update') __prag...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2014-2015, Dataspeed 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: # # * Redistributions of source c...
import os from fnmatch import fnmatch def ignore(source_file, config): file_name = os.path.basename(source_file) if config['ignore'] is True or \ config['ignore'] and any(pattern for pattern in config['ignore'] if fnmatch(file_name, pattern)): return return config ignore.defaults = ...
# Copyright 2013 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# -*- coding: utf-8 -*- """Tests using pytest_resilient_circuits""" import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResult from mock import patch PACKAGE_NAME = "fn_qradar_integration" FUNCTION_NAME = "qradar_referenc...
import six import sys from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type f...
"""Prim's Algorithm. Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm. Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm """ import heapq as hq import math from typing import Iterator class Vertex: """Class Vertex.""" def __init__(self, id): """ ...
from utils.string_utils import home_path import yaml configs = open(home_path() + "hypernlp/dl_framework_adaptor/configs/bert_config.yaml", encoding='utf-8') bert_models_config = yaml.load(configs)
from django.contrib import admin from popolo.models import Person, Organization @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): pass
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain...
from api import all_csvs_to_file bka_zeitreihen_daten_url = "https://www.bka.de/DE/AktuelleInformationen/StatistikenLagebilder/PolizeilicheKriminalstatistik/PKS2019/PKSTabellen/Zeitreihen/zeitreihen_node.html" bka_bund_fall_tabellen_url = "https://www.bka.de/DE/AktuelleInformationen/StatistikenLagebilder/Polizeiliche...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- r''' Usage: python3 assistant.py service ''' import sys def check_version(): v = sys.version_info # print(v) if v.major == 3 and v.minor >= 4: return True print('Your current python is %d.%d. Please use Python 3.4.' % (v.major, v.minor)) r...
# ЭКРАНИРОВАНИЕ # a = "строка с \" кавычкой двойной и \' одинарной" # Чтобы в строке появился символ обратной косой черты # a = "Строка с обратным слешем \\" # Перенос строки # a = "Первая строка \nВторая строка ''' Сделать перенос строки в Питоне можно и другим способом — объявить строку с помощью тройных кавычек. ...
## @file # This file is used to create/update/query/erase table for data models # # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # from __future__ import absolute_import import edk2basetools.Common.EdkLogger as EdkLogger imp...
import os import sys from pathlib import Path sys.path.insert(1, '../Phase1') sys.path.insert(2, '../Phase2') import misc import numpy as np class Feedback: def __init__(self): self.task5_result = None self.reduced_pickle_file_folder = os.path.join(Path(os.path.dirname(__file__)).parent, ...
from rest_framework.filters import BaseFilterBackend, SearchFilter from django.db.models import Q from rest_framework.compat import coreapi, coreschema from datetime import datetime from django.utils.dateparse import parse_datetime from rest_framework.serializers import ValidationError class DatetimeFilter(BaseFilter...
#!/usr/bin/env python3 import requests, re, os from lxml import html print('Ingrese nombre de la banda:') bus=str(input()) pag=1 start=0 url='https://www.metal-archives.com/search/ajax-band-search/?field=name&query='+bus+'&sEcho='+str(pag)+'&iColumns=3&sColumns=&iDisplayStart='+str(start)+'&iDisplayLength=200&mDataP...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayUserFamilyShareAuthCheckModel(object): def __init__(self): self._resource_id = None self._scene_id = None self._target_biz_user_id = None self._target_user_b...
""" Every non-negative integer N has a binary representation, for example, 8 can be represented as “1000” in binary and 7 as “0111” in binary. The complement of a binary representation is the number in binary that we get when we change every 1 to a 0 and every 0 to a 1. For example, the binary complement of “1010” i...
# Print the head of airquality print(airquality.head()) # Melt airquality: airquality_melt airquality_melt = pd.melt(airquality, id_vars=["Month", "Day"], value_vars=["Ozone","Solar.R", "Wind", "Temp"]) # Print the head of airquality_melt print(airquality_melt.head()) # Print the head of airquality print(airquality...
# Copyright 2012-2020 The Meson development team # 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 pytest from django.urls import resolve, reverse from django_crypto_trading_bot.users.models import User pytestmark = pytest.mark.django_db def test_detail(user: User): assert ( reverse("users:detail", kwargs={"username": user.username}) == f"/users/{user.username}/" ) assert resol...
import Shadow import numpy # using mac oasys, for plots # from srxraylib.plot.gol import set_qt # set_qt() # # runs an absorber of 10 um thickness for a source at 10 keV # # def run_example_lens(user_units_to_cm=1.0,npoint=5000,use_prerefl=0): # # Python script to run shadow3. Created automatically with Shad...
model = dict( type = 'm2det', input_size = 320, init_net = True, pretrained = 'weights/vgg16_reducedfc.pth', m2det_config = dict( backbone = 'vgg16', net_family = 'vgg', # vgg includes ['vgg16','vgg19'], res includes ['resnetxxx','resnextxxx'] base_out = [22,34], # [22,34] fo...
import warnings warnings.filterwarnings('ignore') import torch import numpy as np from models import wrn from laplace import kfla import laplace.util as lutil import util.evaluation as evalutil import util.dataloaders as dl import util.misc from math import * from tqdm import tqdm, trange import argparse import os, sys...
### Slave API Views ### from django.db.models import F, Count from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics from rest_framework import permissions from rest_framework import pagination from slave.models import...
from __future__ import absolute_import import unittest import numpy as np from tests.sample_data import SampleData from pyti import average_true_range_percent class TestAverageTrueRangePercent(unittest.TestCase): def setUp(self): """Create data to use for testing.""" self.close_data = SampleData(...
# Copyright 2015 Google LLC # # 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 taichi.lang.kernel_impl import kernel from taichi.lang.matrix import Vector from taichi.types.annotations import template from taichi.types.primitive_types import f32, u8 import taichi as ti vbo_field_cache = {} def get_vbo_field(vertices): if vertices not in vbo_field_cache: N = vertices.shape[0] ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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, overload from . import ...
from django.contrib import admin from .models import LeadModel,AgentModel,UserProfile,User,CategoryModel # Register your models here. admin.site.register(LeadModel) admin.site.register(AgentModel) admin.site.register(UserProfile) admin.site.register(User) admin.site.register(CategoryModel)
#!/usr/bin/env python3 import os from cereal import car, log from common.numpy_fast import clip from common.realtime import sec_since_boot, config_realtime_process, Priority, Ratekeeper, DT_CTRL from common.profiler import Profiler from common.params import Params, put_nonblocking import cereal.messaging as messaging f...
from flask import Blueprint private = Blueprint('private', __name__) from . import views
# -*- coding: utf-8 -*- from unittest.mock import MagicMock, patch, ANY import pytest from chaoslib.exceptions import ActivityFailed from chaosk8s.statefulset.actions import scale_statefulset, \ remove_statefulset, create_statefulset @patch('chaosk8s.has_local_config_file', autospec=True) @patch('chaosk8s.state...
""" """ import os import shutil import tarfile import tempfile from . import GalaxyTestBase class TestGalaxyHistories(GalaxyTestBase.GalaxyTestBase): def setUp(self): super(TestGalaxyHistories, self).setUp() self.default_history_name = "buildbot - automated test" self.history = self.gi.h...
# coding=utf-8 """ Build tasks """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import json import os import subprocess import sys from pynt import task from pyntcontrib import execute, safe_cd from semantic_version import Version PROJECT_N...
""" blockr.io """ import logging import hashlib from hashlib import sha256 import requests from .. import config from binascii import hexlify, unhexlify def getUrl(request_string): return requests.get(request_string).json() def setHost(): config.BLOCKCHAIN_CONNECT = ('http://tbtc.blockr.io' if config.TESTNET ...
from telethon import TelegramClient # Use your own values from my.telegram.org api_id = <your-id> api_hash = <your-hash> # The first parameter is the .session file name (absolute paths allowed) with TelegramClient('anon', api_id, api_hash) as client: client.loop.run_until_complete(client.send_message('me', 'Hello...
# Copyright (c) 2021 elParaguayo # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
from __future__ import unicode_literals from unittest import skipUnless from django.db import connection from django.db.models import Q from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.measure import D # alias for Distance from django.contrib.gis.tests.utils import ( HAS_SPATIAL_DB, mysql, or...
""" Trigger an event in IFTTT ========================= This state is useful for trigging events in IFTTT. .. versionadded:: 2015.8.0 .. code-block:: yaml ifttt-event: ifttt.trigger_event: - event: TestEvent - value1: 'This state was executed successfully.' - value2: 'Another value...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Aug 28 13:38:05 2018 @author: aholaj """ import numpy as np import sound_in_profiles as sp import PythonMethods as pm import ModDataPros as mdp from copy import deepcopy from FindCloudBase import calc_rh_profile from ECLAIR_calcs import calc_rw i...
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib import urllib2 import cookielib import re import json import sys LOGIN_TIMEOUT = 15 REQUEST_TIMEOUT = 25 # ---------------- # Basic functions # ---------------- def format_to_json(unformated_json): # pat = r'(\w+(?=:))' pat = r'((?:(?<=[,{\[])\s*)(\w...
from copy import deepcopy # Puzzle Input ---------- with open('Day18-Input.txt', 'r') as file: puzzle = file.read().split('\n') with open('Day18-Test01.txt', 'r') as file: test01 = file.read().split('\n') with open('Day18-Test02.txt', 'r') as file: test02 = file.read().split('\n') # Main Code ---------...
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name """Transpiler testing""" import unittest.mock from qiskit import QuantumRegister, QuantumCi...
from ..Requirements import BaseObjective # MAXIMIZE class ItemCountObjective(BaseObjective): name = "item_count" def Evaluate(threeDsolution): return -sum([1 for placement in threeDsolution.GetAllPlacements() if placement.position != placement.UNPLACED and placement.itemid is not None]) if __name__=="...
# 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 may ...
from __future__ import annotations import heapq import random import uuid from fractions import Fraction from functools import reduce from typing import Any, Mapping, Optional, Sequence, Union import aiger import aiger_bv as BV import aiger_discrete import attr import funcy as fn from aiger_discrete import FiniteFunc...
# *** WARNING: this file was generated by the Pulumi Kubernetes codegen tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings from typing import Optional import pulumi import pulumi.runtime from pulumi import Input, ResourceOptions from ... import tables, version ...
#!/pxrpythonsubst # # Copyright 2016 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: # ...
#!/usr/bin/env python3 import argparse import sys import colorama from exitstatus import ExitStatus from fact.lib import factorial def parse_args() -> argparse.Namespace: """Parse user command line arguments.""" parser = argparse.ArgumentParser( description="Compute factorial of a given input.", ...
# Objetivo: # Criar um arquivo que mostre: # Aluno -- media # =============================== # Aprovados --- total_aprovado ( media >= 6 ) alunos = [] medias = [] with open('./alunos.txt', 'r') as arquivo_alunos: try: linhas = arquivo_alunos.readlines() for linha in linhas: linha_co...
import chainer import numpy as np from test.util import generate_kernel_test_case, wrap_template from webdnn.graph.placeholder import Placeholder from webdnn.frontend.chainer.converter import ChainerConverter from webdnn.frontend.chainer.placeholder_variable import PlaceholderVariable @wrap_template def template(n=2...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: ADDRESS = "address" AVS_RESULT = "avs_result" BANK_PHONE_COUNTRY_CODE = "bank_phone_country_code" BANK_PHONE_NUMBER = "bank_phone_number" CARD_BANK_NAME = "card_bank_name" CARD_ISSUER_ID_NUMBER = "card_issuer_id_num...
# https://www.hackerrank.com/challenges/countingsort2/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'countingSort' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY arr as parameter. # def countingSort(arr...
"""Automation using nox. """ import glob import nox nox.options.reuse_existing_virtualenvs = True nox.options.sessions = "lint", "tests", "tests-pytest5" locations = "pytest_test_utils", "tests.py" @nox.session(python=["3.7", "3.8", "3.9", "3.10"]) def tests(session: nox.Session) -> None: session.install(".[tes...
# -*- coding: utf-8 -*- """Base exchange class""" # ----------------------------------------------------------------------------- __version__ = '1.81.74' # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import NetworkEr...
# -*- coding: utf-8 -*- # # zalando-research-fashionmnist-experiments documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. #...
import requests import datetime import configparser import json import copy from circuits import Component, handler from events.JobCompleteEvent import JobCompleteEvent from events.EntityPreprocessedEvent import EntityPreprocessedEvent class QuestionJobRunnerComponent(Component): config = configparser.ConfigParser...
# -*- coding: utf-8 -*- import sympy as sp x = sp.symbols('x') assert 1 == sp.limit(sp.exp(x), x, 0) assert 1 == sp.limit(sp.sin(x) / x, x, 0) assert sp.oo == sp.limit(1.0 / x, x, 0) assert sp.E.evalf() == sp.limit((1 + 1.0 / x) ** x, x, sp.oo)
# Copyright 2020 The FastEstimator Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
from deepchem.molnet.load_function.bace_datasets import load_bace_classification, load_bace_regression from deepchem.molnet.load_function.bbbc_datasets import load_bbbc001, load_bbbc002 from deepchem.molnet.load_function.bbbp_datasets import load_bbbp from deepchem.molnet.load_function.cell_counting_datasets import loa...
import home from ws.handler.event.enum import Handler as Parent class Handler(Parent): KLASS = home.event.enable.Event TEMPLATE = "event/enum.html" LABEL = "Detach logic is" ENABLED = "enabled" DISABLED = "disabled" def _get_str(self, e): if e == home.event.enable.Event.On: ...
#Identificar números primos! n = int(input('Digite um número: ')) tot = 0 for c in range(1, n + 1): if n % c == 0: print('\033[33m', end='') tot += 1 else: print('\033[31m', end='') print('{} '.format(c), end='') print('\n\033[mO número {} foi divisível {} vezes'.format(n, tot)) if t...
############################################################################### # Field Types ############################################################################### TEXT = 'TEXT' DATE = 'DATE' INTEGER = 'INTEGER' DECIMAL = 'DECIMAL' DURATION = 'DURATION' BOOLEAN = 'BOOLEAN' SINGLE_OPTION = 'SINGL...
import os from pathlib import Path import shutil import stat from unittest import mock import pytest from outrun.filesystem.common import Attributes from outrun.filesystem.caching.common import Metadata from outrun.filesystem.caching.prefetching import PrefetchSuggestion from outrun.filesystem.caching.service import ...
''' script reduz o valor do um produto com base no desconto(%) ''' produto = float(input('preço do produto: ')) desconto = float(input('porcentagem de desconto: ')) novo_preço = produto - ((produto / 100) * desconto) print(f'o produto custa {produto:.2f}') print(f'o valor do desconto é {desconto:.2f}') print(f'o pr...
from django.shortcuts import render from wiki.models import Page from django.views.generic.list import ListView from django.views.generic.detail import DetailView # Create your views here. class PageList(ListView): """ CHALLENGES: 1. On GET, display a homepage that shows all Pages in your wiki. 2....
import numpy as np def get_calib_from_file(calib_file): with open(calib_file) as f: lines = f.readlines() obj = lines[2].strip().split(' ')[1:] P2 = np.array(obj, dtype=np.float32) obj = lines[3].strip().split(' ')[1:] P3 = np.array(obj, dtype=np.float32) obj = lines[4].strip().split(...
#!/usr/bin/python # -*- coding: utf-8 -- #@File: 07 requests timeout.py #@author: Gorit #@contact: gorit@qq.com #@time: 2020/5/25 20:52 ''' 超时处理: timeout 参数 (防止服务器不能正常响应而抛出异常) ''' import requests # 设置超时时间为 1s (连接 + 读取), 永久等待设置 timeout = None r = requests.get("https://httpbin.org/get", timeout = 1) print(r.status...
# Copyright 2020 The Cross-Media Measurement Authors # # 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 ...
# JSON 데이터도 처리하기. import json jsonDic = {} jsonList = [] csvList = [] filereader = open('TEST01.json', 'r', encoding='utf-8') jsonDic = json.load(filereader) csvName = list(jsonDic.keys()) jsonList = jsonDic[ csvName[0]] # 헤더 추출 header_list = list(jsonList[0].keys()) csvList.append(header_list) # 행들 추출 for tmpDic in ...
from . import brain_vision_to_conmat from . import ts_to_conmat
import os import sys import platform import setuptools SCRIPT_DIR=os.path.dirname(os.path.abspath(__file__)) def main(): os.chdir(SCRIPT_DIR) package_name = 'opencv' package_version = os.environ.get('OPENCV_VERSION', '4.5.1') # TODO long_description = 'Open Source Computer Vision Library Python bin...
""" Elementy w liście są uporządkowane według wartości klucza. Proszę napisać funkcję usuwającą z listy elementy o nieunikalnym kluczu. Do funkcji przekazujemy wskazanie na pierwszy element listy, funkcja powinna zwrócić liczbę usuniętych elementów. """ class Node: def __init__(self, value): self.value = ...
import numpy as np import pandas as pd class DataModel: """ This class implements a data model - values at time points and provides methods for working with these data. """ def __init__(self, n=0, values=None, times=None): """ A constructor that takes values and a time point. ...
import logging from django.core.management.base import BaseCommand from apps.frontpage.models import FrontpageStory from apps.stories.models import Story logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Populates frontpage' def add_arguments(self, parser): parser.add_argume...
from li_std_wstream import * a = A() o = wostringstream() o << a << u" " << 2345 << u" " << 1.435 << wends if o.str() != "A class 2345 1.435\0": print "\"%s\"" % (o.str(),) raise RuntimeError
#!/usr/bin/env python import argparse import os import sys import json import shutil #from src.gradcam import * data_ingest_params = './config/data-params.json' fp_params = './config/file_path.json' gradcam_params = './config/gradcam_params.json' ig_params = './config/ig_params.json' train_params = './config/train_p...
# -*- coding: utf-8 -*- __all__ = ["exception"] from .exception import AergoException, CommunicationException from .conversion_exception import ConversionException from .general_exception import GeneralException
from django.core.management.base import BaseCommand, CommandError from cvrf.imports import * class Command(BaseCommand): help = 'Imports Red Hat CVRF' def handle(self, *args, **options): try: import_redhat_cvrf() except: raise CommandError('import_redhat_cvrf failed') self.stdout.write('Success...
# Copyright 2019, Google LLC. # # 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...