filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_24257
"""Adapted from: https://github.com/mrlibw/ControlGAN""" import numpy as np import torch import torch.nn as nn import skimage.transform from PIL import Image, ImageDraw, ImageFont def normalize(similarities, method="norm"): if method == "norm": return (similarities - similarities.mean(axis=0)) / (simi...
the-stack_106_24258
import os def combine(x): so_far = [] for i in x[0]: if len(x) > 1: for j in combine(x[1:]): so_far.append(' '.join([i, j])) else: so_far.append(i) return so_far args = [ ['100'], ['0'], ['0.5', '1'], ['0.4', '0.8'], ['0.97', '0.99'] ] for idx, arg in enumerate(combine(args)): os.system('pytho...
the-stack_106_24262
import time import heapq from collections import defaultdict, deque from typing import DefaultDict, Dict, List, Tuple, Set import numpy as np from .constants import Constants from .game_map import GameMap, RESOURCE_TYPES from .game_objects import Player, Unit, City, CityTile from .game_position import Position from ....
the-stack_106_24263
import calendar import pytest from collections import OrderedDict from datetime import datetime, timedelta from tests.base import BaseEventsTest from snuba import settings from snuba.datasets.factory import enforce_table_writer from snuba.processor import ( InvalidMessageType, InvalidMessageVersion, Proce...
the-stack_106_24266
import sys class Node: def __init__(self, data): self.right=self.left=None self.data = data class Solution: def insert(self, root, data): if root == None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) ...
the-stack_106_24269
## Program: VMTK ## Language: Python ## Date: May 2, 2018 ## Version: 1.4 ## Copyright (c) Richard Izzo, Luca Antiga, All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR...
the-stack_106_24270
# -*- coding: utf-8 -*- """ This file is covered by the LICENSING file in the root of this project. """ import sys sys.path.append("..") from functools import wraps from werkzeug.exceptions import BadRequest, InternalServerError from dateutil import parser from flask_restful import Resource from flask import request...
the-stack_106_24271
import telegram from telegram.ext import Updater,CommandHandler,MessageHandler, Filters import logging import subprocess as sp import requests import json import threading from bomber import kill import shodan import speech_recognition as sr from pydub import AudioSegment import re enabled_users=[] ippsec_list=[] # a...
the-stack_106_24272
""" Terminal creation and cleanup. Utility functions to run a terminal (connected via socat(1)) on each host. Requires socat(1) and xterm(1). Optionally uses gnome-terminal. """ from os import environ from mininet.log import error from mininet.util import quietRun, errRun def tunnelX11( node, display=None): """...
the-stack_106_24273
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_fullhunt # Purpose: Identify domain attack surface using FullHunt API. # # Author: <bcoles@gmail.com> # # Created: 2021-10-26 # Copyright: (c) bcoles 2021 # Licence: MIT # ----...
the-stack_106_24275
"""Plugin declaration for netbox_onboarding. (c) 2020 Network To Code 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_106_24276
import json import webob class Response: def __init__(self): self.json = None self.html = None self.text = None self.content_type = None self.status_code = 200 def __call__(self, environ, start_response): self.set_body_and_content_type() resp = webob.R...
the-stack_106_24277
# 1 # Usate l'algoritmo CCRP per trovare un piano di evacuazione nel grafo della Città di San Francisco. # # I nodi sorgente del piano sono i tre ingressi autostradali della città: # - nodo 3718987342 (Golden Gate Bridge) # - nodo 915248218 (Oakland Bay Bridge) # - nodo 65286004 (James Lick Freeway) # # I nodi de...
the-stack_106_24282
from django.utils.html import format_html_join from django.conf import settings from wagtail.core import hooks @hooks.register("insert_editor_js") def editor_js(): js_files = ["js/realtime_preview.js"] return format_html_join( "\n", '<script src="{0}{1}"></script>', ((settings.STATIC...
the-stack_106_24283
# Copyright (C) 2012 Google 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 code must retain the above copyright # notice, this list of conditions and the ...
the-stack_106_24285
from . base import BaseGame from .. import colors from .. util import srange from random import randint, choice from time import time from .. import font clist = [ colors.Off, colors.Red, colors.Green ] OPEN = 0 FENCE = 1 CLOSED = 2 class Ball(): def __init__(self): self.x = randint(0, 15) ...
the-stack_106_24286
import pandas as pd from scipy.cluster import hierarchy from matplotlib import pyplot as plt import seaborn as sns cyt_list = 'IL1B,IL2,IL4,IL5,IL6,IL7,CXCL8,IL10,IL12B,IL13,IL17A,CSF3,CSF2,IFNG,CCL2,CCL4,TNF,IL1RN,IL9,IL15,CCL11,FGF2,CXCL10,PDGFB,CCL5,VEGFA,CCL3'.split(',') #getting df from csv with pre-PL therapy in...
the-stack_106_24287
""" KERN models """ import numpy as np import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from torch.nn.utils.rnn import PackedSequence from lib.resnet import resnet_l4 from config import BATCHNORM_MOMENTUM from lib.fpn.nms.functions.nms...
the-stack_106_24289
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from torch import nn import torch.nn.functional as F from . import utils as zutils from ..params import Gam...
the-stack_106_24291
############################# BEGIN FRONTMATTER ################################ # # # TEA - calculates Thermochemical Equilibrium Abundances of chemical species # # ...
the-stack_106_24293
#!/usr/bin/env python3 import datetime import os import signal import subprocess import sys import traceback from multiprocessing import Process import cereal.messaging as messaging import selfdrive.crash as crash from common.basedir import BASEDIR from common.params import Params, ParamKeyType from common.text_window...
the-stack_106_24294
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import codecs from setuptools import setup, find_packages kwargs = {} kwargs["install_requires"] = [ "setuptools", "rdflib>=6.0", "Cython", "lsm-db", "importlib-metadata; python_version < '3.8.0'", ] kwargs["dependency_links"] = [ ...
the-stack_106_24296
from django.test import TestCase from django.urls import reverse class TestApi(TestCase): def test_decode_success(self): """ Ensure decode endpoint invokes decode successfully. """ response = self.client.get(reverse("api-decode"), data={"input": "226"}) self.assertEqual(res...
the-stack_106_24301
# 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_106_24302
import os import argparse import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from torchvision import datasets, transforms from models import * # Prune settings parser = argparse.ArgumentParser(description='PyTorch Slimming CIFAR prune') parser.add_argument('--dataset', type=st...
the-stack_106_24307
""" ============================================== Auto-Aligning AIA and HMI Data During Plotting ============================================== This example shows how to auto-align two images with different reference frames during plotting. Here we use the optional keyword ``autoalign`` when calling Map's :meth:`~su...
the-stack_106_24308
#! /usr/bin/env python """ Utility for saving seed images """ import logging import os from astropy.io import fits import numpy as np import mirage from mirage.logging import logging_functions from mirage.utils.constants import LOG_CONFIG_FILENAME, STANDARD_LOGFILE_NAME classdir = os.path.abspath(os.path.join(os.p...
the-stack_106_24309
from bs4 import BeautifulSoup import requests import sys def pega_items(caixa_produto): # para cada div produto achado ele faz isso: for produtos_achados in caixa_produto: # aqui pega os atributos desejados dos seguintes items produto_descricao = produtos_achados.find('h2', class_='ui-search-item__ti...
the-stack_106_24312
# -------------------------------------------------------- # Fully Convolutional Instance-aware Semantic Segmentation # Copyright (c) 2017 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Haozhi Qi, Guodong Zhang, Yi Li # -------------------------------------------------------- import ...
the-stack_106_24314
# coding: utf-8 import binascii import warnings from .asset import Asset from .keypair import Keypair from . import memo from .network import NETWORKS, Network from . import operation from .transaction import Transaction from .transaction_envelope import TransactionEnvelope as Te from .exceptions import SequenceError ...
the-stack_106_24315
#!/usr/bin/env python """ The setup script for salt """ # pylint: disable=file-perms,resource-leakage import contextlib import distutils.dist import glob import operator import os import platform import sys from ctypes.util import find_library from datetime import datetime # pylint: disable=no-name-in-module from dis...
the-stack_106_24316
#!/usr/bin/env python3 """Updates HelmReleases with an annotation consumeable by rennovate. This script adds annotations fo HelmRelease files so that rennovate can manage chart upgrades. This script accepts a --cluster-path argument which should point at a fluxv2 repository that contains Kustomization yaml files, refe...
the-stack_106_24317
import os import unittest from kaggler.online_model import SGD DUMMY_SPARSE_STR = """0 1:1 3:1 10:1 0 3:1 5:1 1 4:1 6:1 8:1 10:1""" DUMMY_Y = [0, 0, 1] DUMMY_LEN_X = [3, 2, 4] class TestSGD(unittest.TestCase): def setUp(self): self.model = SGD(n=2**10, a=0.1, l1=1, l2=1, interaction=True) self...
the-stack_106_24319
from typing import Union, Dict, List, Any, Callable from threading import RLock from ..transition import Transition from .buffer import Buffer from machin.parallel.distributed import RpcGroup import torch as t import numpy as np import itertools as it def _round_up(num): return int(np.ceil(num)) class Distribut...
the-stack_106_24320
""" Implementation of the hierarchical poisson glm model, with a precinct-specific term, an ethnicity specific term, and an offset term. The data are tuples of (ethnicity, precinct, num_stops, total_arrests), where the count variables num_stops and total_arrests refer to the number of stops and total arrests of an eth...
the-stack_106_24321
import pynput from datetime import datetime from pynput.keyboard import Key, Listener count= 0 keys = [] def on_press(key): global keys, count keys.append(key) count +=1 if count >= 1: k = str(key).replace("'", "") if k.find("space") > 0: print(keys) count =0 ...
the-stack_106_24323
# Databricks CLI # Copyright 2018 Databricks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"), except # that the use of services to which certain application programming # interfaces (each, an "API") connect requires that the user first obtain # a license for the use of the APIs from Databricks,...
the-stack_106_24324
from forecast.utils.query_fields import ForecastQueryFields class FigureFieldData: select_related_list = [ "financial_code", "financial_code__cost_centre", "financial_code__natural_account_code", "financial_code__programme", "financial_code__project_code", "financi...
the-stack_106_24325
import copy import errno import os import signal import time import sys import operator import datetime from random import randint try: from itertools import zip_longest as izip_longest except ImportError: from itertools import izip_longest # NOQA import site from tornado import gen from psutil import NoSuchP...
the-stack_106_24326
class No: def __init__(self, value): self.value = value self.next = None class Diretorio: def __init__(self): self.first = No("\\") def insert(self, value=None): if self.first.value == "\\": self.first = No(str(value)) else: aux = self.first...
the-stack_106_24327
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import unittest import numpy as np from nose.tools import assert_raises, eq_ as eq from allel.test.tools import assert_array_equal as aeq, assert_array_almost_equal import allel from allel.util import ignore_invalid from alle...
the-stack_106_24329
from __future__ import annotations import sqlite3 from collections import defaultdict from contextlib import closing, contextmanager from importlib import resources from pathlib import Path from typing import Iterator def summary() -> Path: with resources.path(__package__, "summary.sqlite") as path: retu...
the-stack_106_24330
"""Support for Timers.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.event...
the-stack_106_24332
# -*- coding: utf-8 -*- import re from menus.menu_pool import menu_pool from menus.base import Menu, NavigationNode, Modifier from cms.utils import get_language_from_request from cms.utils.moderator import get_page_queryset, get_title_queryset from django.conf import settings from django.contrib.sites.models import Si...
the-stack_106_24333
MIN_BATCH = 5 LOSS_V = .5 # v loss coefficient LOSS_ENTROPY = .01 # entropy coefficient LEARNING_RATE = 5e-3 RMSPropDecaly = 0.99 # Params of advantage (Bellman equation) GAMMA = 0.99 N_STEP_RETURN = 5 GAMMA_N = GAMMA ** N_STEP_RETURN TRAIN_WORKERS = 10 # Thread number of learning. TEST_WORKER = 1 # Thread number...
the-stack_106_24335
import torch from torchvision import datasets, transforms from torch.utils.data import random_split def data_generator(root, batch_size): train_set = datasets.MNIST(root=root, train=True, download=True, transform=transforms.Compose([ transforms.ToT...
the-stack_106_24336
# this file contains code for a permuted graph topologies experiment # (we permute columns and rows of the adjacency matrix and check the # resulting neural networks fits) import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split import os import graph_utils...
the-stack_106_24337
## ## data_loader.py ## Load in brick/ball/cylinder examples for programming challenge. ## import numpy as np from easydict import EasyDict import glob import cv2 def data_loader(label_indices, channel_means, train_test_split = 0.7, input_image_size = (227, 227), data_path = '../data'): ''' ...
the-stack_106_24338
#! /usr/bin/env python # -*- coding:UTF-8 -*- """ Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import os import posixpath import re import stat from django.http import ( FileResponse, Http404, HttpR...
the-stack_106_24340
from operator import itemgetter cancerlist = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA", "GBM", "HNSC", "KICH", "KIRC", "KIRP", "LGG", "LIHC", "LUAD", "LUSC", "MESO", "OV", "PAAD", "PCPG", "PRAD", "READ", "SARC", "SKCM", "STAD", "TGCT", "THCA", "THYM", "UCEC", "UCS", "UVM"] #cancerlist = ["PANCANCE...
the-stack_106_24343
import pandas as pd import matplotlib as plt def teamSearch(teamName): teams = pd.read_html("https://en.wikipedia.org/wiki/Wikipedia:WikiProject_National_Basketball_Association/National_Basketball_Association_team_abbreviations", header=0) team_names = pd.DataFrame(columns=["Abbreviation/Acronym", "Franchise"]...
the-stack_106_24344
import codecs alphabet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzАаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфЦцЧчШшЩщХхЬьЪъЫыЭэЮюЯяΨ&Ǻλ∆0123456789!•−⋅→.—"‘±’,/\?%#@^$*+-_– №:;©‐[]=|(){}<>«»\r\n\ufeff\t' filename = "hello.txt" file_alphabet = "alphabet.txt" m = [] word_mass = [] word_size = [] in...
the-stack_106_24345
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the Partially Signed Transaction RPCs. """ from test_framework.test_framework import BitcoinTestFramew...
the-stack_106_24348
# 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, software # distributed under the Li...
the-stack_106_24350
import sys if 'PyQt5' in sys.modules: from PyQt5.QtCore import ( Qt, QSize, QPoint, QPointF, QRectF, QEasingCurve, QPropertyAnimation, QSequentialAnimationGroup, pyqtSlot, pyqtProperty) from PyQt5.QtWidgets import QCheckBox from PyQt5.QtGui import QColor, QBrush, QPaintEvent, QPen, ...
the-stack_106_24352
# -*- coding: utf-8 -*- from rest_framework import serializers from rest_framework.reverse import NoReverseMatch, reverse from tandlr.core.api.serializers import ModelSerializer from tandlr.users.serializers import UserSerializer from .models import Notification class NotificationTargetSerializer(serializers.Serial...
the-stack_106_24353
"""Module defining the ixdat csv reader, so ixdat can read the files it exports.""" from pathlib import Path import numpy as np import re import pandas as pd from ..exceptions import ReadError from ..data_series import ValueSeries, TimeSeries, DataSeries, Field from ..measurements import Measurement from ..spectra imp...
the-stack_106_24354
# 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, software # d...
the-stack_106_24355
#! /usr/bin/env python """ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x...
the-stack_106_24356
import os import socket from libqtile import qtile, widget from settings.shortcut import terminal, font from settings.themes import colors from settings.widgets_mod import * # PRYMARY WIDGETS LIST def init_widgets_list(): widgets_list = [ group_box(colors["color2"], colors["color3"]), current_lay...
the-stack_106_24357
# -*- coding: utf-8 -*- import json import re import scrapy from locations.hours import OpeningHours from locations.items import GeojsonPointItem class FnbUSSpider(scrapy.Spider): name = "fnb_us" item_attributes = {"brand": "First National Bank", "brand_wikidata": "Q5426765"} allowed_domains = ["fnb-onl...
the-stack_106_24360
"""Provide a registry to track entity IDs. The Entity Registry keeps a registry of entities. Entities are uniquely identified by their domain, platform and a unique id provided by that platform. The Entity Registry will persist itself 10 seconds after a new entity is registered. Registering a new entity while a timer...
the-stack_106_24361
import numpy as np import openml import pandas as pd import scipy.sparse as sp __all__ = ['query_regression_tasks', 'load_openml'] def query_regression_tasks(n_samples_min=100, n_samples_max=5000, n_features_max=None): task_list = openml.tasks.list_tasks(task_type_id=2) tasks = pd...
the-stack_106_24365
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by ...
the-stack_106_24368
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Tuple, Generator import numpy as np from jina.executors.indexers.dbms import BaseDBMSIndexer from jina.executors.indexers.dump import export_dump_streaming from .postgreshandler import PostgreSQLD...
the-stack_106_24370
# # Copyright 2018 the original author or 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...
the-stack_106_24371
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function """ A pure python ping implementation using raw sockets. Compatibility: OS: Linux, Windows, MacOSX Python: 2.6 - 3.5 Note that due to the usage of RAW sockets root/Administrator privileges a...
the-stack_106_24373
# # Copyright (c) 2021 Citrix Systems, 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 or...
the-stack_106_24376
import pygame,sys,random colors = [ "red","green", "yellow", "orange","turquoise"] fireworks = { "red":"red.png", "turquoise":"blue.png", "orange":"orange.png", "green":"green.png", "yellow":"yellow.png", } class Firework: def __init__(self,y = 590): self.x = random.ran...
the-stack_106_24380
"""Return data tables. Widgets: - summary_title: Div containing title of summary_table - summary_table: Contains summary statistics for numeric data columns - data_title: Div containing title of data_table - data_table: Contains all rows and columns of dataset """ # %% Imports # Standard sy...
the-stack_106_24382
import os import sys import argparse import pandas as pd import numpy as np import lightgbm as lgb from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score import random import operator import pickle as pickle import matplotlib.pyplot as plt np.random.seed(1) def load_da...
the-stack_106_24383
# -*- coding: utf-8 -*- # @Organization : insightface.ai # @Author : Jia Guo # @Time : 2021-05-04 # @Function : from __future__ import division import collections import numpy as np import glob import os import os.path as osp from numpy.linalg import norm from ..model_zoo import model_zoo from ...
the-stack_106_24384
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import StatisticsValidator from hecatoncheir.exception import ValidationError from hecatoncheir.msgutil import gettext as _ class StatEvalValidator(StatisticsValidator.StatisticsValidator): """Validator for the min/max value v = StatEvalValidator('foo', [u'CO...
the-stack_106_24385
# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood # Copyright (c) 2009 The Hewlett-Packard Development Company # Copyright (c) 2010 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following ...
the-stack_106_24386
import cv2 bitwise1 = cv2.imread("bitwise_1.png") bitwise2 = cv2.imread("bitwise_2.png") #bit_and = cv2.bitwise_and(bitwise1, bitwise2) #bit_or = cv2.bitwise_or(bitwise1, bitwise2) #bit_xor = cv2.bitwise_xor(bitwise1, bitwise2) bit_not = cv2.bitwise_not(bitwise1, bitwise2) #cv2.imshow("and", bit_and) #cv2...
the-stack_106_24389
import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from ..utils.no_swin_unet_v2_utils import * from ..builder import BACKBONES from mmseg.utils import get_root_logger from mmcv_custom import load_...
the-stack_106_24390
"""Blueprint for connecting to Twitch API.""" from flask_dance.consumer import OAuth2ConsumerBlueprint from flask_dance.consumer.requests import OAuth2Session from functools import partial from flask.globals import LocalProxy, _lookup_app_object import os from flask import _app_ctx_stack as stack __maintainer__ = "...
the-stack_106_24391
import pytest from dagster import ( DagsterInstance, Int, Output, OutputDefinition, check, composite_solid, execute_pipeline, lambda_solid, pipeline, solid, ) from dagster.core.definitions.pipeline_base import InMemoryPipeline from dagster.core.errors import ( DagsterInvalidC...
the-stack_106_24392
import logging import os import shutil import tempfile import time import salt.master import salt.transport.client import salt.utils.files import salt.utils.platform import salt.utils.user from tests.support.case import TestCase from tests.support.mixins import AdaptedConfigurationTestCaseMixin from tests.support.runt...
the-stack_106_24393
import os dir_names = ["butterfly", "sisl", "magent", "mpe", "atari"] had_error = False for name in dir_names: root_dir = os.path.join("pettingzoo", name) for _dir, subdirs, files in os.walk(root_dir): for file in files: if file.endswith(".py"): with open(os.path.join(_di...
the-stack_106_24395
# Copyright 2015 PerfKitBenchmarker 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...
the-stack_106_24396
from __future__ import unicode_literals from datetime import datetime from operator import attrgetter from django.core.exceptions import FieldError from django.test import TestCase, skipUnlessDBFeature from .models import Author, Article, Tag, Game, Season, Player class LookupTests(TestCase): def setUp(self):...
the-stack_106_24397
from rpython.rtyper.rmodel import inputconst, log from rpython.rtyper.lltypesystem import lltype, llmemory, rclass from rpython.jit.metainterp import history from rpython.jit.codewriter import heaptracker from rpython.rlib.jit import InvalidVirtualRef class VirtualRefInfo: def __init__(self, warmrunnerdesc): ...
the-stack_106_24398
from pykechain.enums import PropertyType, Multiplicity from pykechain.exceptions import IllegalArgumentError from pykechain.models import Part from pykechain.models.validators import RequiredFieldValidator from pykechain.utils import is_uuid from tests.classes import TestBetamax class TestPartCreateWithProperties(Tes...
the-stack_106_24399
#!/usr/bin/env python2 # coding:utf-8 import sys from mmseg import seg_txt for line in sys.stdin: blks = str.split(line) out_line = blks[0] for i in range(1, len(blks)): if blks[i] == "[VOCALIZED-NOISE]" or blks[i] == "[NOISE]" or blks[i] == "[LAUGHTER]": out_line += " " + blks[i] ...
the-stack_106_24401
# 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 to u...
the-stack_106_24404
""" Wrapper class around the ndarray object for the array API standard. The array API standard defines some behaviors differently than ndarray, in particular, type promotion rules are different (the standard has no value-based casting). The standard also specifies a more limited subset of array methods and functionali...
the-stack_106_24406
import numpy as np import cv2 import rospy import abc import math import tf2_ros as tf2 from tf.transformations import euler_from_quaternion from .color import ColorDetector from operator import itemgetter class FieldBoundaryDetector(object): """ The abstract class :class:`.FieldBoundaryDetector` is used for ...
the-stack_106_24407
#!/usr/bin/env python # Copyright 2015 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 ...
the-stack_106_24408
#! /usr/bin/env python import pygame import sys import random class Robot(object): def __init__ (self): self.pygame = pygame.init() self.screen = pygame.display.set_mode((640,480)) self.x = random.randint(0,9) # robot x position self.y = random.randint(0,9) # robot y position ...
the-stack_106_24409
from data.models import Comment, Post, User from django.db.models import Q from .. import remote_request class PostListMixin(object): def preprocess(self, request, *args, **kwargs): posts = Post.objects.none() user = None if 'post_list_filter' in kwargs: if request.user.is_au...
the-stack_106_24410
import dku_dataproc from gce_client import DataProcClient import os, json, argparse, logging from dataiku.cluster import Cluster logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO) logging.getLogger().setLevel(logging.INFO) class MyCluster(Cluster): def __init__(self,cluster...
the-stack_106_24413
#!/usr/bin/env python import os import sys import pathlib import subprocess import shutil import itertools def main(): exit_status = 0 assert pathlib.Path.cwd().resolve() == pathlib.Path(__file__).parent.resolve(), \ f"Please run {__file__} from ALIGN_HOME." argv = sys.argv[1:] output_dir = p...
the-stack_106_24414
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # Copyright 2015 and onwards 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/license...
the-stack_106_24417
from dataIO import fileIO import os false_strings = ["false", "False", "f", "F", "0", ""] if fileIO("data.json", "check"): data_json = fileIO("data.json", "load") else: data_json = { "Twitter": { "consumer_key": os.environ["CONSUMER_KEY"], "consumer_secret": os.environ["CONSUME...
the-stack_106_24418
import numpy as np import scipy.stats._stats_py from . import distributions from .._lib._bunch import _make_tuple_bunch __all__ = ['_find_repeats', 'linregress', 'theilslopes', 'siegelslopes'] # This is not a namedtuple for backwards compatibility. See PR #12983 LinregressResult = _make_tuple_bunch('LinregressResult...
the-stack_106_24420
#!/usr/bin/env python # coding: utf8 # # Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES). # # This file is part of CARS # (see https://github.com/CNES/cars). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obta...
the-stack_106_24421
import logging from typing import Optional, Tuple from .tflite import TFLiteConverter from .sklearn import SklearnConverter from .tensorflow import TensorflowConverter from .torch import TorchConverter class ModelConverter: def __init__(self, model_path: str, input_dims: Optional[Tuple[int]]): self.model_path ...
the-stack_106_24424
import sys from Qt import QtWidgets, QtCore from avalon import api, io, pipeline from openpype import style from openpype.tools.utils.widgets import AssetWidget from openpype.tools.utils import lib from .widgets import ( SubsetWidget, VersionWidget, FamilyListView, ThumbnailWidget, Representation...
the-stack_106_24425
from flask import Flask, render_template, url_for, request, redirect import smtplib import csv app = Flask(__name__) def write_to_db(data): with open('database.txt', mode='a') as db: email = data['email'] name = data['name'] subject = data['subject'] message = data['message'] ...