filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_13450
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton from PyQt5.QtGui import QIcon class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(100, 200, 300, 400) self.setWindowTitle("PyQt") self.setWindowIcon(QIcon("icon/graph.png")...
the-stack_0_13451
from unittest import TestCase, main from expects import expect, equal from twin_sister.injection.dependency_context import DependencyContext class TestSetEnv(TestCase): def test_can_set_arbitrary_var(self): key = 'some_key' value = 'some_value' context = DependencyContext(supply_env=Tru...
the-stack_0_13455
import os import sys from config import cfg import argparse import torch from torch.backends import cudnn import torchvision.transforms as T from PIL import Image sys.path.append('.') from utils.logger import setup_logger from model import make_model import numpy as np import cv2 from utils.metrics import cosine_simil...
the-stack_0_13458
"""Create LM input function for TPUEstimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os from absl import flags import absl.logging as _logging # pylint: disable=unused-import import tensorflow as tf # pylint: disable=g...
the-stack_0_13461
import discord import os import datetime from keep_alive import keep_alive from discord.ext import commands my_secret = os.environ['Token'] # client = discord.Client() # test bot = commands.Bot(command_prefix='!') @bot.command(pass_context=True, help="Update the role of user if you have Admin role eg: !updaterole 'xy...
the-stack_0_13463
# Copyright 2018, 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
the-stack_0_13464
# Copyright (c) 2019 Toyota Research Institute. All rights reserved. """ This module provides objects related to the discovery of new crystal structures using structural domains. """ import pandas as pd import os from datetime import datetime from monty.serialization import dumpfn from camd.domain import StructureD...
the-stack_0_13466
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from codecs import open # To use a consistent encoding from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) # Get version info ABOUT = {} with open(path.join(HER...
the-stack_0_13467
# -*- coding: utf-8 -*- import logging, urllib, time from django.utils.translation import gettext as _ from django.utils.timezone import now from crontab_monitor.models import SelectOption, single_entry_point def single_entry_point_of_crontab(*args, **kw): lg = logging.getLogger('django-crontab-monitor') kw['...
the-stack_0_13469
"""Test the arraymodule. Roger E. Masse """ import unittest from test import support from test.support import _2G import weakref import pickle import operator import struct import sys import warnings import array # from array import _array_reconstructor as array_reconstructor # XXX: RUSTPYTHON # sizeof_wchar = a...
the-stack_0_13474
""" Utilities for input/output operations. It is important to have DFS as global variable in this class to take advantatges of singeltons Info: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html All pages can import this file and retrive data by: > from data_loader ...
the-stack_0_13475
import sys import hashlib if len(sys.argv) <= 1: print("Provide string argument") exit(-1) else: s = sys.argv[1] result = "" for i in s: result = result + hashlib.sha256(i.encode("utf-8")).hexdigest() + "\n" print(result)
the-stack_0_13477
import configparser import json def write_config_to_file(config_dict, ini_fpath): """ Writes a configuration to an ini file. :param config_dict: (Dict) config to write :param ini_fpath: (str) fpath to ini file :return: (str) ini_file written to """ config = configparser.ConfigParser() config["DEFAULT"]...
the-stack_0_13478
"""show_l2vpn.py show l2vpn parser class """ import re from netaddr import EUI from ipaddress import ip_address from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Any from genie.libs.parser.base import * class ShowL2vpnMacLearning(MetaParser): """Parser for show l2vpn mac-...
the-stack_0_13479
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: radial_resample.py # # Tests: mesh - 2D rectilinear, single domain, # 3D rectilinear, single domain # 3D unstructured, multiple domain # ...
the-stack_0_13481
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
the-stack_0_13483
# 공공데이터 공영주차장 정보 DB에 저장 (총 14417개) import json from math import fsum from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.get_database('parking_lot') def get_data(): with open('static/seoul_park_lot.json', encoding='UTF8') as json_file: result = json.load(json_file) ...
the-stack_0_13484
"""pokerFace URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') C...
the-stack_0_13486
# 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_13487
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
the-stack_0_13488
import setuptools with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='sprofiler', version='0.1.0', author='Bryan Brzycki', author_email='bbrzycki@berkeley.edu', description='Lightweight profiler with checkpoints', long_description=long_description, l...
the-stack_0_13489
# coding=utf-8 """Search SoundCloud playlists for audio.""" from __future__ import absolute_import import os import string import sys import requests import soundcloud from tqdm import tqdm def sanitize(s): return ''.join( c for c in s if c in '-_.() {}{}'.format(string.ascii_letters, string.dig...
the-stack_0_13490
from django import forms from .models import Department, Province, District class DepartmentForm(forms.Form): department = forms.ModelChoiceField( queryset=Department.objects.all() ) class ProvinceForm(DepartmentForm): province = forms.ModelChoiceField( queryset=Province.objects.none() ...
the-stack_0_13492
#####EXERCÍCIOS 70 ####### print('-'*50) print('{^} LOJA DO BARATÃO') print('-'*50) menor = cont = caro = total = 0 barato = 'a' while True: produto = str(input('DIGITE O NOME DO PRODUTO : ')) cont += 1 preço = float(input('Digite o valor do produto : ')) total += preço if preço >=1000: ...
the-stack_0_13493
from datetime import date, datetime, timedelta import numpy as np import pytest import pytz from pandas._libs.tslibs import iNaT, period as libperiod from pandas._libs.tslibs.ccalendar import DAYS, MONTHS from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime from pandas._libs.tslibs.parsing import DateParse...
the-stack_0_13494
# -*- coding: utf8 -*- import sys import unittest import platform IS_PYPY = "PyPy" == platform.python_implementation() try: from pygame.tests.test_utils import arrinter except NameError: pass import pygame init_called = quit_called = 0 def __PYGAMEinit__(): # called automatically by pygame.init() g...
the-stack_0_13496
from datetime import datetime, timedelta import fundamental_analysis.financial_statements_entries as fi import fundamental_analysis.supporting_metrics as me from fundamental_analysis.metrics_helpers import FundamentalMetricsHelpers from matilda.quantitative_analysis.risk_factor_modeling import asset_pricing_model impor...
the-stack_0_13497
# coding: utf-8 # %% [markdown] # # 📃 Solution for Exercise M2.01 # # The aim of this exercise is to make the following experiments: # # * train and test a support vector machine classifier through # cross-validation; # * study the effect of the parameter gamma of this classifier using a # validation curve; # * us...
the-stack_0_13498
#!/usr/bin/env python3 import ssl from pwncat.channel import ChannelError from pwncat.channel.connect import Connect class SSLConnect(Connect): def __init__(self, **kwargs): super().__init__(**kwargs) def _socket_connected(self, client): try: self.context = ssl.SSLContext(ssl.PRO...
the-stack_0_13499
import logging def derive_initial_state_model(max_repeats, num_symbols, max_extra_states=15, start_symbol=1000, end_symbol=1001, num_random_starts=20 ...
the-stack_0_13502
from plenum.test.test_node import ensure_node_disconnected, getNonPrimaryReplicas from indy_node.test.helper import addRawAttribute from indy_client.test.conftest import nodeSet from indy_common.test.conftest import config_helper_class, node_config_helper_class def test_n_minus_f_pool_processes_attrib(looper, nodeS...
the-stack_0_13504
import sys sys.path.append(".") import numpy as np from dctree.core.basemodel import BaseModel class AdaboostClassifier(BaseModel): def __init__(self,base_estimator:BaseModel,n_estimators=5,learning_rate=1.0,base_estimator_params={}): """ An AdaBoost classifier \n Params: base_estim...
the-stack_0_13506
"""Test functions for the sparse.linalg._onenormest module """ import numpy as np from numpy.testing import assert_allclose, assert_equal, assert_ import pytest import scipy.linalg import scipy.sparse.linalg from scipy.sparse.linalg._onenormest import _onenormest_core, _algorithm_2_2 class MatrixProductOperator(scip...
the-stack_0_13507
# -*- encoding: utf-8 -*- # # Author: John Tran <jhtran@att.com> # Julien Danjou <julien@danjou.info> # # 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/li...
the-stack_0_13508
from django.db.models.signals import post_migrate from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission def add_view_permissions(sender, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # f...
the-stack_0_13512
# -*- coding: utf-8 -*- import logging import subprocess from imghdr import what as determinetype from django.core.files.base import ContentFile from django.core.files.temp import NamedTemporaryFile from easy_thumbnails.optimize.conf import settings try: from subprocess import check_output except ImportError: ...
the-stack_0_13514
from No import No from Estado import Estado from collections import deque def executaBFS(): """ Esta função executa a pesquisa BFS usando uma fila """ #criar fila fila = deque([]) #por ser um gráfico, criamos uma lista de visitantes visitados = [] #criar nó raiz estadoIni...
the-stack_0_13515
"""This module defines the funtions byref_at(cobj, offset) and cast_field(struct, fieldname, fieldtype). """ from ctypes import * def _calc_offset(): # Internal helper function that calculates where the object # returned by a byref() call stores the pointer. # The definition of PyCArgObject in C ...
the-stack_0_13516
import torch.nn as nn class NLayerDiscriminator(nn.Module): """ A PatchGAN """ def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d): super(NLayerDiscriminator, self).__init__() kwidth = 4 padw = 1 sequence = [nn.Conv2d(input_nc, n...
the-stack_0_13519
#!/usr/bin/python3 from keras.datasets import mnist from keras.preprocessing.image import load_img, array_to_img from keras.utils.np_utils import to_categorical from keras.models import Sequential from keras.layers import Dense import numpy as np import matplotlib.pyplot as plt (X_train, y_train), (X_test, y_test) =...
the-stack_0_13520
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2019 "Neo4j," # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # 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 L...
the-stack_0_13521
#!/usr/bin/env python -tt # # Copyright (c) 2007 Red Hat Inc. # Copyright (c) 2009, 2010, 2011 Intel, Inc. # # 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; version 2 of the License # # This pr...
the-stack_0_13522
def incworkload(inchtml,composition): Xh = 45100*(composition/(composition+1)) / (3 * 60 * 60)*inchtml Xi = 45100*(1/(composition+1)) / (3 * 60 * 60)*inchtml request_size_h = 3000 / 1000 request_size_i = 15000 / 1000 Dhc = (0.008 + (0.002 * request_size_h)) Dic = (0.008 + (0.002 * request_size_i...
the-stack_0_13524
"""Test data purging.""" import json from datetime import datetime, timedelta import unittest from homeassistant.components import recorder from homeassistant.components.recorder.const import DATA_INSTANCE from homeassistant.components.recorder.purge import purge_old_data from homeassistant.components.recorder.models ...
the-stack_0_13526
from django.db import models from django.db.models import Q from django.utils.encoding import force_text from cms.models import CMSPlugin, Placeholder class AliasPluginModel(CMSPlugin): cmsplugin_ptr = models.OneToOneField( CMSPlugin, on_delete=models.CASCADE, related_name='cms_aliasplugi...
the-stack_0_13529
#!/usr/bin/env python3 # Copyright 2017-18 TransitCenter http://transitcenter.org # 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 requ...
the-stack_0_13530
# -*- coding: utf-8 -*- import numpy as np import scipy.signal as sig from math import pi import math def PLL(input_signal, Fs, lenght, N): """Synchronizes the input carryer signal with the local oscillator to avoid crosstalk due to phase and frequency differences between TX and RX. Parameters -...
the-stack_0_13531
from . import FieldType from . import FieldValue from . import FieldTypeRegression from . import FieldValueRegression def rec(node, result, randomstate): node.randomstate = randomstate v = node.pick_value() result[node.field_name] = v.get_field_value() if v.next_field and len(v.next_field.values) > 0:...
the-stack_0_13532
import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Phase2C6_timing_layer_bar_cff import Phase2C6_timing_layer_bar process = cms.Process('PROD',Phase2C6_timing_layer_bar) process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.load("IOMC.EventVertexGenerators.VtxSmearedGauss_cfi") process.loa...
the-stack_0_13533
''' Problem 72 - Counting fractions Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3...
the-stack_0_13534
import numpy as np from allennlp.common.testing import ModelTestCase from tests import FIXTURES_ROOT class TestBidirectionalLanguageModel(ModelTestCase): def setUp(self): super().setUp() self.expected_embedding_shape = (2, 8, 14) self.set_up_model( FIXTURES_ROOT / "lm" / "l...
the-stack_0_13536
# -*- coding: utf-8 -*- from openerp import models, fields, api class Wizard(models.TransientModel): _name = 'openacademy.wizard' def _default_session(self): return self.env['openacademy.session'].browse(self._context.get('active_ids')) session_ids = fields.Many2many('openacademy.session', ...
the-stack_0_13540
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from django.contrib import admin from django.urls import path, include # add this urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("rest.urls")), path("", include("authentication.urls")), # add th...
the-stack_0_13541
""" Blocklist management """ from collections import defaultdict from typing import TYPE_CHECKING, Any, Dict, List import pkg_resources from .configuration import BandersnatchConfig if TYPE_CHECKING: from configparser import SectionProxy # The API_REVISION is incremented if the plugin class is modified in a # ...
the-stack_0_13542
__author__ = "Christopher Dean" __copyright__ = "" __credits__ = ["Christopher Dean"] __version__ = "" __maintainer__ = "Christopher Dean" __email__ = "cdean11@colostate.edu" __status__ = "I'm doing fine." import sys import argparse def parse_cmdline_params(cmdline_params): info = "Remove duplicate annotatio...
the-stack_0_13545
import random class BaseTank: def __init__(self, tank_data): self.death = False self.model = tank_data.get('short_name') self.nation = tank_data.get('nation') default_profile = tank_data.get('default_profile') self.armor_dict = default_profile.get('armor').get('hull') ...
the-stack_0_13546
import speedtest as st import sys import threading import itertools import time from colorama import Fore from plugin import plugin class SpinnerThread(threading.Thread): """SpinnerThread class to show a spinner on command line while the progream is running""" def __init__(self, label="Hmmm... ", delay=0.2): ...
the-stack_0_13547
import math import re import threading import time from typing import Any, Callable, List, Optional, Set, Tuple import antlr4 from pytest import mark, param, raises, warns from omegaconf import ( AnyNode, Container, DictConfig, ListConfig, OmegaConf, _utils, grammar_parser, grammar_vis...
the-stack_0_13549
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'apply.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^accounts/login/$', 'django.contrib.auth.views.login'), url(r'^accounts/logout/$', 'dj...
the-stack_0_13551
""" @author: Jonatan González Rodríguez <jonatan.gonzalez.r@outlook.com> """ import re import csv, datetime import pysam def reformat_nanomonsv(inp, out): vcf = open(inp, 'r') filtered_vcf = open(out, 'w') for line in vcf: if line.startswith('##') and 'ID=TR' in line: filtered_vcf.wri...
the-stack_0_13555
import pytest from vnep_approx import treewidth_model import numpy as np from alib import mip from alib import datamodel as dm from alib import util from .test_data.request_test_data import create_test_request from .test_data.substrate_test_data import create_test_substrate_topology_zoo from .test_data.substrate_test...
the-stack_0_13557
import abc from typing import Any, Dict, List, Optional import tqdm from openforcefield.topology import Molecule from openforcefield.utils.toolkits import OpenEyeToolkitWrapper, RDKitToolkitWrapper from pydantic import BaseModel, Field, validator from pydantic.main import ModelMetaclass from qcelemental.util import wh...
the-stack_0_13558
from pathlib import Path from setuptools import find_packages, setup module_dir = Path(__file__).resolve().parent with open(module_dir / "README.md") as f: long_description = f.read() if __name__ == "__main__": setup( name="atomate2", setup_requires=["setuptools_scm"], use_scm_versio...
the-stack_0_13559
class BaseCAM(object): """ Base class for Class Activation Mapping. """ def __init__(self, model_dict): """Init # Arguments model_dict: dict. A dict with format model_dict = dict(arch=self.model, layer_name=target_layer_name). """ layer_name...
the-stack_0_13560
# Copyright (C) 2020 Intel Corporation # # SPDX-License-Identifier: MIT class _GitImportFix: import sys former_path = sys.path[:] @classmethod def apply(cls): # HACK: fix application and module name clash # 'git' app is found earlier than a library in the path. # The clash is ...
the-stack_0_13561
#!/home/kyy/lecture/search-restaurants/venv/bin/python3.5 """PILdriver, an image-processing calculator using PIL. An instance of class PILDriver is essentially a software stack machine (Polish-notation interpreter) for sequencing PIL image transformations. The state of the instance is the interpreter stack. The only...
the-stack_0_13562
import sys def main(input_file): with open(input_file, 'r') as fh: for line in fh: line = line.strip() days = int(line.split(';')[0]) array = [int(x) for x in line.split(';')[1].split(' ')] result = 0 for i in range(0, len(array)-days+1): ...
the-stack_0_13563
# Copyright 2013 IBM Corp. # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LIC...
the-stack_0_13565
# -*- coding: utf-8 -*- from contextlib import contextmanager import base64 import datetime import json import pickle import os from cms.api import create_page from django import http from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.contrib.admin.widgets i...
the-stack_0_13567
#!/usr/bin/python2.7 from __future__ import print_function import sys import os import copy import argparse def outputReactions(fn, sfx, rxns, db_rxns, db_enz, gf=None, v=False): fn += "_" fh = open(fn + sfx, "w") if gf: fh.write("reaction\tcomplex\tfunction\tgapfilled\tgfstep\tequation\n") el...
the-stack_0_13570
import unittest import numpy as np from slice_merge import TiledImage class TestTiledImage(unittest.TestCase): def test_slicing(self): data = np.zeros((5, 5, 2)) sliced = TiledImage(data, tile_size=2, keep_rest=True) self.assertEqual(sliced.data.shape, (3, 3, 2, 2, 2)) self.asse...
the-stack_0_13573
''' (C) 2014-2016 Roman Sirokov and contributors Licensed under BSD license http://github.com/r0x0r/pywebview/ ''' import os import json import logging from uuid import uuid1 from copy import deepcopy from threading import Semaphore, Event from webview.localization import localization from webview import _parse_api_...
the-stack_0_13575
#!/usr/bin/env python from translate.misc import autoencode from py import test class TestAutoencode: type2test = autoencode.autoencode def test_default_encoding(self): """tests that conversion to string uses the encoding attribute""" s = self.type2test(u'unicode string', 'utf-8') ass...
the-stack_0_13578
import discord import asyncio import io import aiohttp import utils from random_generators import RandomMessageGenerator from base_client import BaseClient class DiscordClient(discord.Client, BaseClient): def __init__(self, discord_config, send_handler): discord.Client.__init__(self) self.channel...
the-stack_0_13581
# Copyright (c) 2017, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import itertools import pandas as pd import os import unittest from coremltools._deps import HAS_SKLEAR...
the-stack_0_13583
import tensorflow as tf import pickle from model import Model from utils import build_dict, build_train_draft_dataset, test_batch_iter import os with open("args.pickle", "rb") as f: args = pickle.load(f) print("Loading dictionary...") word_dict, reversed_dict, article_max_len, summary_max_len = build_dict("test"...
the-stack_0_13585
import importlib import inspect import json import logging import os import re import sys import zipfile from pathlib import Path import click def add_to_dict_if_exists(options_dict, initial_dict={}): for k, v in options_dict.items(): if v: initial_dict[k] = v return initial_dict def co...
the-stack_0_13588
from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import SGDRegressor from sklearn.metrics import mean_squared_error """ 线性回归:梯度下降法 :return:None """ # 1.获取数据 data = load_boston() # 2.数据集...
the-stack_0_13589
import os.path import clr project_dir = os.path.dirname(os.path.abspath(__file__)) import sys sys.path.append(os.path.join(project_dir, "..", "TestStack.White.0.13.3\\lib\\net40\\")) sys.path.append(os.path.join(project_dir, "..", "Castle.Core.3.3.0\\lib\\net40-client\\")) clr.AddReferenceByName('TestStack.White') fro...
the-stack_0_13591
import json from pyaltherma.const import VALID_RESPONSE_CODES from pyaltherma.errors import PathException, AlthermaResponseException def query_object(o, json_path, raise_exception=False, convert_to_none=True): location_steps = json_path.split('/') if isinstance(o, str): o = json.loads(o) for idx,...
the-stack_0_13594
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
the-stack_0_13596
import os import re from dataclasses import dataclass from pathlib import PurePath from typing import Awaitable, List, Optional, Pattern, Set, Union from urllib.parse import urljoin from bs4 import BeautifulSoup, Tag from ..config import Config from ..logging import ProgressBar, log from ..output_dir import FileSink ...
the-stack_0_13597
import gc import sys import unittest import collections import weakref import operator import contextlib import copy import threading import time import random from test import support from test.support import script_helper, ALWAYS_EQ # Used in ReferencesTestCase.test_ref_created_during_del() . ref_from_del = None #...
the-stack_0_13598
""" Test basic properties of implemented datasets. """ import unittest import numpy as np from classicdata import Ionosphere from classicdata.dataset import Dataset, CitationWarning class TestLoading(unittest.TestCase): def test_loading(self): with self.assertWarns(CitationWarning): for Data...
the-stack_0_13600
''' Provides various utility functions. This file is part of RTSLib. Copyright (c) 2011-2013 by Datera, Inc Copyright (c) 2011-2014 by Red Hat, 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 ...
the-stack_0_13603
from . import SentenceEvaluator, SimilarityFunction import logging import os import csv from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances from typing import List from ..readers import InputExample logger = logging.getLogger(__name__) class TripletEv...
the-stack_0_13605
# Copyright (c) 2020 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 appli...
the-stack_0_13606
import argparse import json import os import sys from random import shuffle from multiprocessing.pool import ThreadPool from functools import partial import io from tqdm import tqdm # Assumes ai4eutils is on the path (github.com/Microsoft/ai4eutils) from write_html_image_list import write_html_image_list #from data...
the-stack_0_13607
from flask import g, request from pprint import pformat from requests.exceptions import ConnectionError from requests.models import Request import logging import requests import sys import time def getLogger(*args, **kwargs): logger = logging.getLogger(*args, **kwargs) return CustomLogger(logger=logger) cla...
the-stack_0_13608
# Copyright 2018-2019 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' fil...
the-stack_0_13610
from statistics import mean import numpy as np import matplotlib.pylab as plt from matplotlib import style style.use("fivethirtyeight") #dtype important later xs = np.array([1,2,3,4,5,6],dtype=np.float64) ys = np.array([5,4,6,5,6,7],dtype=np.float64) plt.scatter(xs,ys) plt.show() def best_fit_slope(...
the-stack_0_13611
# -*- coding: utf-8 -*- import re from scrapy import Spider, Request from dateutil import parser from artbot_scraper.items import EventItem from pytz import timezone class AmbushSpider(Spider): name = "Goodspace" allowed_domains = ["goodspace.co"] start...
the-stack_0_13613
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from threading import Event from typing import IO, Any, Optional, Union import libvirt # type: ignore from . import libvirt_events_thread # Reads serial console log from libvirt VM and writes it to a file. class QemuConsoleLogger: def __...
the-stack_0_13614
cont = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte') while True: núm = int(input('Digite um número entre 0 e 20:\n')) if 0 <= núm <= ...
the-stack_0_13616
import json import shutil import re from os.path import exists,join, realpath import os file_name = 'compile_commands.json' with open(file_name, 'r') as f: data = json.load(f) cnt = 0 CYBER_DIR = "/home/zhihaohe/cybertron" PROTO_DIR = '/home/zhihaohe/cybertron' container_dirs = ['/home/zhihaohe/container_cybertro...
the-stack_0_13617
# Logging level must be set before importing any stretch_body class import stretch_body.robot_params stretch_body.robot_params.RobotParams.set_logging_level("DEBUG") import unittest import stretch_body.dynamixel_XL430 import logging from concurrent.futures import ThreadPoolExecutor class TestDynamixelXL430(unittest...
the-stack_0_13619
import cv2 face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def face_extractor(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale(gray, 1.3, 5) if faces is (): return for (x, y, w, h) in faces: cropped_faces = img[...
the-stack_0_13620
from tqdm import tqdm import numpy as np import torch from typing import Callable, Optional, Union from alibi_detect.cd.base_online import BaseDriftOnline from alibi_detect.utils.pytorch.kernels import GaussianRBF from alibi_detect.utils.pytorch import zero_diag, quantile class MMDDriftOnlineTorch(BaseDriftOnline): ...
the-stack_0_13621
from utils import * import pickle import numpy_indexed import copy # version of dfs that builds the graph as it traverses it def dfs_2(start, goals, side, grouped_c_r, keys_c_r, grouped_r_r, keys_r_r, max_depth = 11): ''' Parameters: start : str name of the root node, e.g. 'ctg1' goals : list o...
the-stack_0_13622
"""ILI9341 demo (Scrolling Marquee).""" from ili9341 import Display, color565 from time import sleep from sys import implementation def test(): """Scrolling Marquee.""" try: # Implementation dependant pin and SPI configuration if implementation.name == 'circuitpython': import board...