filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_23917
# 2. Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 # и 3 и т.д. При нечетном количестве элементов последний сохранить # на своем месте. Для заполнения списка элементов необходимо # использовать функцию input(). # создание пустого списка my_list =...
the-stack_106_23918
# Copyright 2020 The PyMC Developers # # 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 ag...
the-stack_106_23920
import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib import animation import numpy as np fig, ax = plt.subplots(2, 2, figsize=(9, 8.5)) topend = 50 angle_list = [] int_angle = [] count = [] sidelengths = [] area_list = [] for x in range(3,topend): #finds regular angle of an n-g...
the-stack_106_23922
# -*- coding: utf-8 -*- # Copyright 2020 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...
the-stack_106_23924
# Copyright (c) 2021 PaddlePaddle 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 app...
the-stack_106_23926
import typing from qtpy.QtCore import QPoint, QRectF, QSize, QSizeF, Qt from qtpy.QtGui import QCursor, QPainter from qtpy.QtWidgets import (QGraphicsDropShadowEffect, QGraphicsItem, QGraphicsObject, QGraphicsProxyWidget, QGraphicsSceneContextMenuEvent, ...
the-stack_106_23928
# Copyright The OpenTelemetry 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 or agreed to in ...
the-stack_106_23930
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('leonardo_form_pegastudio', '0031_auto_20180214_2209'), ] operations = [ migrations.AlterField( model_name='pegas...
the-stack_106_23932
import collections import torch from .. import dndarray, tiling from .. import factories __all__ = ["qr"] def qr(a, tiles_per_proc=1, calc_q=True, overwrite_a=False): """ Calculates the QR decomposition of a 2D DNDarray. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is upper-triangula...
the-stack_106_23935
""" Utilities Tests --------------- UnitTests for the utilities module """ import unittest import tempfile import os from damn_at import utilities as utils class UtilTests(unittest.TestCase): def test_is_existing_file_a(self): """Test returns false when given a bad path""" ret = utils.is_existin...
the-stack_106_23937
### LIBRARIES ### # Global libraries import os import sys import argparse import logging import pdb from tqdm import tqdm, trange import json from io import open import math import random from time import gmtime, strftime from timeit import default_timer as timer import numpy as np from tensorboardX import Summary...
the-stack_106_23938
import importlib import threading import logging import json import re import ckanext.hdx_service_checker.checks as checks import ckanext.hdx_service_checker.exceptions as exceptions log = logging.getLogger(__name__) LOCK = threading.RLock() def run_checks(config_file_path, runtime_vars): with open(config_fil...
the-stack_106_23939
# # 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_106_23940
# encoding: utf-8 """ Custom element classes related to paragraphs (CT_P). """ from docx.enum.fields import WD_FIELD_TYPE from ..ns import qn from ..xmlchemy import BaseOxmlElement, OxmlElement, ZeroOrMore, ZeroOrOne class CT_P(BaseOxmlElement): """ ``<w:p>`` element, containing the properties and text for ...
the-stack_106_23941
# # Protocol diffing tool from http://github.com/dsjoerg/s2protocol # # Usage: s2_cli.py --diff 38215,38749 # import sys import argparse import pprint from zephyrus_sc2_parser.s2protocol_fixed.versions import build def diff_things(typeinfo_index, thing_a, thing_b): if type(thing_a) != type(thing_b): prin...
the-stack_106_23942
''' Show a streaming, updating representation of Fourier Series. The example was inspired by `this video`_. Use the ``bokeh serve`` command to run the example by executing: bokeh serve fourier_animated.py at your command prompt. Then navigate to the URL http://localhost:5006/fourier_animated in your brows...
the-stack_106_23943
from __future__ import absolute_import import sys import numpy import sklearn.preprocessing import ctypes import faiss from ann_benchmarks.algorithms.base import BaseANN from ann_benchmarks.algorithms.faiss import Faiss class FaissIVF(Faiss): def __init__(self, metric, n_list): self._n_list = n_list ...
the-stack_106_23946
import os import sys from copy import deepcopy from distutils.core import Extension from ..openmp_helpers import add_openmp_flags_if_available from ..setup_helpers import _module_state, register_commands IS_TRAVIS_LINUX = os.environ.get('TRAVIS_OS_NAME', None) == 'linux' IS_APPVEYOR = os.environ.get('APPVEYOR', None)...
the-stack_106_23947
import zmq import sys import math import numpy class Broker: context = zmq.Context() router = context.socket(zmq.ROUTER) #poller = zmq.Poller() p = 0 def __init__(self, n): self.op = {"WorkDone":self.serverResponse, "serverFREE":self.serverFree} self.router.bind("tcp://*:5000") ...
the-stack_106_23948
import absl.flags import absl.testing import test_util absl.flags.DEFINE_string("model", None, "model path to execute") class ManualTest(test_util.TFLiteModelTest): def __init__(self, *args, **kwargs): super(ManualTest, self).__init__( absl.flags.FLAGS.model, *args, **kwargs ) de...
the-stack_106_23949
import midtransclient # initialize core api client object core = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Alternative way to initialize CoreApi client object: # core = midtransclient.CoreApi() # core.api_config.set( # is_production=Fals...
the-stack_106_23950
# -*- test-case-name: twisted.test.test_stdio.StandardInputOutputTests.test_hostAndPeer -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Main program for the child process run by L{twisted.test.test_stdio.StandardInputOutputTests.test_hostAndPeer} to test that ITransport.getHost() and IT...
the-stack_106_23951
""" Receieves notifications from remote queue. """ # pylint:disable=W0212 # pylint:disable=W0703 import threading import logging import json from azure.servicebus import ServiceBusService MESSAGE_WAIT_AFTER_ERROR = 5 MESSAGE_WAIT_TIMEOUT = 5 SBS_TOPIC_NAME = "webhooks" SBS_SUBSCRIPTION_NAME = "RPiOneSubscription" SBS...
the-stack_106_23952
# Copyright 2018 Changan Wang # 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, so...
the-stack_106_23954
# -*- coding: utf-8 -*- # !/usr/bin/env python import re import time import os from sqlalchemy import create_engine import pandas as pd import requests __author__ = 'berniey' re_limit = re.compile(r"^[0-9]*:[0-9]*") re_ip = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") re_time = re.compile(r"^\d{4}\-\d{2}\-\...
the-stack_106_23955
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2020 Fetch.AI Limited # # 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 ...
the-stack_106_23956
# coding: utf-8 # cf.http://d.hatena.ne.jp/white_wheels/20100327/p3 import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D def _numerical_gradient_no_batch(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[...
the-stack_106_23957
# -*- coding: utf-8 -*- """ DCGAN Tutorial ============== **Author**: `Nathan Inkawhich <https://github.com/inkawhich>`__ """ ###################################################################### # Introduction # ------------ # # This tutorial will give an introduction to DCGANs through an example. We # will train ...
the-stack_106_23958
# 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...
the-stack_106_23959
#!/usr/bin/python3 # -*- coding:utf-8 -*- from typing import * import numpy as np import pickle import time import rospy import math from geometry_msgs.msg import PoseStamped from nics_ros_host.msg import global_state from nics_ros_host.msg import vehicle_state from nics_ros_host.msg import human_cmd from nics_ros_hos...
the-stack_106_23961
""" Python 3 Object-Oriented Programming Chapter 12. Advanced Python Design Patterns """ from __future__ import annotations import contextlib import csv from pathlib import Path import sqlite3 from typing import ContextManager, TextIO, cast, Optional import sys def test_setup(db_name: str = "sales.db") -> sqlite3.Co...
the-stack_106_23962
import yaconfig metaconfig = yaconfig.MetaConfig( yaconfig.Variable("db", type=str, default="local.db", help="Database to use"), yaconfig.Variable("secret", type=bytes, default='_5#y2L"F4Q8z\n\xec]/', help="Flask secret"), # Note default values must be str. The are encoded to bytes using UTF8 yaconfig....
the-stack_106_23963
from flask import request from app.api.responses import Responses parties = [] class PoliticalParty: """this initializes political party class methods""" def __init__(self, name, hqAddress, logoUrl): self.party_id = len(parties) + 1 self.name = name self.hqAddress = hqAddress ...
the-stack_106_23965
""" Helpers to train with 16-bit precision. """ import numpy as np import torch as th import torch.nn as nn from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors import logger INITIAL_LOG_LOSS_SCALE = 20.0 def convert_module_to_f16(l): """ Convert primitive modules to float16. ...
the-stack_106_23968
# borg cli interface / toplevel archiver code import sys import traceback try: import argparse import collections import configparser import faulthandler import functools import hashlib import inspect import itertools import json import logging import os import re i...
the-stack_106_23969
from __future__ import absolute_import import json import numpy import logging from twisted.internet import defer from twisted.internet import reactor from twisted.internet.protocol import ClientFactory from twisted.protocols.basic import NetstringReceiver from autobahn.twisted.websocket import WebSocketServerProtoco...
the-stack_106_23973
from machine import * from machine import Pin, I2C import machine import ssd1306 import time import utime switchA = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) switchB = machine.Pin(13, machine.Pin.IN, value = 0) switchC = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP) point = 0 settime = (2018, 12, 1, 1...
the-stack_106_23974
import numpy as np import os import shutil import torch from torch.optim import Optimizer BEST_MODEL_PATH = 'model_best.pt' class AveTracker: def __init__(self): self.average = 0 self.sum = 0 self.counter = 0 def update(self, value, n): self.sum += value * n self.cou...
the-stack_106_23975
import glob import random import json import os import six import cv2 import numpy as np from tqdm import tqdm from time import time from .train import find_latest_checkpoint from .data_utils.data_loader import get_image_array, get_segmentation_array,\ DATA_LOADER_SEED, class_colors, get_pairs_from_paths from .mo...
the-stack_106_23977
""" A tree of operations, The output goes up the tree, inputs are down """ import inspect import logging import operator import re from base import base logging.basicConfig(filename='../log/{}.log'.format(__name__), level=logging.DEBUG) logger = logging.getLogger(__name__) class Optree: """ Apply operations ...
the-stack_106_23979
""" SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable...
the-stack_106_23981
#----------------------------------------------------------------------------- # Copyright (c) 2013-2021, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
the-stack_106_23982
from tkinter import * class Calc: def __init__(self): self.window = Tk() self.window.title("Calc") self.window.resizable(0, 0) # Travamos o tamanho da janela conforme os widgets. self.screen_numbers = Entry(self.window, justify="center", font="arial 20 bold", bg="#D9525E", fg="w...
the-stack_106_23984
from CybORG import CybORG import inspect from CybORG.Agents.SimpleAgents.BlueMonitorAgent import BlueMonitorAgent from CybORG.Agents.SimpleAgents.KeyboardAgent import KeyboardAgent from CybORG.Agents.Wrappers.RedTableWrapper import RedTableWrapper from CybORG.Agents import TestAgent from CybORG.Agents.Wrappers.FixedF...
the-stack_106_23986
""" 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 use this ...
the-stack_106_23988
from itertools import cycle from matplotlib import pyplot as plt from matplotlib import ticker from ._typing import ( Axes, Iterable, Opt_Iter_Float, Opt_Iter_Str, Opt_Plot, Optional, Plot, Sequence, TypeVar, ) from .orbitals._base_orbital import BaseOrbital def plotter( orbi...
the-stack_106_23990
import os import cv2 import numpy as np import pandas as pd import albumentations import torch from torch.utils.data import Dataset from tqdm import tqdm class MelanomaDataset(Dataset): def __init__(self, csv, mode, meta_features, transform=None): self.csv = csv.reset_index(drop=True) self.mode ...
the-stack_106_23993
# -*- coding: utf-8 -*- """Tests for the replace script and ReplaceRobot class.""" # # (C) Pywikibot team, 2015 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id: 04d8c30bad95dfbaedc34bdd259c60cecdacf082 $' # import os import pywikibot from pywikibot im...
the-stack_106_23995
import collections import sys import pip import json import changelogs import urllib.request from packaging import version from urllib.error import HTTPError, URLError from distutils.version import LooseVersion SECURITY_NOTICE_KEYWORDS = [ 'security', 'vulnerability', 'cve', 'xss', 'sql injection', ] DISPLAY_TAB...
the-stack_106_23996
import torch import random import numpy as np from tqdm import tqdm from scipy.signal import windows from torch.utils.data import DataLoader # Custom packages import net import data import utils import loss def getFreqWin(): """ Window used for weighing the Fourier amplitude spectrum. """ win = 100*...
the-stack_106_23997
class Solution: def maxNumber(self, nums1, nums2, k): def merge(arr1, arr2): res, i, j = [], 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i:] >= arr2[j:]: res.append(arr1[i]) i += 1 else: ...
the-stack_106_24000
############################################################################## # Copyright by The HDF Group. # # All rights reserved. # # # # Th...
the-stack_106_24003
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest class AppTestSorting(BaseNumpyAppTest): def test_argsort_dtypes(self): from numpy import array, arange assert array(2.0).argsort() == 0 nnp = self.non_native_prefix for dtype in ['int', 'float', 'int16', 'float32', '...
the-stack_106_24004
import tensorflow as tf from garage.tf.regressors import Regressor2 from tests.fixtures.models import SimpleMLPModel class SimpleMLPRegressor(Regressor2): """Simple GaussianMLPRegressor for testing.""" def __init__(self, input_shape, output_dim, name, *args, **kwargs): super().__init__(input_shape, ...
the-stack_106_24005
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # Developed by Lutkin Wang # Check prototype in # <codeblock props="ios mac" outputclass="language-objectivec">- (void)receiveMetadata:(NSData * _Nonnull)data # fromUser:(NSInteger)uid atTimestamp:(NSTimeInterval)timestamp; # </codeblock> import os import re log_name ...
the-stack_106_24006
"""Sensor platform for FireServiceRota integration.""" import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.re...
the-stack_106_24007
#!/usr/bin/python # Copyright (c) 2016 Simon van Heeringen <simon.vanheeringen@gmail.com> # # This module is free software. You can redistribute it and/or modify it under # the terms of the MIT License, see the file COPYING included with this # distribution. """Command line function 'maelstrom'""" import os from gimmem...
the-stack_106_24009
from manim import * # French Cursive LaTeX font example from http://jf.burnol.free.fr/showcase.html # Example 1 Manually creating a Template TemplateForFrenchCursive = TexTemplate( preamble=r""" \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage[T1]{fontenc} \usepackage[default]{fr...
the-stack_106_24013
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 17:17:30 2021 @author: Rafael Arenhart """ import os import time import numpy as np import tkinter as tk import tkinter.filedialog as filedialog import tkinter.messagebox as messagebox from PIL import Image, ImageTk import src.io as io import src.operations as opera...
the-stack_106_24014
# coding=utf-8 # Copyright 2020 HuggingFace Inc. 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 appli...
the-stack_106_24018
import cv2 import numpy as np import posenet.constants def valid_resolution(width, height, output_stride=16): target_width = (int(width) // output_stride) * output_stride + 1 target_height = (int(height) // output_stride) * output_stride + 1 return target_width, target_height def _process_input(source_...
the-stack_106_24019
# Copyright 2013 VMware, Inc. 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 a...
the-stack_106_24020
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
the-stack_106_24022
# Test the Corpus module. import sys import time import unittest import sb_test_support sb_test_support.fix_sys_path() from spambayes.Corpus import Corpus, ExpiryCorpus, MessageFactory # We borrow the test messages that test_sb_server uses. from test_sb_server import good1, spam1, malformed1 class simple_msg(objec...
the-stack_106_24023
import json import unittest from flask_caching import Cache from sqlalchemy import asc from app import app, db from apps.comments.models import CommentsSongs from apps.songs.models import Songs from apps.users.models import Users, UsersAccessLevels, UsersAccessMapping, UsersAccessTokens from apps.utils.time import ge...
the-stack_106_24024
# coding: utf-8 import pprint import six from enum import Enum class User: swagger_types = { 'id': 'int', 'planned_purge_date': 'datetime', 'scope': 'Scope', 'state': 'CreationEntityState', 'user_type': 'UserType', 'version': 'int', } attribute_map =...
the-stack_106_24025
from rubicon.objc import ( CGPoint, objc_method ) from travertino.size import at_least from toga_iOS.libs import ( NSLayoutAttributeBottom, NSLayoutAttributeLeading, NSLayoutAttributeTop, NSLayoutAttributeTrailing, NSLayoutConstraint, NSLayoutRelationEqual, UILabel, UITextView, ...
the-stack_106_24026
import json import threading import time from typing import Union, List, Set, Dict import attr from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager class BinanceMarketDataMessage: @staticmethod def from_dict(data: dict, obj_type): obj = obj_type()...
the-stack_106_24028
from bokeh.plotting import figure, output_file, save # prepare some data x = [1, 2, 3, 4, 5] y = [4, 5, 5, 7, 2] # set output to static HTML file output_file(filename="custom_filename.html", title="Static HTML file") # create a new plot with a specific size p = figure(sizing_mode="stretch_width", max_width=500, plot...
the-stack_106_24031
#!/usr/bin/python """ modules.py """ from __future__ import print_function import os from mylib import log from testpkg import module1 from testpkg.module2 import func2 def run_tests(): # type: () -> None module1.func1() func2() dog = Dog('white') dog.Speak() cat = module1.Cat() cat.Speak() cat2 ...
the-stack_106_24033
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
the-stack_106_24036
_base_ = [ '../_base_/models/setr_mlala_convfuse.py', '../_base_/datasets/cityscapes_768x768_foggy.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] model = dict( backbone=dict(img_size=768,pos_embed_interp=True, drop_rate=0.,mla_channels=256, model_name='de...
the-stack_106_24037
# # Copyright 2018 Analytics Zoo 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 or agreed to...
the-stack_106_24040
def readconfig(fn:str): with open(fn,"r") as fp: buf="" out={} while 1: line = fp.readline() if line == "": break if line.strip() == "" or line.strip()[0]=="#": continue if "#" in line: line=line...
the-stack_106_24042
# coding: utf-8 import numpy as np from common_function import * from util import im2col, col2im class Relu: def __init__(self): self.mask = None def forward(self, x): self.mask = (x <= 0) out = x.copy() out[self.mask] = 0 return out def backward(self, dout): ...
the-stack_106_24043
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'recipes_project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/doc/', include...
the-stack_106_24044
#/usr/bin/env python try: from flask import Flask except ImportError: print("\n[X] Please install Flask:") print(" $ pip install flask\n") exit() from optparse import OptionParser from wordpot.logger import * from werkzeug.routing import BaseConverter from wordpot.plugins_manager import PluginsManage...
the-stack_106_24045
"""Demo platform that has two fake binary sensors.""" from homeassistant.components.binary_sensor import BinarySensorEntity from . import DOMAIN async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo binary sensor platform.""" async_add_entities( [ ...
the-stack_106_24046
#!/usr/bin/env python3 import sys import os import re import json import merger import numpy import matplotlib.pyplot as plt import datetime class Object: pass class GrowingList( list ): def __getitem__( self, index ): if index >= len(self): self.extend( [0] * ( index + 1 - len( self ) ) ...
the-stack_106_24047
import logging import argparse import configparser import os import torch import numpy as np import gym from crowd_nav.utils.explorer import Explorer from crowd_nav.policy.policy_factory import policy_factory from crowd_sim.envs.utils.robot import Robot from crowd_sim.envs.policy.orca import ORCA import crowd_sim.envs...
the-stack_106_24048
import argparse import runpy import sys from .logger import LogLevel from .reloader import start_reloader def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", dest="module", required=True) parser.add_argument("-w", dest="watch", action="append") parser.add_argument("-v", dest="ver...
the-stack_106_24049
# Copyright 2021 AlQuraishi Laboratory # # 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 i...
the-stack_106_24050
import lambentlight.client as client async def show_info(): """ Shows the basic information of the LambentLight instance. """ # Request the basic info and print it info = await client.get("/") print("{0} v{1} running on {2}".format(info["prog"], info["version"], client.host))
the-stack_106_24051
""" Chronic is a module designed to do simple profiling of your python code while giving you full control of the granularity of measurement. It maintains the hierarchy of the call tree, but only at the levels you care about. The timing results can easily be captured as JSON and logged for analysis in postgres or mong...
the-stack_106_24053
import torch.utils.data as data import torch class DataIterator(object): def __init__(self, dataloader): self.dataloader = dataloader self.iterator = enumerate(self.dataloader) def __next__(self): try: _, data = next(self.iterator) except Exception: sel...
the-stack_106_24054
from django.shortcuts import render #from django.http import HttpResponse #from django.http import Http404 #from lxml import etree import imports from eulexistdb import db # load the 2014 and 2015 cve files on server launch #cvestub = "static/data/nist.gov/nvd/cve/nvdcve-2.0-" #tree2014 = etree.parse(cvestub+"2014...
the-stack_106_24055
import sys from types import MappingProxyType, DynamicClassAttribute __all__ = [ 'EnumMeta', 'Enum', 'IntEnum', 'Flag', 'IntFlag', 'auto', 'unique', ] def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return ( hasattr(obj, '__get...
the-stack_106_24056
# Copyright (c) Microsoft Corporation and Fairlearn contributors. # Licensed under the MIT License. # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/config...
the-stack_106_24057
""" This requires the MLCube 2.0 that's located somewhere in one of dev branches. """ import os import click import logging import typing as t from omegaconf import (OmegaConf, DictConfig) logger = logging.getLogger(__name__) class MLCubeConfig(object): @staticmethod def ensure_values_exist(config: DictCon...
the-stack_106_24058
"""This module contains the general information for FabricSanCloudFsmStage ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class FabricSanCloudFsmStageConsts: LAST_UPDATE_TIME_ = "" NAME_SWITCH_MODE_BEGIN = "SwitchModeB...
the-stack_106_24059
import os from PIL import Image ''' The file is used for image transformation: horisontal/vertical scale, crop Currently only 1 of 3 mode ('crop') is used in the app. Not sure that it's reasonably to delete other two modes. May need it later. ''' SCALE_WIDTH = 'w' SCALE_HEIGHT = 'h' SCALE_BOTH = 'crop' ...
the-stack_106_24061
class Solution: def solve(self, points): edges = [[abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j] for i in range(len(points)) for j in range(i+1,len(points))] edges.sort() parents = list(range(len(points))) ans = 0 def union(x,y,parents): ...
the-stack_106_24063
import logging logging.basicConfig(level=logging.DEBUG) import os from slack_bolt.app import App from slack_bolt.context import BoltContext bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") app = App(signing_secret="will-be-removed-soon", token=bot_token) @app.event("app_mention") def mention(con...
the-stack_106_24064
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import random import numpy as np # type: ignore from onnx import helper, defs, numpy_helper, checker from onnx import AttributeProto, TensorProto, GraphProto, Denotati...
the-stack_106_24065
# encoding: UTF-8 # # The MIT License (MIT) # # Copyright (c) 2016-2019 yutiansut/QUANTAXIS # # 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-stack_106_24067
"""Test the binascii C module.""" from test import support import unittest import binascii import array # Note: "*_hex" functions are aliases for "(un)hexlify" b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu', 'hexlify', 'rlecode_hqx'] a2b_functions = ['a2b_base64', 'a2b_hex', ...
the-stack_106_24068
from __future__ import annotations import numpy as np from typing import Union, List, Tuple class Calibration: """ A class containing calibration information for spectra or Q-matrices. This class handles all matters relating to calibrations, energy binning etc. Attributes ---------- n_channe...
the-stack_106_24069
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. import aria2p from asyncio import sleep from subprocess import PIPE, Popen from userbot import LOGS, CMD_HELP from userb...
the-stack_106_24071
import json import unittest import urllib.request from urllib.error import URLError from bs4 import BeautifulSoup from django import template from django.core.exceptions import ValidationError from django.test import TestCase, override_settings from django.urls import reverse from mock import patch from wagtail.core ...
the-stack_106_24075
import pytest import eff def test_init(): e = eff.Effects(print=print) assert e.print is print def test_short_alias(): assert eff.ects is eff.Effects e = eff.ects(print=print) assert e.print is print def test_no_attr(): e = eff.Effects() with pytest.raises(AttributeError): e.pr...