filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_20491 | # -*- 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 "L... |
the-stack_106_20494 | import hashlib
import os
import mimetypes
from time import time
from zlib import adler32
from werkzeug.datastructures import Headers
from werkzeug.wrappers import Response
from werkzeug.wsgi import wrap_file
SEND_FILE_MAX_AGE_DEFAULT = 43200 # 12 hours, default from Flask.
def send_file(request, filename, attachm... |
the-stack_106_20496 | from __future__ import division
import os
import cv2
import numpy as np
import sys
import pickle
from optparse import OptionParser
import time
from keras_frcnn import config
from keras import backend as K
from keras.layers import Input
from keras.models import Model
from keras_frcnn import roi_helpers
sys.setrecursion... |
the-stack_106_20502 |
import os
from dataclasses import dataclass
from datetime import date
from datetime import datetime
from typing import Any
from typing import Dict
import requests
from common.dicts import Objectview
class ResponseError(Exception):
def __init__(self, *args, response, **kwargs):
super().__init__(*args, *... |
the-stack_106_20504 | def Kadane(array):
partialSum = bestSum = array[0]
fromIndex = toIndex = 0
for i in range(1, len(array)):
if array[i] > partialSum + array[i]:
partialSum = array[i]
fromIndex = i
else:
partialSum += array[i]
if partialSum >= bestSum:
bestSum = partialSum
toIndex = i
return {
"fromIndex" ... |
the-stack_106_20505 | import asyncio
import functools
import operator
from typing import (
cast,
Iterable,
NamedTuple,
Sequence,
Type,
Tuple,
)
from cached_property import cached_property
from cancel_token import CancelToken
from eth_utils import (
ExtendedDebugLogger,
to_tuple,
)
from eth_utils.toolz impo... |
the-stack_106_20506 | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from util import exec_remote_command
from dbaas_cloudstack.models import HostAttr as CS_HostAttr
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0020
LOG = logging.getLogger(__name__)
class ConfigLog(Ba... |
the-stack_106_20507 | from random import randint
from sympy import expand, sqrt
from cartesian import *
def sub_y(x, y):
return y, (1 - randint(0, 1)*2)*sqrt(1 - x**2)
def main():
# A hexagon ABCDEF inscribed in a unit circle
# Prove 3 intersections of opposite edges (AB∩DE, BC∩EF, CD∩FA) are collinear
a, b, c, d, e, f, g,... |
the-stack_106_20509 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import errno
import codecs
import collections
import json
import math
import shutil
import sys
import numpy as np
import tensorflow as tf
import pyhocon
def initialize_from_env():
if "GPU" in os.... |
the-stack_106_20511 | # MIT License
# Copyright (c) 2019 Yang Liu and the HuggingFace team
# 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, c... |
the-stack_106_20512 | """
Module for executing git commands, sending results back to the handlers
"""
import os
import subprocess
from subprocess import Popen, PIPE
class Git:
"""
A single parent class containing all of the individual git methods in it.
"""
def __init__(self, root_dir, *args, **kwargs):
super(Git,... |
the-stack_106_20514 | """
See //docs/search.md for overview.
"""
import grpc
from sqlalchemy.sql import func, or_
from couchers import errors
from couchers.db import session_scope
from couchers.models import Cluster, Event, EventOccurrence, Node, Page, PageType, PageVersion, Reference, User
from couchers.servicers.api import (
hostings... |
the-stack_106_20520 | import numpy as np
import pandas as pd
results = {
'results-imagenet.csv': [
'results-imagenet-real.csv',
'results-imagenetv2-matched-frequency.csv',
'results-sketch.csv'
],
'results-imagenet-a-clean.csv': [
'results-imagenet-a.csv',
],
'results-imagenet-r-clean.csv... |
the-stack_106_20521 | pkgname = "bzip2"
pkgver = "1.0.8"
pkgrel = 0
pkgdesc = "Freely available, patent free, high-quality data compressor"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:bzip2"
url = "https://sourceware.org/bzip2"
source = f"https://sourceware.org/pub/bzip2/bzip2-{pkgver}.tar.gz"
sha256 = "ab5a03176ee106d3f0fa... |
the-stack_106_20522 | #
# 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
# ... |
the-stack_106_20524 | from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class HighscoresDialog(QDialog):
def __init__(self, scorelist, parent=None):
super(HighscoresDialog, self).__init__(parent)
self.setWindowTitle('High Scores')
frame = QFrame(self)
frame.setFrameStyle... |
the-stack_106_20526 | import os
import json
import math
import torch
import numpy
import os.path
import pandas
import argparse
import scikit_wrappers
import sys
def load_UCR_dataset(path, dataset):
"""
Loads the UCR dataset given in input in numpy arrays.
@param path Path where the UCR dataset is located.
@param dataset Na... |
the-stack_106_20527 | from helpers import upload
import json
import os
# Assumes the system's current directory is iot-farm/src
with open('config.json') as f:
CONFIG = json.load(f)
def create_file(filename: str):
f = open(filename, 'w')
f.write('Hello again world!')
f.close()
def main():
uploader = upload.Uploader(CON... |
the-stack_106_20528 | import numpy as np
import pytest
from . import fit_atg_model
from .fit_atg_model import AtgModelFit
def test_fit_atg_model():
a = 2719.0
tg = 7.2
exp = 6.23
t0 = 2.5
xs = np.arange(1, 100)
# Test perfect fit.
ys = fit_atg_model._model(params=[a, tg, exp, t0], xs=xs)
fit = fit_atg_mod... |
the-stack_106_20529 | """Interaction with smart contracts over Web3 connector.
"""
import functools
from eth_abi import (
encode_abi,
decode_abi,
)
from web3.utils.encoding import (
encode_hex,
)
from web3.utils.formatting import (
add_0x_prefix,
remove_0x_prefix,
)
from web3.utils.string import (
force_bytes,
... |
the-stack_106_20530 | import numpy as np
from collections import defaultdict
import random
class Agent:
def __init__(self, nA=6):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(lambda: np.zeros(self.nA))
... |
the-stack_106_20531 | import re
from abc import ABC, abstractmethod
from typing import List
from nltk import Tree, ParentedTree
def pas_to_str(x):
if isinstance(x, tuple): # has children
head = x[0]
children = [pas_to_str(e) for e in x[1]]
return f"{head}({', '.join(children)})"
else:
return x
... |
the-stack_106_20532 | import random
import json
import pymsteams
import torch
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('intents.json', 'r') as json_data:
intents = json.load(json_data)
FILE = "data.pth"
data = torch.load(... |
the-stack_106_20534 | import logging
from collections import namedtuple
from six import string_types
from samtranslator.metrics.method_decorator import cw_timer
from samtranslator.model.intrinsics import ref, fnGetAtt, make_or_condition
from samtranslator.model.apigateway import (
ApiGatewayDeployment,
ApiGatewayRestApi,
ApiGa... |
the-stack_106_20535 | # Configuration file for Jupyter Hub
from jinja2 import Template
from oauthenticator.github import GitHubOAuthenticator
from jupyterhub.auth import PAMAuthenticator
from jupyterhub.traitlets import Command
from jupyterhub.apihandlers.base import APIHandler
from jupyterhub.handlers.login import LogoutHandler
from jupyt... |
the-stack_106_20536 | import sys, os
sys.path.append(os.path.dirname(__file__)+'/../../../')
import FormulaSolidityPort
import FormulaNativePython
MIN = 0
MAX = 2 ** 256 - 1
PPM_RESOLUTION = 1000000
def add(a, b):
assert a + b <= MAX, 'error {} + {}'.format(a, b)
return a + b
def sub(a, b):
assert a - b >= MIN, 'error {} - ... |
the-stack_106_20538 | """
===============
Radon transform
===============
In computed tomography, the tomography reconstruction problem is to obtain
a tomographic slice image from a set of projections [1]_. A projection is formed
by drawing a set of parallel rays through the 2D object of interest, assigning
the integral of the object's con... |
the-stack_106_20539 | import pygame
import sys
SCREENWIDTH = 800
SCREENHEIGHT = 600
max_iteration = 255
pygame.init()
screen = pygame.display.set_mode(
(SCREENWIDTH, SCREENHEIGHT), pygame.DOUBLEBUF | pygame.HWSURFACE)
pygame.display.set_caption("Mandelbrot Fractal")
fractal = screen.copy()
pygame.mixer.init()
fractal.fill((0, 0, ... |
the-stack_106_20540 | """Module for creating and managing random sequences or keys."""
import random
from shufflealgos import List
class Key:
"""Class for managing random sequences of integers."""
def __init__(
self, globalminval: int = 1, globalmaxval: int = 200,
length: int = 100, values: List[int] = No... |
the-stack_106_20541 | # 2021 - Douglas Diniz - www.manualdocodigo.com.br
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from hexdata import HexData
from selections import Selections
class HexEditor_p(QtWidgets.QWidget):
def __init__(self, parent):
super(HexEditor_p, self).__init__(parent)
... |
the-stack_106_20543 | import unittest
import time
from selenium import webdriver
from HtmlTestRunner import HTMLTestRunner
class My_Test(unittest.TestCase):
''' 百度搜索测试'''
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(10)
self.base_url = '... |
the-stack_106_20544 | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Copyright (c) 2017-2020 The Qtum Core developers
# Copyright (c) 2020 The BCS Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Tests... |
the-stack_106_20545 | import time
import os
import json
from vcpeutils.csar_parser import CsarParser
from robot.api import logger
from datetime import datetime
import sys
from ONAPLibrary.PreloadSDNCKeywords import PreloadSDNCKeywords
from ONAPLibrary.RequestSOKeywords import RequestSOKeywords
from ONAPLibrary.BaseAAIKeywords import BaseAAI... |
the-stack_106_20548 | """
Schema differencing support.
"""
import logging
import sqlalchemy
from sqlalchemy.types import Float
log = logging.getLogger(__name__)
def getDiffOfModelAgainstDatabase(metadata, engine, excludeTables=None):
"""
Return differences of model against database.
:return: object which will evaluate to... |
the-stack_106_20556 | import math
import pdb
import torch
import torch.nn as nn
from torch.nn import functional as F
from .fully_connected import MLP
class TRMMHAttention(nn.Module):
def __init__(self, n_heads, d_model, dropout_p=0.):
super(TRMMHAttention, self).__init__()
self.d_model = d_model
self.n_hea... |
the-stack_106_20557 | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... |
the-stack_106_20560 | """setup for the dlib project
Copyright (C) 2015 Ehsan Azar (dashesy@linux.com)
License: Boost Software License See LICENSE.txt for the full license.
This file basically just uses CMake to compile the dlib python bindings project
located in the tools/python folder and then puts the outputs into standard
python pa... |
the-stack_106_20563 | # Copyright 2020 Facebook, Los Alamos National Laboratory
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
the-stack_106_20564 | """Gravitational Search Algorithm.
"""
import numpy as np
import opytimizer.math.general as g
import opytimizer.math.random as r
import opytimizer.utils.constant as c
import opytimizer.utils.exception as e
import opytimizer.utils.logging as l
from opytimizer.core import Optimizer
logger = l.get_logger(__name__)
cl... |
the-stack_106_20565 | """Platform for the Daikin AC."""
import asyncio
from datetime import timedelta
import logging
from socket import timeout
import async_timeout
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_HOSTS
import homeassistant.helpers.config_val... |
the-stack_106_20566 | class IntcodeMemory(object):
def __init__(self, init_data=None):
self.data = {}
for address, value in enumerate(init_data):
self.data[address] = value
def __repr__(self):
return repr(self.data)
def __setitem__(self, address, value):
self.data[address] = value
... |
the-stack_106_20567 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import NavCoinTestFramework
from test_framework.util import *
BLOCK_R... |
the-stack_106_20568 | '''
Write a Python program to find the occurrence and position of the substrings
within a string.
'''
import re
sub=input()
n=input()
for i in re.finditer(pattern=sub,string=n):
print(i.start(),n[i.start():i.end()]) |
the-stack_106_20570 | # -*- coding: utf-8 -*-
from irc3 import dec
import venusian
import functools
def plugin(wrapped):
"""register a class as server plugin"""
setattr(wrapped, '__irc3_plugin__', False)
setattr(wrapped, '__irc3d_plugin__', True)
return wrapped
class event(dec.event):
"""same as :class:`~irc3.dec.eve... |
the-stack_106_20572 | #!/usr/bin/env python
# /export/covey1/CMIP5/Precipitation/DiurnalCycle/HistoricalRuns/compositeDiurnalStatisticsWrapped.py
# This modifiction of ./compositeDiurnalStatistics.py will have the PMP Parser "wrapped" around it,
# so that it can be executed with input parameters in the Unix command line, for example:
# --... |
the-stack_106_20573 | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA 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... |
the-stack_106_20575 | """Persistence details for Model Classes"""
from __future__ import unicode_literals # isort:skip
from future import standard_library # isort:skip
standard_library.install_aliases() # noqa: E402
from io import StringIO
import json
import os
from flask import current_app
from sqlalchemy import exc
from ..database ... |
the-stack_106_20577 | #!/usr/bin/env python
# Copyright 2017 The Kubernetes 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 appli... |
the-stack_106_20580 | #!/usr/bin/env python3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
from basecls.configs import RegNetConfig
_cfg = dict(
model=dict(
name="regnety_080",
),
)
class Cfg(RegNetConfig):
def __init__(self, values_or_file=None, **kwargs):
super().__init__(_cfg)
self.merg... |
the-stack_106_20582 | """
Given a char array representing tasks CPU need to do.
It contains capital letters A to Z where different letters represent different tasks.
Tasks could be done without original order. Each task could be done in one interval.
For each interval, CPU could finish one task or just be idle.
However, there is a non... |
the-stack_106_20583 | import traceback
from celery import shared_task
from celery.utils.log import get_task_logger
# NOTE: do not import `models` to avoid recursive imports
logger = get_task_logger(__name__)
def _safe_execution(func, *args, **kwargs):
"""Execute a task and return any tracebacks that occur as a string."""
try:
... |
the-stack_106_20585 | from datetime import datetime, timedelta
import jwt
import pytest
from flask import testing
from werkzeug.datastructures import Headers
# pylint: disable=wrong-import-position
# We need to override the database
from yeti.common.config import yeti_config
yeti_config.arangodb.database = yeti_config.arangodb.database + ... |
the-stack_106_20586 | from window import Window
from dialogs.dialog import FormDialog
from dialogs.text_widget import TextWidget
from dialogs.wlist import ListWidget
from utils import center_rect
from color import color_name
import config
class ColorDialog(FormDialog):
def __init__(self):
super().__init__(Window(center_rect(60... |
the-stack_106_20589 | from flask_wtf import FlaskForm
from wtforms import FieldList, FormField, HiddenField, SelectField, \
StringField, SubmitField, TextAreaField, ValidationError
from wtforms.validators import DataRequired, Optional
class GroupForm(FlaskForm):
"""Subform for groups"""
group_id = HiddenField('Gruppen-ID', val... |
the-stack_106_20590 | # Copyright (c) 2013 Mirantis 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_20592 | from collections import deque
from itertools import combinations
def add_list_to_dict(target_dict, key, value):
if key in target_dict.keys():
target_dict[key].append(value)
else:
target_dict[key] = [value]
class Node:
def __init__(self, player, terminal, eu=0):
self.children = {}... |
the-stack_106_20593 | # Lib
import logging
import numpy as np
import pandas as pd
from ..utils.progress_bar import * # checks environment and imports tqdm appropriately.
from collections import Counter
from pathlib import Path
import pickle
# App
from ..files import Manifest, get_sample_sheet, create_sample_sheet
from ..models import Channe... |
the-stack_106_20594 | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysnmp.sf.net/license.html
#
# Copyright (C) 2008 Truelite Srl <info@truelite.it>
# Author: Filippo Giunchedi <filippo@truelite.it>
#
# This program is free software; you can redistribute it and/or modi... |
the-stack_106_20595 | import argparse
import os
import platform
import sys
import socket
from typing import List, Optional, Union, Callable
import requests
from pygments import __version__ as pygments_version
from requests import __version__ as requests_version
from . import __version__ as httpie_version
from .cli.constants import OUT_REQ... |
the-stack_106_20597 | """
NVLAMB optimizer.
"""
import collections
import math
import torch
from tensorboardX import SummaryWriter
from torch.optim import Optimizer
# not finished yet
def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
"""Log a histogram of trust ratio scalars in across layers."""
... |
the-stack_106_20598 | from PyQt5.QtWidgets import QFileDialog
from ...i18n import _
from ...plugin import run_hook
from .util import ButtonsTextEdit, MessageBoxMixin, ColorScheme
class ShowQRTextEdit(ButtonsTextEdit):
def __init__(self, text=None):
ButtonsTextEdit.__init__(self, text)
self.setReadOnly(1)
ico... |
the-stack_106_20599 | # Author: Hansheng Zhao <copyrighthero@gmail.com> (https://www.zhs.me)
# import required setup libraries
from setuptools import setup, find_packages
from codecs import open
from os import path
# import library for metadata
from decibel import __author__, __license__, __version__
# project absolute directory
DIRECTOR... |
the-stack_106_20601 | import io
import os
import re
from setuptools import find_packages
from setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding='utf-8') as fd:
return re.sub(text_type(r':[a-z]+:`~?(.*... |
the-stack_106_20605 | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.T... |
the-stack_106_20606 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in an... |
the-stack_106_20607 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import find_packages
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == "publish":
os.system("python setup.py sdist upload")
sys.exit()
if sys.argv[-1] == "test"... |
the-stack_106_20610 | r1 = float(input('Primeiro Segmento: '))
r2 = float(input('Segundo Segmento: '))
r3 = float(input('Terceiro Segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos PODEM FORMAR um triângulo ', end='')
if r1 == r2 == r3:
print('EQUILATERO.')
elif r1 != r2 != r3 != r1:
... |
the-stack_106_20612 | import asyncio
import time
import trio
import joulehunter
def do_nothing():
pass
def busy_wait(duration):
end_time = time.time() + duration
while time.time() < end_time:
do_nothing()
async def say(what, when, profile=False):
if profile:
p = joulehunter.Profiler()
p.start... |
the-stack_106_20613 | import astropy.units as u
import numpy as np
import pytest
from astropy import time
from astropy.constants import c
from astropy.coordinates import (SkyCoord, EarthLocation, ICRS, GCRS, Galactic,
CartesianDifferential, SpectralCoord,
get_body_barycentric... |
the-stack_106_20615 | """empty message
Revision ID: 37dc079188db
Revises: None
Create Date: 2015-01-19 20:32:38.647835
"""
# revision identifiers, used by Alembic.
revision = '37dc079188db'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... |
the-stack_106_20616 | import os
import subprocess
def cmd(cmd, listed=False):
output = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
correct_output = output.communicate()[0].decode().replace('\'', '').splitlines()
if listed:
return correct_output
else:
return correct_ou... |
the-stack_106_20619 | # Copyright (c) 2020, Manfred Moitzi
# License: MIT License
"""
This module provides "nested Polygon" detection for multiple paths.
Terminology
-----------
exterior
creates a filled area, has counter-clockwise (ccw) winding in matplotlib
exterior := Path
hole
creates an unfilled area, has clockwise win... |
the-stack_106_20620 | # -*- coding: utf-8 -*-
# This module is responsible for communicating with the outside of the yolo package.
# Outside the package, someone can use yolo detector accessing with this module.
import os
import numpy as np
from yolo.backend.decoder import YoloDecoder
from yolo.backend.loss import YoloLoss
from yolo.backe... |
the-stack_106_20621 | from interfaces.interface import Resource
from enum import Enum
class Code(object):
enum = {"RELIANCE": "RI",
"CIPLA": "C",
"BIOCON": "BL03",
"AXISBANK": "UTI10",
"HDFCBANK": "HDF01",
"BAJFINANCE": "BAF",
"HEROMOTOCO": "HHM",
"DIV... |
the-stack_106_20622 | # Natural Language Toolkit: evaluation of dependency parser
#
# Author: Long Duong <longdt219@gmail.com>
#
# Copyright (C) 2001-2018 NLTK Project
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import division
import unicodedata
class DependencyEvaluator(object):
"""
Cla... |
the-stack_106_20625 | # subprocess - Subprocesses with accessible I/O streams
#
# For more information about this module, see PEP 324.
#
# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
#
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/2.4/license for licensing details.
r"""subprocess - Subpr... |
the-stack_106_20626 | import errno
import unittest
from test import support
from test.support import os_helper
from test.support import socket_helper
from test.test_urllib2 import sanepathname2url
import os
import socket
import urllib.error
import urllib.request
import sys
support.requires("network")
def _retry_thrice(func, exc, *args, ... |
the-stack_106_20627 |
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
values = []
self.visit(root, values)
return values
def visit(self, root, values):
values.append(root.val)
for child in root.children:
self.visit(child, values)
|
the-stack_106_20629 | """"
Google cloud storage
"""
from io import BytesIO
from google.cloud import storage
from google.cloud.exceptions import NotFound
from sqlalchemy_media.exceptions import GCPError
from sqlalchemy_media.optionals import ensure_gcs
from .base import Store
from ..typing_ import FileLike
class GoogleCloudStorge(Sto... |
the-stack_106_20631 | # -*- coding: utf-8 -*-
"""
@File: rnns.py
@Copyright: 2019 Michael Zhu
@License:the Apache License, Version 2.0
@Author:Michael Zhu
@version:
@Date:
@Desc:
"""
import torch
import torch.nn as nn
class RnnEncoder(nn.Module):
"""
A ``RnnEncoder`` is a rnn layer. As a
:class:`Seq2SeqEncoder`, the input t... |
the-stack_106_20632 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
the-stack_106_20634 | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def pytest_addoption(parser):
parser.addoption('--language', action='store', default='en',
help="Choose language for page")
@pytest.fixture(scope="function")
def browser(request):
print("\... |
the-stack_106_20637 | # -*- coding: utf-8 -*-
import os
import time
import unittest
from configparser import ConfigParser
from GenomeReport.GenomeReportImpl import GenomeReport
from GenomeReport.GenomeReportServer import MethodContext
from GenomeReport.authclient import KBaseAuth as _KBaseAuth
from installed_clients.WorkspaceClient import... |
the-stack_106_20638 | import os
import json
import time
import datetime
import os.path
from pathlib import Path
from loguru import logger
from pycoingecko import CoinGeckoAPI
# NOTE: this is a WIP
def _get_coins_list(use_cache=True, filename="_coingecko/coins_list.json"):
cg = CoinGeckoAPI()
if use_cache and os.path.isfile(filen... |
the-stack_106_20641 | """
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
... |
the-stack_106_20642 | import sys
sys.path.insert(0, '../')
from maskrcnn_benchmark.config_aurora import cfg
from predictor import AuroraDemo
import cv2
import matplotlib.pyplot as plt
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from PIL import Image
import numpy as np
import math
import os
save_reults_folder = './results/'
if not os... |
the-stack_106_20644 | import sys, yaml
with open("config/config.yaml", 'r') as stream:
data = yaml.safe_load(stream)
species = data["species"]
version = data["genome"]
ucsc2ensembl={}
for line in open(f"../resources/ChromosomeMappings/{version}_UCSC2ensembl.txt"):
linesplit=line.strip().split("\t")
if len(linesplit) <= 1: cont... |
the-stack_106_20645 | import flask
import sqlite3
from flask import g
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
DATABASE = './database.db'
TABLE_NAME = "books"
COLUMN_ID_NAME = "id"
COLUMN_TITLE_NAME = "title"
COLUMN_AUTHOR_NAME = "author"
COLUMN_CATEGORY_NAME = "category"
def get_db():
... |
the-stack_106_20648 | import os
import re
from typing import Optional, Tuple
# Github has two URLs, one that is https and one that is ssh
GITHUB_HTTP_URL = r"^https://(www\.)?github.com/(.+)/(.+).git$"
GITHUB_SSH_URL = r"^git@github.com:(.+)/(.+).git$"
# We don't support git < 2.7, because we can't get repo info without
# talking to the r... |
the-stack_106_20649 | # Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LIC... |
the-stack_106_20650 | import setuptools
from setuptools_behave import behave_test
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="colorgrade",
version="0.0.1",
author="Alexey Kuznetsov",
author_email="kuznecov.alexey@gmail.com",
description="Conditional formatting for termina... |
the-stack_106_20651 | #------------------------------------------------------------------------------
# Copyright 2013 Esri
# 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/LICENS... |
the-stack_106_20654 | import asyncio
from unittest import mock
from lib.jsonrpc import RPCError
from server.env import Env
from server.controller import Controller
loop = asyncio.get_event_loop()
def set_env():
env = mock.create_autospec(Env)
env.coin = mock.Mock()
env.loop_policy = None
env.max_sessions = 0
env.max_... |
the-stack_106_20655 | __author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>"
__version__ = "$Revision$"
__copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim"
from .base import validatorBase
from .validators import *
#
# author element.
#
class category(validatorBase):
def getExpectedAttrN... |
the-stack_106_20657 | import os
import torch
import numpy as np
from model import CNN, init_weights
from my_dataset import initialize_loader
from train import Trainer
import cv2
import util
import torchvision
from PIL import Image
from model import find_batch_bounding_boxes, Label
def train_model(load_model=None, num_features=16):
exp... |
the-stack_106_20658 | import numpy as np
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
import seaborn as sns
import time
from neural_clf.controllers.clf_qp_net import CLF_QP_Net
from neural_clf.controllers.constrained_lqr import PVTOLSimpleMPC
from models.pvtol import (
control_affine_dynamics,
u_nominal,
n... |
the-stack_106_20659 | #
# Copyright 2013, Couchbase, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
the-stack_106_20660 | #!/usr/bin/env python3
import pyeapi
class my_switch():
def __init__(self, config_file_location, device):
# loads the config file
pyeapi.client.load_config(config_file_location)
self.node = pyeapi.connect_to(device)
self.hostname = self.node.enable('show hostname')[0]['result... |
the-stack_106_20661 | #!/usr/bin/env python
#
# MIT License
#
# Copyright (c) 2018, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory (subject to receipt of any
# required approvals from the U.S. Dept. of Energy). All rights reserved.
#
# Permission is hereby granted, free of charge, to any person... |
the-stack_106_20662 | from flask_restful import Resource
from firebase_admin import firestore
from google.cloud import storage
from models import thumb_bucket
class MetaREST(Resource):
@staticmethod
def get():
# Make firestore client
fcl = firestore.client()
response = {}
# Gets the do... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.