filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_4882
#!/usr/bin/env python3 import os import subprocess import pypact as pp import matplotlib.pyplot as plt do_collapse = True show_plot = True group = 709 inventory = [('Fe', 1.0)] # files file def createfiles(): nuclear_data_base = os.getenv('NUCLEAR_DATA', os.path.join(os.sep, 'opt', 'fispact', 'nuclear_data')) ...
the-stack_0_4883
# # * The source code in this file is developed independently by NEC Corporation. # # # NLCPy License # # # Copyright (c) 2020-2021 NEC Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following cond...
the-stack_0_4886
#!/usr/bin/env python # -*- coding: utf-8 -*- __authors__ = ["Katharina Eggensperger", "Matthias Feurer"] __contact__ = "automl.org" from collections import OrderedDict from itertools import product from io import StringIO import sys import pyparsing from ConfigSpace.configuration_space import ConfigurationSpace fr...
the-stack_0_4888
# -*- coding: utf-8 -*- # # Copyright (C) 2013-2014 Germain Z. <germanosz@gmail.com> # # This program 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 ...
the-stack_0_4890
from functools import lru_cache from findimports import ModuleGraph from pathlib import Path from onegov.core import LEVELS def test_hierarchy(): """ Originally, onegov.* modules were separated into separate repositories and deployed individually to PyPI. This meant that each module would list the depen...
the-stack_0_4891
# -*- coding: utf-8 -*- try: from models.interface import AbstractModel except: from interface import AbstractModel import torch import torch.nn.functional as F import torch.nn as nn import torchvision import torchvision.datasets as datasets import matplotlib.pyplot as plt import numpy as np import pickle from tor...
the-stack_0_4892
# Copyright (c) Microsoft Corporation # # All rights reserved. # # MIT License # # 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...
the-stack_0_4893
import argparse from sniffles.feature import FeatureParser from sniffles.rule_formats import (PetabiPacketClassifierFormat, RegexFormat, RuleFormat, SnortRuleFormat) def main(): parser = argparse.ArgumentParser(description='Random Rule Generator') parser.add_argument('-c', ...
the-stack_0_4894
import requests from PIL import Image from datainfo import file_list for item in file_list: item_file = '../items/'+item items = open(item_file, 'r').read().split() for name in items: print('downloading', name) url = 'https://gameinfo.albiononline.com/api/gameinfo/items/' response...
the-stack_0_4895
# Copyright 2017 IBM Corp. 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 applicable law or agre...
the-stack_0_4897
import copy def compose(a, b, keep_null=False): """ Compose two operations into one. ``keep_null`` [default=false] is a boolean that controls whether None/Null attributes are retrained. """ if a is None: a = {} if b is None: b = {} # deep copy b, but get rid of None ...
the-stack_0_4899
n, l, t = input().split() n, l, t = int(n), int(l), int(t) p = [int(i) for i in input().split()] sp = sorted(p) map_set = list() for i in p: map_set.append(sp.index(i)) ori = [1] * n for ti in range(t): for i in range(n-1): if sp[i] == sp[i+1]: ori[i] ^= (-1^1) ori[i+1] ^= (-1...
the-stack_0_4901
""" This module contains the panel API. """ import logging from pyqode.core.api.mode import Mode from pyqode.qt import QtWidgets, QtGui def _logger(): """ Returns module's logger """ return logging.getLogger(__name__) class Panel(QtWidgets.QWidget, Mode): """ Base class for editor panels. A pan...
the-stack_0_4906
from face_detection import Model_face_detection from facial_landmarks_detection import Model_landmarks from head_pose_estimation import Model_pose from gaze_estimation import Model_gaze from argparse import ArgumentParser from mouse_controller import MouseController from input_feeder import InputFeeder import cv2 i...
the-stack_0_4907
from lib import rpclib import json import time import re import sys import pickle import platform import os import subprocess import signal from slickrpc import Proxy from binascii import hexlify from binascii import unhexlify from functools import partial from shutil import copy operating_system = platform.system() ...
the-stack_0_4910
"""Define a RainMachine controller class.""" # pylint: disable=too-few-public-methods,too-many-instance-attributes from datetime import datetime, timedelta from typing import Awaitable, Callable, Optional from regenmaschine.api import API from regenmaschine.diagnostics import Diagnostics from regenmaschine.parser impo...
the-stack_0_4911
import subprocess import threading import platform import socket import os from electrum import constants from electrum.plugin import BasePlugin, hook from electrum.i18n import _ from electrum.util import UserFacingException from electrum.logging import get_logger from electrum.network import Network _logger = get_lo...
the-stack_0_4912
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
the-stack_0_4914
import streamlit as st import urllib3 import numpy as np from PIL import Image import cv2 import requests import socket #================================ # Message Headers #================================= COMMAND_START=bytes("<command>",'utf-8') COMMAND_END=bytes("</command>","utf-8") IMAGE_START=by...
the-stack_0_4916
#!/usr/bin/python3 # # Copyright (c) Siemens AG, 2020 # tiago.gasiba@gmail.com # # SPDX-License-Identifier: MIT # # # NOTE this was tested on Python 3.6.9 # NOTE subprocess seems to return empty stdout when ASan reports an error import sys import os import os.path import signal import subprocess import uuid from p...
the-stack_0_4918
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf import settings from django.test import TestCase, override_settings from unittest import skip from zerver.lib.avatar import avatar_url from zerver.lib.bugdown import url_filename from zerver.lib.test_helpers import AuthedTestCase from zerv...
the-stack_0_4920
import numpy as np import cv2 import math import argparse import time def calculate_area(contours): """ Calculate contour area Paramters: contours: List[numpy.ndarray] Returns: List[numpy.ndarray]: contours_area """ contours_area = [] # calculate area and filter into new arr...
the-stack_0_4921
import matplotlib.pyplot as plt import pymc3 as pm import numpy as np # import pydevd # pydevd.set_pm_excepthook() np.seterr(invalid='raise') data = np.random.normal(size=(2, 20)) model = pm.Model() with model: x = pm.Normal('x', mu=.5, tau=2. ** -2, shape=(2, 1)) z = pm.Beta('z', alpha=10, beta=5.5) d...
the-stack_0_4922
import numpy as np import pandas as pd import os import sys from scipy import sparse import utils PAPER_COUNT_FILE = sys.argv[1] YEAR = int(sys.argv[3]) WINDOW_LENGTH = int(sys.argv[4]) OUTPUT_NODE_FILE = sys.argv[5] OUTPUT_EDGE_FILE = sys.argv[6] year = YEAR if __name__ == "__main__": # Connect to the database ...
the-stack_0_4924
from pathlib import Path import requests import re from one import params from one.webclient import http_download_file import SimpleITK as sitk def download_histology_data(subject, lab): if lab == 'hoferlab': lab_temp = 'mrsicflogellab' elif lab == 'churchlandlab_ucla': lab_tem...
the-stack_0_4925
""" sphinx.domains.python ~~~~~~~~~~~~~~~~~~~~~ The Python domain. :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import builtins import inspect import re import sys import typing import warnings from inspect import Parameter from typi...
the-stack_0_4926
""" In this file one can find the implementation of helpful class and functions in order to handle the given dataset, in the aspect of its structure. Here is the implementation of helpful class and functions that handle the given dataset. """ import json import csv from scipy.stats import zscore from torch import Tens...
the-stack_0_4927
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
the-stack_0_4929
from os.path import join from os.path import exists import torch import argparse import os import torch.nn.functional as F import models from evaluation.PerceptualSimilarity.models import PerceptualLoss from evaluation.PerceptualSimilarity.util import util import glob import pickle import numpy as np def plot_vid(vid...
the-stack_0_4931
""" Define the NonlinearRunOnce class. This is a simple nonlinear solver that just runs the system once. """ from openmdao.recorders.recording_iteration_stack import Recording from openmdao.solvers.solver import NonlinearSolver from openmdao.utils.general_utils import warn_deprecation from openmdao.utils.mpi import mu...
the-stack_0_4932
# -*- coding: utf-8 -*- # # txThings asyncio branch documentation build configuration file, created by # sphinx-quickstart on Wed Jun 4 09:40:16 2014. # # 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 # autogener...
the-stack_0_4934
import tempfile import time import os import os.path from ovos_utils.log import LOG def get_ipc_directory(domain=None, config=None): """Get the directory used for Inter Process Communication Files in this folder can be accessed by different processes on the machine. Useful for communication. This is...
the-stack_0_4935
""" Author: Zeliha Ural Merpez Date: March,13 2021 """ import requests import json import pandas as pd from bs4 import BeautifulSoup import altair as alt import numpy as np from math import sin, cos, sqrt, atan2, radians import matplotlib.pyplot as plt def get_keys(path): with open(path) as f: return js...
the-stack_0_4937
# Load selenium components from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait, Select from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import time def course_desc(): #...
the-stack_0_4938
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals import unittest import os from pymatgen.io.feff.outputs import LDos, Xmu test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ...
the-stack_0_4939
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/lvis_instance.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] model = dict( roi_head=dict( bbox_head=dict(num_classes=1230), mask_head=dict(num_classes=1230))) test_cfg = dict( rcnn=d...
the-stack_0_4940
"""Lazy version of the dataset for training TDC and CMC.""" from typing import Any, List, Tuple import cv2 import librosa import numpy as np import torch from skvideo.io import FFmpegReader from torch.utils.data import Dataset class LazyTDCCMCDataset(Dataset): """ Dataset for training TDC and CMC. Datas...
the-stack_0_4941
import requests import json host = "s-platform.api.opendns.com" api_key = "a0b1c2d3-e4f5-g6h7-i8j9-kalbmcndoepf" print(f"\n==> Finding all of the domains in a custom enforcement list") url = f"https://{host}/1.0/domains?customerKey={api_key}" headers = {'Authorization':'Bearer ' + api_key} try: response = requests...
the-stack_0_4942
"""Tests for device finding functionality.""" import unittest from unittest.mock import patch from pysyncdroid.exceptions import DeviceException from pysyncdroid.find_device import ( get_connection_details, get_mtp_details, lsusb, ) mock_lsub_parts = [ "Bus 002 Device 001: ID 0123:0001 test_vendor ...
the-stack_0_4944
# Copyright 2013 IBM Corp. # # 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...
the-stack_0_4945
import os import urllib.request import subprocess import time import ssl import requests from test_workflow.test_cluster import TestCluster, ClusterCreationException class LocalTestCluster(TestCluster): ''' Represents an on-box test cluster. This class downloads a bundle (from a BundleManifest) and runs it as ...
the-stack_0_4947
# Copyright 2016-2017 Capital One Services, 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 ...
the-stack_0_4949
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import pytest from indico.modules.users import User pytest_plugins = 'indico.modules.rb.testing.fixture...
the-stack_0_4950
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy as sp import scanpy as sc def pearson_residuals(counts, theta, clipping=True): '''Computes analytical residuals for NB model with a fixed theta, clipping outlier residuals ...
the-stack_0_4952
import contextlib import io from elftools.elf.elffile import ELFFile from elftools.dwarf.die import DIE from elftools.dwarf.die import AttributeValue from elftools.dwarf.descriptions import describe_DWARF_expr, set_global_machine_arch from elftools.dwarf.locationlists import LocationEntry, LocationExpr, Location...
the-stack_0_4954
from __future__ import absolute_import, division, print_function # DIALS version numbers are constructed from # 1. a common prefix __dials_version_format = "DIALS %s" # 2. the most recent annotated git tag (or failing that: a default string) __dials_version_default = "2.dev" # 3. a dash followed by the number of co...
the-stack_0_4955
from base import api from .helpers import TestsDatasets from .helpers import LibraryPopulator from .helpers import wait_on_state class LibrariesApiTestCase( api.ApiTestCase, TestsDatasets ): def setUp( self ): super( LibrariesApiTestCase, self ).setUp() self.library_populator = LibraryPopulator( ...
the-stack_0_4960
import pandas as pd import numpy as np from typing import Dict, Any, Union, Tuple, AnyStr from sklearn import datasets, metrics, model_selection from sklearn.model_selection import train_test_split, cross_val_score, cross_validate from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClas...
the-stack_0_4961
# 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 ...
the-stack_0_4962
import argparse import math from urllib.request import urlopen import sys import os import json import subprocess import glob from braceexpand import braceexpand from types import SimpleNamespace import os.path from omegaconf import OmegaConf import torch from torch import nn, optim from torch.nn import functional a...
the-stack_0_4963
import subprocess import typer from typer.testing import CliRunner from docs_src.first_steps import tutorial004 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_help(): result = runner.invoke(app, ["--help"]) assert result.exit_code == 0 assert "Arguments:" in result.ou...
the-stack_0_4964
# coding: utf-8 """ Dyspatch API # Introduction The Dyspatch API is based on the REST paradigm, and features resource based URLs with standard HTTP response codes to indicate errors. We use standard HTTP authentication and request verbs, and all responses are JSON formatted. See our [Implementation Guide](ht...
the-stack_0_4965
import sys from typing import ( # type: ignore TYPE_CHECKING, AbstractSet, Any, ClassVar, Dict, Generator, List, Mapping, NewType, Optional, Sequence, Set, Tuple, Type, Union, _eval_type, cast, get_type_hints, ) from typing_extensions import Anno...
the-stack_0_4966
import math import collections class NaiveBayes: classes = ['spam', 'ham'] # Word Lists spam_list = [] ham_list = [] spam_file_count = 0 ham_file_count = 0 def __init__(self, spam_list, ham_list, spam_file_count, ham_file_count): self.spam_list = spam_list self.ham_list = ...
the-stack_0_4968
import torch from torch import nn import torch.nn.functional as F """ Differences with V-Net Adding nn.Tanh in the end of the conv. to make the outputs in [-1, 1]. """ class ConvBlock(nn.Module): def __init__(self, n_stages, n_filters_in, n_filters_out, normalization='none'): super(ConvBlock, self).__init...
the-stack_0_4969
"""Support for IKEA Tradfri covers.""" import logging from pytradfri.error import PytradfriError from homeassistant.components.cover import ( CoverDevice, ATTR_POSITION, SUPPORT_OPEN, SUPPORT_CLOSE, SUPPORT_SET_POSITION, ) from homeassistant.core import callback from .const import DOMAIN, KEY_GATE...
the-stack_0_4971
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """ Utilities for downloadi...
the-stack_0_4973
''' A Keras port of the original Caffe SSD300 network. 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...
the-stack_0_4975
#! /usr/bin/env python """ Copyright 2015-2018 Jacob M. Graving <jgraving@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required...
the-stack_0_4977
""" Web Map Tile Service time dimension demonstration ------------------------------------------------- This example further demonstrates WMTS support within cartopy. Optional keyword arguments can be supplied to the OGC WMTS 'gettile' method. This allows for the specification of the 'time' dimension for a WMTS layer ...
the-stack_0_4978
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` tests.integration.shell.master ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' # Import python libs from __future__ import absolute_import import os import signal import shutil # Import 3rd-party libs import yaml # Import salt libs...
the-stack_0_4979
"""Create a camera asset.""" import bpy from openpype.pipeline import legacy_io from openpype.hosts.blender.api import plugin, lib, ops from openpype.hosts.blender.api.pipeline import AVALON_INSTANCES class CreateCamera(plugin.Creator): """Polygonal static geometry""" name = "cameraMain" label = "Camer...
the-stack_0_4981
"""The tests for the WUnderground platform.""" import unittest from homeassistant.components.sensor import wunderground from homeassistant.const import TEMP_CELSIUS, LENGTH_INCHES from tests.common import get_test_home_assistant VALID_CONFIG_PWS = { 'platform': 'wunderground', 'api_key': 'foo', 'pws_id':...
the-stack_0_4983
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from six.moves.urllib import request import glob import os import platform # Mac or Linux special for uncompress command import errno import sys import numpy as np import codecs import re import subprocess import sys import ...
the-stack_0_4986
# -*- coding: UTF-8 -*- # Copyright (c) 2018, Xycart # License: MIT License from __future__ import unicode_literals import sys, os # standard modules from dxfGenerator import dxfGenerator import ConvertPingYin SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__)) ATD_DIR = os.path.dirname(SCRIP...
the-stack_0_4989
from pathlib import Path from typing import List, Optional from ipywidgets import HBox, SelectMultiple from .core import JSONType from .mixins import TextTrainerMixin, sample_from_iterable from .widgets import Solver, GPUIndex, Engine alpha = "abcdefghijklmnopqrstuvwxyz0123456789,;.!?:’\“/\_@#$%^&*~`+-=<>()[]{}" c...
the-stack_0_4990
#!/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. from collections import OrderedDict from unittest import mock import numpy as np from ax.core.metric import Metric fro...
the-stack_0_4991
import matplotlib.pyplot as plt import numpy as np with open("log1.txt",'r',encoding='utf-8') as f: train_x = [] train_y = [] dev_x = [] dev_y = [] step = 0 log=f.readline() while(log): log = log.split() if "Step" in log: index = log.index("Step") step...
the-stack_0_4992
# Copyright (c) 2021 AllSeeingEyeTolledEweSew # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERC...
the-stack_0_4993
import sys class Graph: def __init__(self, v): self.vertices_count = v self.vertices = [i for i in range(v)] self.adj_mat = [[0 for _ in range(v)] for _ in range(v)] def connect_all(self): self.adj_mat = [] for i in range(self.vertices_count): raw_mat = [] ...
the-stack_0_4994
# 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 ...
the-stack_0_4997
from typing import List, Optional, Set, Dict import aiosqlite from mint.protocols.wallet_protocol import CoinState from mint.types.blockchain_format.coin import Coin from mint.types.blockchain_format.sized_bytes import bytes32 from mint.types.coin_record import CoinRecord from mint.util.db_wrapper import DBWrapper from...
the-stack_0_4999
# # Copyright (c) 2015, Adam Meily <meily.adam@gmail.com> # Pypsi - https://github.com/ameily/pypsi # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # ...
the-stack_0_5001
import segmentation_models_pytorch as smp import torch.optim from .losses import CombinedLoss, BinaryFocalLoss def get_optimizer(config, model): """ """ optimizer_name = config.SOLVER.OPTIMIZER if optimizer_name == 'adam': return torch.optim.Adam( model.parameters(), l...
the-stack_0_5002
import asyncio import logging import time from typing import Callable from covid.protocols.protocol_message_types import ProtocolMessageTypes log = logging.getLogger(__name__) async def time_out_assert_custom_interval(timeout: int, interval, function, value=True, *args, **kwargs): start = time.time() while ...
the-stack_0_5003
# encoding: UTF-8 __author__ = 'CHENXY' # C++和python类型的映射字典 type_dict = { 'int': 'int', 'char': 'string', 'double': 'float', 'short': 'int' } def process_line(line): """处理每行""" if '///' in line: # 注释 py_line = process_comment(line) elif 'typedef' in lin...
the-stack_0_5004
# coding=utf-8 # Copyright 2020, The T5 Authors and HuggingFace 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 ...
the-stack_0_5008
import os import sys from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) requires = ['opencv-python', 'numpy', 'gym'] setup(name='Flappy_Bird_with_Segmentation', version='1.0', description='Flappy bird environment with ground truth segmentation', a...
the-stack_0_5009
#!/usr/bin/env python # coding: utf-8 import argparse import logging import os import sys import time import numpy as np import pandas as pd import scanpy as sc import torch from sklearn import preprocessing from sklearn.model_selection import train_test_split from torch import nn, optim from torch.optim import lr_sche...
the-stack_0_5010
from cellpose import io, models, metrics, plot from pathlib import Path from subprocess import check_output, STDOUT import os, shutil def test_class_train(data_dir, image_names): train_dir = str(data_dir.joinpath('2D').joinpath('train')) model_dir = str(data_dir.joinpath('2D').joinpath('train').joinpath('model...
the-stack_0_5011
import torch # transpose FLIP_LEFT_RIGHT = 0 FLIP_TOP_BOTTOM = 1 class Keypoints(object): def __init__(self, keypoints, size, mode=None): # FIXME remove check once we have better integration with device # in my version this would consistently return a CPU tensor device = keypoints.device ...
the-stack_0_5012
""" make_bmap.py Creates an image that can be used as a bump mapping texture. Mahesh Venkitachalam shader.in """ import numpy as np from PIL import Image from math import sqrt def main(): NX, NY = 256, 256 nmap = np.zeros([NX, NY, 3], np.float32) r = 32.0 ...
the-stack_0_5014
# coding: utf-8 """ Pure Storage FlashBlade REST 1.9 Python SDK Pure Storage FlashBlade REST 1.9 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/). OpenAPI spec version: 1.9 Contact: i...
the-stack_0_5015
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # MicroPython documentation build configuration file, created by # sphinx-quickstart on Sun Sep 21 11:42:03 2014. # # 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 ...
the-stack_0_5018
from concurrent.futures import Future from functools import wraps from typing import Callable, Optional, TypeVar, Union CallableReturnsInt = Callable[..., int] IntOrBool = TypeVar( "IntOrBool", int, bool, ) CallableReturnsIntOrBool = TypeVar( "CallableReturnsIntOrBool", Callable[..., int], Ca...
the-stack_0_5019
import pytest from mixer.backend.django import mixer from .. import forms pytestmark = pytest.mark.django_db class TestPostForm: def test_form(self): form = forms.PostForm(data={}) assert form.is_valid() is False, ('Should be invalid if no data is given') data = {'body': 'Hello'} f...
the-stack_0_5020
""" This file offers the methods to automatically retrieve the graph Janthinobacterium sp. Marseille. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein...
the-stack_0_5026
# -*- coding: utf-8 -*- # Copyright 2018 ICON Foundation # # 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 o...
the-stack_0_5029
import xml.etree.ElementTree as ET from nltk.tokenize import WordPunctTokenizer from sentence_splitter import SentenceSplitter from src.parser import Word, Dataset class Aspect(object): def __init__(self, begin=0, end=0, target="", polarity=1, category="", aspect_type=0, mark=0): self.type_values = { ...
the-stack_0_5030
import json import pytest from unittest import mock from asynctest import patch from blebox_uniapi.box import Box from blebox_uniapi import error pytestmark = pytest.mark.asyncio @pytest.fixture def mock_session(): return mock.MagicMock(host="172.1.2.3", port=80) @pytest.fixture def data(): return { ...
the-stack_0_5031
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Megvii Technology # # 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 #...
the-stack_0_5033
# qubit number=3 # total number=12 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collectio...
the-stack_0_5034
import logging from enum import Enum import json from iota import Address, TryteString logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) vendor_address = "OPMGOSBITOTGSZRESXAO9SGPAOOFEQ9OIPEMY9DEHPVOUULUHXIHHWBNFNMKXPEZWIMHB9JPEXSE9SFLA" class ChargingStationStatus(Enum): FREE = "fre...
the-stack_0_5035
# IMPORTATION STANDARD import gzip import json # IMPORTATION THIRDPARTY import pytest # IMPORTATION INTERNAL from openbb_terminal.cryptocurrency.defi import llama_view def filter_json_data(response): """To reduce cassette size.""" headers = response["headers"] if "FILTERED" in headers: return r...
the-stack_0_5037
from bs4 import BeautifulSoup from inspect import getmembers import urllib.request import urllib.error import urllib.parse import threading import requests import sys import pprint import string import time import threading import hashlib import psycopg2 class Novoterm(threading.Thread): item_links = list() category...
the-stack_0_5038
"""Provides RootCauseAnalysis class for computing RCA.""" import warnings from itertools import combinations from math import isclose from textwrap import wrap from typing import Dict, List, Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from chaos_genius.core.rca.constants import TIME_...
the-stack_0_5040
import torch.nn as nn import torch.nn.functional as F import torch from einops.layers.torch import Rearrange from einops import rearrange import numpy as np from typing import Any, List import math import warnings from collections import OrderedDict __all__ = ['ConTBlock', 'ConTNet'] r""" The following trunc_norm...
the-stack_0_5043
# -*- coding: utf-8 -*- # Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
the-stack_0_5044
# coding: utf-8 """ Ed-Fi Operational Data Store API The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reas...
the-stack_0_5045
from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): return {'hello': 'world'} api.add_resource(HelloWorld, '/') if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')