filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_24944
from __future__ import absolute_import from __future__ import print_function import os import sys # the next line can be removed after installation sys.path.insert(0, os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) import nngen as ng import veriloggen import matrix_sub a_shape =...
the-stack_106_24947
from XFE_v2 import Client, ip_command, url_command, cve_get_command, \ cve_search_command, file_command, whois_command from CommonServerPython import outputPaths DBOT_SCORE_KEY = 'DBotScore(val.Indicator == obj.Indicator && val.Vendor == obj.Vendor)' MOCK_BASE_URL = 'https://www.this-is-a-fake-url.com' MOCK_API_K...
the-stack_106_24948
#!/usr/bin/env python # coding:utf8 # Copyright (c) 2018, Tencent. All rights reserved # Implement FastText # Reference "Bag of Tricks for Efficient Text Classification" # https://github.com/facebookresearch/fastText import tensorflow as tf from model.embedding_layer import EmbeddingLayer from model.m...
the-stack_106_24951
from datetime import datetime, timedelta from pytz import timezone, UTC import unittest2 from google.appengine.ext import ndb from google.appengine.ext import testbed from consts.event_type import EventType from helpers.season_helper import SeasonHelper from models.event import Event class TestSeasonHelper(unittest...
the-stack_106_24952
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- if __name__ == "__main__": lst = list(map(int, input().split())) i_max = lst.index(max(lst)) lst[i_max], lst[0] = lst[0], lst[i_max] print(*lst)
the-stack_106_24953
# Copyright 2020 Huawei Technologies Co., Ltd # # 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_24955
import unittest import numpy as np from chariot.transformer.vocabulary import Vocabulary from gcn.graph import DependencyGraph, SimilarityGraph, StaticGraph from gcn.visualize.draw import AttentionDrawer class TestDraw(unittest.TestCase): def test_draw_dependency_graph(self): sentence = "I am living at h...
the-stack_106_24956
# encoding: utf-8 import math import torch from torch import nn from .AIBN import AIBNorm2d from clustercontrast.models.pooling import build_pooling_layer def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, ...
the-stack_106_24957
import json import logging import redis from tsa.extensions import redis_pool def query_dataset(iri): return { "related": query_related(iri), "profile": query_profile(iri) } def query_related(ds_iri): key = f'distrquery:{ds_iri}' red = redis.Redis(connection_pool=redis_pool) try...
the-stack_106_24960
import numpy as np from scipy import integrate from reactorPhysics import reactorSystem from reactorPhysics import qFuel from reactorPhysics import rho #import matplotlib.pyplot as pl import time class LegoReactor(object): """ Provides methods to interact with the point kenetics model. The reactor system ...
the-stack_106_24963
# 豆瓣美剧的爬取,数据会写入csv import csv import time import jsonpath import requests class Douban: def __init__(self): self.url = 'https://movie.douban.com/j/search_subjects?' \ 'type=tv&tag=%E7%BE%8E%E5%89%A7&sort=recommend&page_limit=20&page_start={}' self.headers = { "User-...
the-stack_106_24965
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
the-stack_106_24966
""" This module implements some standard regression models: OLS and WLS models, as well as an AR(p) regression model. Models are specified with a design matrix and are fit using their 'fit' method. Subclasses that have more complicated covariance matrices should write over the 'whiten' method as the fit method prewhi...
the-stack_106_24967
""" Utility RPython functions to inspect objects in the GC. """ from pypy.rpython.lltypesystem import lltype, llmemory, rffi from pypy.rlib.objectmodel import free_non_gc_object from pypy.rpython.module.ll_os import underscore_on_windows from pypy.rlib import rposix, rgc from pypy.rpython.memory.support import Address...
the-stack_106_24969
""" test.test_component_switch ~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests switch component. """ # pylint: disable=too-many-public-methods,protected-access import unittest import os import homeassistant as ha import homeassistant.loader as loader import homeassistant.util as util import homeassistant.components as components im...
the-stack_106_24971
"""Matplotlib rankplot.""" import matplotlib.pyplot as plt import numpy as np import scipy.stats from ....stats.density_utils import histogram from ...plot_utils import _scale_fig_size, make_label from . import backend_kwarg_defaults, backend_show, create_axes_grid def plot_rank( axes, length_plotters, r...
the-stack_106_24972
# # 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_24976
import argparse import logging from funcy import compact from dvc.cli.command import CmdBase from dvc.cli.utils import append_doc_link from dvc.exceptions import InvalidArgumentError from dvc.ui import ui logger = logging.getLogger(__name__) class CmdExperimentsInit(CmdBase): DEFAULT_NAME = "train" CODE = ...
the-stack_106_24977
from mpvr.datamodule.manager import Manager as dm from mpvr.utils.process import * from scipy.signal import savgol_filter import numpy as np import pandas as pd dm = dm.from_config(dm.section_list()[0]) max_val = 0 sum_of_incidence = np.zeros(315) for scenario in dm.get_scenarios(): dm.set_scenario(scenario) d...
the-stack_106_24978
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
the-stack_106_24979
from typing import Hashable, Iterable, List, Optional from .._internal import API @API.public class AntidoteError(Exception): """Base class of all errors of antidote.""" def __repr__(self) -> str: return f"{type(self).__name__}({self})" @API.public class DoubleInjectionError(AntidoteError): ""...
the-stack_106_24984
""" Updating submission annotations Deprecate many of these functions once synapseclient==2.1.0 """ import json import typing from synapseclient import SubmissionStatus, Annotations from synapseclient.annotations import (is_synapse_annotations, to_synapse_annotations, ...
the-stack_106_24986
""" Robot planning problem turned into openai gym-like, reinforcement learning style environment """ from __future__ import print_function from __future__ import absolute_import from __future__ import division import attr import copy import numpy as np from bc_gym_planning_env.robot_models.tricycle_model import Tricyc...
the-stack_106_24987
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # 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_24988
# Copyright 2019 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_24990
import streamlit as st def color_performance(column): """ color values in given column using green/red based on value>0 Args: column: Returns: """ color = 'green' if column > 0 else 'red' return f'color: {color}' def money_color(value): if value < 0: color = 'red' ...
the-stack_106_24993
import pyglet class Coin(pyglet.sprite.Sprite): red_image = pyglet.resource.image('assets/coin-red.png') blue_image = pyglet.resource.image('assets/coin-blue.png') blue_victory_image = pyglet.resource.image('assets/coin-blue-victory.png') red_victory_image = pyglet.resource.image('assets/coin-red-vi...
the-stack_106_24994
#!/usr/bin/env python # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. from __future__ import absolute_import import sys __author__ = "Sorin Sbarnea" __copyright__ = "Copyright 2010-2018, Sorin Sbarnea" __email__ = "sorin.sbarnea@gmail.com" __status__ = "P...
the-stack_106_24995
# -*- coding: utf-8 -*- # Copyright 2022 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_24996
import pyb import stm # The BLUE Led on the pyboard is on pin B4 LED_MASK = const(1 << 4) # The BLUE Led on the pyboard is active high @micropython.viper def v_led_pulse(): LED_BSRR = ptr16(stm.GPIOB + stm.GPIO_BSRR) LED_BSRR[0] = LED_MASK # high = on pyb.delay(100) LED_BSRR[1] = LED_MASK # low = off pyb....
the-stack_106_24997
def check_command_line_arguments(in_arg): """ Prints each of the command line arguments passed in as parameter in_arg. Parameters: in_arg -data structure that stores the command line arguments object Returns: Nothing - just prints to console """ if in_arg is None: print("* ...
the-stack_106_24999
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt y = np.random.standard_normal((1000, 2)) c = np.random.randint(0, 10, len(y)) print(y) plt.figure(figsize=(7,5)) plt.hist(y, label=['1st', '2nd'], color=['b', 'g'], stacked=True, bins=20) plt.grid(True) plt.legend(loc=0) plt.xlabel('value') ...
the-stack_106_25003
""" Stream test: Pull the video from the drone and display in cv2 window. Optionally encode video and dump to file. """ import av import numpy import tellopy import cv2 def encode(frame, ovstream, output): """ convert frames to packets and write to file """ try: pkt = ovstream.encode(frame) ...
the-stack_106_25004
""" Custom Authenticator to use Bitbucket OAuth with JupyterHub """ import json import urllib from tornado.auth import OAuth2Mixin from tornado import web from tornado.httputil import url_concat from tornado.httpclient import HTTPRequest, AsyncHTTPClient from jupyterhub.auth import LocalAuthenticator from traitlet...
the-stack_106_25007
# -*- coding: utf-8 -*- from datetime import datetime from PIL import Image,ImageFont,ImageDraw from copy import copy import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI from gsiot.v3 import * from gsiot.v3.file.gsdisplay import device from gsiot.v3.file.gsdisplay.ili9341 import ILI9341 # tk窗口显示 class containe...
the-stack_106_25008
import json from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union, TYPE_CHECKING from ..config import Config from .irresource import IRResource if TYPE_CHECKING: from .ir import IR def qualify_service_name(ir: 'IR', service: str, namespace: Optional[str]) -> str: fully_qualified = "." in ser...
the-stack_106_25012
"""Support for IOTA wallets.""" from datetime import timedelta from iota import Iota import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.entity import Entity CONF_IRI = "iri" CONF_TESTNET = "testnet" CONF_W...
the-stack_106_25019
# 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_106_25020
from __future__ import absolute_import from __future__ import division from __future__ import print_function from model.utils.config import cfg from model.faster_rcnn.faster_rcnn import _fasterRCNN import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math impor...
the-stack_106_25021
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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_25022
"""For each HUC12 we are processing, dump our present file database.""" import os import sys def main(argv): """Go Main Go.""" scenario = int(argv[1]) for line in open("myhucs.txt"): huc12 = line.strip() removed = 0 for subdir in [ "crop", "error", ...
the-stack_106_25025
#!/usr/bin/env python3 """Module used to read devices on a Dallas 1-wire bus with an Embedded Devices HA7S master. The class that does the reading of the bus is HA7Sreader. """ import logging, time, re, glob import serial from . import base_reader # ----------- Dallas 1-wire CRC Calculations ------------- crc8_table ...
the-stack_106_25026
import json import sys from django.core.serializers.base import DeserializationError from django.core.serializers.json import Serializer as JSONSerializer from djmoney.money import Money from .models.fields import MoneyField from .utils import get_currency_field_name Serializer = JSONSerializer def Deserializer(...
the-stack_106_25030
# -*- test-case-name: twisted.conch.test.test_keys -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Handling of RSA, DSA, ECDSA, and Ed25519 keys. """ from __future__ import absolute_import, division import binascii import itertools from hashlib import md5, sha256 import base64 import...
the-stack_106_25031
""" Performs a few basic commands in creating groups and moving targets around. No errors or exceptions should be thrown. """ import seash import sys orig_stdout = sys.stdout # To temporarily prevent printing to console, test_results.txt is used as a text # dump as stdout is redirected to it sys.stdout = open("test_...
the-stack_106_25032
# coding: utf-8 """ Experimental Looker API 3.1 Preview This API 3.1 is in active development. Breaking changes are likely to occur to some API functions in future Looker releases until API 3.1 is officially launched and upgraded to beta status. If you have time and interest to experiment with new or modifie...
the-stack_106_25033
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ This script can be used to extract the VOC2007 and VOC2012 dataset files [data, labels] from the given annotations that can be used for tra...
the-stack_106_25034
import cv2 img='/Users/xh/Downloads/ks/qa-irs/app/task/frames/60/irs-1cd298e4ed39042588cb5224662f79b2.mp4.mp4/00001.jpg' # 把图片转换为单通道的灰度图 img=cv2.imread(img) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 获取灰度图矩阵的行数和列数 r, c = gray_img.shape[:2] piexs_sum = r * c # 整个弧度图的像素个数为r*c # 获取偏暗的像素(表示0~19的灰度值为暗) 此处阈值可以修改 d...
the-stack_106_25037
from pymongo import MongoClient mongo_uri = "mongodb://admin:admin@ds021182.mlab.com:21182/c4e" client = MongoClient(mongo_uri) db = client.get_default_database() blog = db["posts"] post = { "title" : "Ai đưa em về", "author" : "Duy Anh", "content" : """ Đêm nay ai đưa em về Đường khuya sao trời l...
the-stack_106_25039
from __future__ import print_function """ panotti_models.py Author: Scott Hawley Where we'll put various NN models. MyCNN: This is kind of a mixture of Keun Woo Choi's code https://github.com/keunwoochoi/music-auto_tagging-keras and the MNIST classifier at https://github.com/fchollet/keras/blob/master/examples/m...
the-stack_106_25043
""" SMPP validators """ from jasmin.protocols.validation import AbstractCredentialValidator from jasmin.protocols.smpp.error import * from jasmin.vendor.smpp.pdu.constants import priority_flag_value_map from jasmin.vendor.smpp.pdu.pdu_types import RegisteredDeliveryReceipt, RegisteredDelivery class SmppsCredentialVa...
the-stack_106_25045
""" Loggers help keep track of the workings of your evolutionary algorithm. By default, each Population is initialized with a BaseLogger, which you can use by using the .log() method of the population. If you want more complex behaviour, you can supply another logger to the Population on initialisation. """ import date...
the-stack_106_25047
import cv2 as cv import numpy as np import os from time import time, sleep from windowcapture import WindowCapture from vision import Vision from hsvfilter import HsvFilter, grab_object_preset from actions import Actions, Movement_Handler # Allow 3 seconds to open the gam window sleep(3) # Change the working director...
the-stack_106_25049
from typing import Dict, List import streamlit as st def get_case_default(features: List[str]) -> int: """ Heuristic for selecting a sound attribute as default for case id :param features: list of available features :return: index of the suggested feature in the list """ for idx, f in enumera...
the-stack_106_25050
import os import boto3 from common import AWSServiceCollector, AWS_REGIONS_SET sns = boto3.client('sns') sts = boto3.client('sts') class ElasticacheCollector(AWSServiceCollector): boto3_service_name = 'elasticache' def _collect_assets(self): max_records = 100 marker = '' while True...
the-stack_106_25051
from util.enums import ModelAttribute from util.trainer import load_model import yaml import argparse import numpy as np import torch from fine_tune_vae.models import * from fine_tune_vae.experiment import VAEXperiment import torch.backends.cudnn as cudnn from pytorch_lightning import Trainer from pytorch_lightning.lo...
the-stack_106_25052
from kg.checkers import * ### @import @chk.get_one_input def get_one_input(file, **kwargs): n = int(next(file)) a = list(map(int, next(file).strip().split())) ensure(len(a) == n, "Invalid length in input", exc=Fail) return a @chk.get_output_for_input @chk.get_judge_data_for_input def get_output_for_in...
the-stack_106_25054
# !/usr/bin/env python3 # -*- coding:utf-8 -*- # @author: Shengjia Yan # 2020-10-14 Wednesday # @email: i@yanshengjia.com # Copyright @ Shengjia Yan. All Rights Reserved. # Process lingspam corpus to generate trainset and testset in csv files. import os import csv import codecs import string TRAINSET_PATH = '../d...
the-stack_106_25057
import numpy as np from gym.spaces import Discrete, Box, MultiDiscrete from ..utils import instantiate class PowerElectronicConverter: """ Base class for all converters in a SCMLSystem. Properties: | *voltages(tuple(float, float))*: Determines which output voltage polarities the conv...
the-stack_106_25058
""" ZADANIE 1. GENERATOR KODÓW POCZTOWYCH przyjmuje 2 stringi: "79-900" i "80-155" i zwraca listę kodów pomiędzy nimi """ def post_code_generator(p_code1, p_code2): p_code1 = int(p_code1.replace('-', '')) p_code2 = int(p_code2.replace('-', '')) return ["%02d-%03d" % divmod(x, 1000) for x in range...
the-stack_106_25059
import json import watson_developer_cloud ASSISTANT_ID="<Enter your ASSISTANT_ID>" assistant = watson_developer_cloud.AssistantV2( iam_apikey='<Enter your API key>', version='2018-11-08', url='<Enter your assistant url that you set while creating the assistant>'# eg:'https://gateway-lon.watsonplatform...
the-stack_106_25060
import csv import operator important_rank = 6 def process_opioid_table(list_table): patient_id = 0 data = {} for table_loc in list_table: with open(table_loc, 'rb') as csvfile: data_reader = csv.reader(csvfile, delimiter=',') header = True for row in data_reader...
the-stack_106_25061
import subprocess from autonmt.api import NO_VENV_MSG def cmd_spm_encode(model_path, input_file, output_file, venv_path=None): print("\t- [INFO]: Using 'SentencePiece' from the command line.") env = f"{venv_path}" if venv_path else NO_VENV_MSG cmd = f"spm_encode --model={model_path} --output_format=piece...
the-stack_106_25062
from .db import get_connection, get_data from flask import render_template, url_for def do_db_info(): context = {'db': True} conn = get_connection() cur = conn.cursor() column_names, rows = get_data(cur, "SELECT * FROM PRINTERS") context['printers_cols'] = column_names context['printers_rows'] ...
the-stack_106_25069
import pandas as pd import numpy as np from RetailChurnTemplateUtility import * def azureml_main(df1=None, df2=None): key_column = 'UserId' IsDevelopment = True # Feature Engineering churnUtil = RetailChurnTemplateUtility() # Return value must be of a sequence of pandas.DataFrame ...
the-stack_106_25070
# Copyright 2018 The TensorFlow Probability 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 o...
the-stack_106_25071
# Copyright 2014 NEC Corporation. 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 ...
the-stack_106_25074
import components def NumDumbNodesTest (size): fws = ['f_%d'%(f) for f in xrange(0, size)] # Start with 4 end hosts end_hosts = ['e_%d'%(e) for e in xrange(2)] all_nodes = [] all_nodes.extend(end_hosts) all_nodes.extend(fws) addresses = ['ip_%s'%(n) for n in all_nodes] ctx = components...
the-stack_106_25075
from __future__ import annotations import sys import os sys.path.append(os.getcwd()) from typing import List, Dict, Tuple import math import joblib import numpy as np import bisect import random import copy from src.read_problem_data import ProblemData from src.util.print import bcolors int_inf = 9999 class Node...
the-stack_106_25077
def fn(): x = [] if a % 2 == 1: return "bad" for i in range(len(b)): if b[i] == c[i]: return "bad" if b[i] < c[i]: x.append(b[i] + c[i]) else: x.append(c[i] + b[i]) for i in x: if x.count(i) != 2: return "bad" re...
the-stack_106_25078
import sys import subprocess import os import collections import re def is_clang(command): for word in command: if '--compiler-bindir' in word and 'clang' in word: return True return False def main(): try: sys.argv.remove('--y_skip_nocxxinc') skip_nocxxinc = True ...
the-stack_106_25079
# coding: utf-8 from __future__ import unicode_literals import itertools from .common import InfoExtractor from ..compat import compat_str from ..utils import ( ExtractorError, int_or_none, try_get, ) CDN_API_BASE = 'https://cdn.younow.com/php/api' MOMENT_URL_FORMAT = '%s/moment/fetch/id=%%s' % CDN_API_B...
the-stack_106_25080
class Solution: def judgeCircle(self, moves: str) -> bool: x, y = 0, 0 for move in moves: if move == "U": y += 1 elif move == "D": y -= 1 elif move == "L": x -= 1 elif move == "R": x += 1...
the-stack_106_25081
from django.shortcuts import render from django.core.files.storage import default_storage from rest_framework.response import Response from rest_framework import generics, mixins from rest_framework.parsers import MultiPartParser from rest_framework.decorators import APIView from rest_framework.permissions import IsAu...
the-stack_106_25082
# -*- coding: utf-8 -*- # # 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 #...
the-stack_106_25084
from itertools import count import numpy as np def day25(inp): floor = np.array([list(row) for row in inp.splitlines()]) shape = floor.shape kind_codes = '>v' deltas = np.array([(0, 1), (1, 0)]) poses = [np.array((floor == kind_code).nonzero()) for kind_code in kind_codes] # two lists with s...
the-stack_106_25085
"""Utility functions, node construction macros, etc.""" # Author: Collin Winter # Local imports from .pgen2 import token from .pytree import Leaf, Node from .pygram import python_symbols as syms from . import patcomp ########################################################### ### Common node-construction ...
the-stack_106_25087
import angr import logging l = logging.getLogger(name=__name__) class atol(angr.SimProcedure): #pylint:disable=arguments-differ def run(self, s): strtol = angr.SIM_PROCEDURES['libc']['strtol'] return strtol.strtol_inner(s, self.state, self.state.memory, 10, True)[1]
the-stack_106_25088
from collections import deque from collections import namedtuple import numpy as np import cv2 from ..engine.base_service import BaseService from ..engine.adapters import get as get_adapter from ..utils.generic_utils import log from ..utils.output_utils import draw_objects_np from ..utils.output_utils import label_to_...
the-stack_106_25092
from . import Bing, Google import argparse def main(): parser = argparse.ArgumentParser( description="Scrape images from the internet.") parser.add_argument( "engine", help="Which search engine should be used? (Bing/Google)") parser.add_argument( "query", help="Query that should be used...
the-stack_106_25094
from __future__ import print_function import __main__ as main import os os.environ['https_proxy'] = 'https://localhost:1087' import fcntl import pandas as pd import mysql.connector import numpy as np import tensorflow as tf from pstk import data as dat from sqlalchemy import create_engine from joblib import Parallel,...
the-stack_106_25095
# Copyright 2018 NTRLab # # 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, softw...
the-stack_106_25098
#!/usr/bin/env python2.7 import boto3 import rx from poll import Poll from calculate import Sum from update import Update from delete import Delete import logging logging.getLogger( 'botocore.vendored.requests.packages.urllib3.connectionpool' ).setLevel(logging.CRITICAL) logging.getLogger('boto3.resources.actio...
the-stack_106_25099
import logging import wrapt import ddtrace log = logging.getLogger(__name__) # To set attributes on wrapt proxy objects use this prefix: # http://wrapt.readthedocs.io/en/latest/wrappers.html _DD_PIN_NAME = '_datadog_pin' _DD_PIN_PROXY_NAME = '_self_' + _DD_PIN_NAME class Pin(object): """Pin (a.k.a Patch INfo...
the-stack_106_25100
""" A module for constructing Hamiltonians for marginal reconstruction and variational 2-RDM theory. functionality to transform molecular integrals into the appropriate Tensor objects """ from itertools import product import numpy as np from scipy.linalg import block_diag from representability.fermions.basis_utils imp...
the-stack_106_25103
import json from summary.model import DockSummary from summary.schema import DockSummarySchema def load(dock_file: str) -> DockSummary: try: with open(dock_file) as json_file: data = json.load(json_file) return DockSummarySchema().load(data) except FileNotFoundError: r...
the-stack_106_25104
#!/usr/bin/env python3 """Script to check whether the installation is done correctly.""" # Copyright 2018 Nagoya University (Tomoki Hayashi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import importlib import shutil import sys from packaging.version import parse module_list = [ ("torchaudio", N...
the-stack_106_25105
# -*- coding: utf-8 -*- # # wotlkdoc_images documentation build configuration file, created by # sphinx-quickstart on Mon Jul 1 00:00:00 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
the-stack_106_25110
# # Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE. # # Distributed under 3-Clause BSD license. See LICENSE file for more information. # import numpy as np from scipy.sparse import ...
the-stack_106_25112
# Copyright (c) 2020 Aldo Hoeben / fieldOfView # The ArcWelderPlugin for Cura is released under the terms of the AGPLv3 or higher. from collections import OrderedDict import json import tempfile import os import stat import subprocess import locale import re from UM.Extension import Extension from UM.Application impo...
the-stack_106_25120
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyEasybuildFramework(PythonPackage): """The core of EasyBuild, a software build and instal...
the-stack_106_25122
import logging import time from typing import List, Optional from ..kafka import KafkaProducer from ..models.event_models import ( AcknowledgedWorkRequestEvent, CompletedWorkRequestEvent, HeartbeatEvent, LeaderChangedEvent, ) from ..models.subsystem_config_models import HeartbeatSubsystemConfiguration...
the-stack_106_25123
# -*- coding: utf-8 -*- """ Set of functions to make diff from Scan results. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.utils.encoding import force_unicode from ralph.discovery.models import Dev...
the-stack_106_25125
from typing import List from eventz.messages import Event from eventz_aws.types import EventPublisherProtocol class EventPublisherDummy(EventPublisherProtocol): def __init__(self): self.events: List[Event] = [] def publish( self, connection_id: str, route: str, msgid...
the-stack_106_25126
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem from sqlalchemy.pool import SingletonThreadPool from flask import session as login_session import rando...
the-stack_106_25127
from flask import Flask, request, send_from_directory import os import argparse from tqdm import tqdm from flask import jsonify import csv import numpy from bling_fire_tokenizer import BlingFireTokenizer import yaml app = Flask(__name__, static_url_path='') app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # # data loading...
the-stack_106_25132
# -*- coding: utf-8 -*- from pandas_ta.utils import get_offset, pascals_triangle, verify_series, weights def pwma(close, length=None, asc=None, offset=None, **kwargs): """Indicator: Pascals Weighted Moving Average (PWMA)""" # Validate Arguments length = int(length) if length and length > 0 else 10 ...
the-stack_106_25133
from typing import Optional, Union import torch from catalyst.metrics.functional._classification import precision_recall_fbeta_support def precision( outputs: torch.Tensor, targets: torch.Tensor, argmax_dim: int = -1, eps: float = 1e-7, num_classes: Optional[int] = None, ) -> Union[float, torch....
the-stack_106_25135
import torch import torchvision.transforms as T class Config: # network settings backbone = 'fmobile' # [resnet, fmobile] metric = 'arcface' # [cosface, arcface] embedding_size = 512 drop_ratio = 0.5 # data preprocess input_shape = [1, 128, 128] train_transform = T.Compose([ T...
the-stack_106_25141
""" MIT License Copyright (c) 2021 Ashwin Vallaban Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...