filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_16454 | ############################################################
# #
# hprose #
# #
# Official WebSite: http://www.hprose.com/ #
# ... |
the-stack_106_16455 | import numpy as np
from scipy.signal import medfilt
import cv2
import os.path as op
from skimage import transform
"""
The image had better be squared... And width and height can both be divided by 4
"""
import gist
from IPython import embed
def get_gist_C_implementation(img, mask=None):
"""
Extract GIST desc... |
the-stack_106_16456 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# 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... |
the-stack_106_16459 | from dart.client.python.dart_client import Dart
from dart.model.datastore import Datastore, DatastoreState
if __name__ == '__main__':
dart = Dart('localhost', 5000)
assert isinstance(dart, Dart)
datastore = dart.get_datastore('KNMUGQWTHT')
assert isinstance(datastore, Datastore)
datastore.data.st... |
the-stack_106_16460 | from typing import Any
from pandas_ml import ConfusionMatrix
import sklearn.metrics as metrics
from tabulate import tabulate
from collections import defaultdict
from expanded_checklist.checklist.utils import \
DataShape, ACCUMULATED_STR, FlattenGroup
from ..abstract_tests import ClassificationMetric
class BasicC... |
the-stack_106_16461 | __author__ = 'heroico'
import sqlite3
import numpy
from .. import KeyedDataSet
from .. import Exceptions
import os
class DBLoaders(object):
@classmethod
def loadKeyedDataSetFromDB(cls, db_path, table_name, key_column, value_column):
if not os.path.exists(db_path):
raise Exceptions.BadFil... |
the-stack_106_16462 | # -*- coding: utf-8 -*-
import torch.nn as nn
import torch
# from pytorch_transformers import XLNetConfig, XLNetModel # old-version
# from transformers import XLNetConfig, XLNetModel, XLNetTokenizer
from transformers import BertTokenizer, BertModel
class Encoder_BERT(nn.Module):
def __init__(self, config, x_em... |
the-stack_106_16465 | # Import the WebIDL module, so we can do isinstance checks and whatnot
import WebIDL
def WebIDLTest(parser, harness):
# Basic functionality
threw = False
try:
parser.parse("""
A implements B;
interface B {
attribute long x;
};
interface ... |
the-stack_106_16466 | import numpy as np
import pytest
import tensorflow as tf
import tensorflow_probability as tfp
import gpflow
from gpflow import default_float
from gpflow.base import PriorOn
from gpflow.config import set_default_float
from gpflow.utilities import to_default_float
from tensorflow_probability.python.bijectors import Exp
... |
the-stack_106_16467 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs Apple's JetStream benchmark.
JetStream combines a variety of JavaScript benchmarks, covering a variety of
advanced workloads and programming techniq... |
the-stack_106_16468 | #1047 Tempo de jogo com minutos 14/04/2020
entrada = input().split()
a, b, c, d = entrada
a = int(a)
b = int(b)
c = int(c)
d = int(d)
inicio = a * 60 + b
fim = c * 60 + d
if inicio < fim:
hora = (fim - inicio) // 60
min = (fim - inicio) % 60
print('O JOGO DUROU {} HORA(S) E {} MINUTO(S)'.format(hora, min))
... |
the-stack_106_16469 | # Copyright 2013-2020 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 PyMpi4py(PythonPackage):
"""This package provides Python bindings for the Message Passing
... |
the-stack_106_16470 | # -*- 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_16471 | import dask
import dask.dataframe as dd
import json
import pandas as pd
import numpy as np
import os.path
import csv
import boto3
from dask.distributed import Client
import time
def load_dataset(client, data_dir, s3_bucket, nbytes, npartitions):
num_bytes_per_partition = nbytes // npartitions
filenames = []... |
the-stack_106_16476 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ct', '0027_auto_20180904_1112'),
]
operations = [
migrations.AddField(
model_name='lesson',
name='mc_simplified',
field=models.BooleanField(default=False... |
the-stack_106_16478 | import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def proper_noun_extractor(text, noun_limit=2):
out = ''
words = nltk.word_tokenize(text)
words = [word for word in words if word not in set(stopwords.words('english'))]
tagged = nltk.pos_tag(words)
for (word, tag) in tagged... |
the-stack_106_16479 | from Instrucciones.Identificador import Identificador
from Instrucciones.TablaSimbolos.Tipo import Tipo, Tipo_Dato
from Instrucciones.Expresiones.Primitivo import Primitivo
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.Excepcion import *
import hashlib
class Md5(Instruccion):
d... |
the-stack_106_16480 | import yaml
import os
import urllib.request
import ssl
import certifi
import pdfkit
import html2text
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import HTMLConverter
from pdfminer.layout import LAParams
from pycti import OpenCTIConn... |
the-stack_106_16481 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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_16483 | from torch.autograd import Variable
import torch.nn as nn
import torch
import numpy as np
import os
import re
import pickle
import argparse
from rnn import *
parser = argparse.ArgumentParser(description='PyTorch char-rnn')
parser.add_argument('--temperature', type=float, default=0.8)
parser.add_argument('--sample_le... |
the-stack_106_16484 | from mykrobe.typing.typer.base import Typer
from mykrobe.stats import log_lik_R_S_coverage
from mykrobe.stats import log_lik_R_S_kmer_count
from mykrobe.typing.typer.base import MIN_LLK
from mykrobe.typing.typer.base import DEFAULT_MINOR_FREQ
from mykrobe.typing.typer.base import DEFAULT_ERROR_RATE
from mykrobe.stats... |
the-stack_106_16486 | """Clean Wikipedia dumps for use as a training corpus."""
import re
import argparse
import html
import bz2
import logging
from .utensils import log_timer
from multiprocessing import cpu_count
logging.basicConfig(format='[{levelname}] {message}', style='{', level=logging.INFO)
cores = int(cpu_count() / 2)
@log_timer
d... |
the-stack_106_16488 | from toolz import (
pipe,
)
from eth_utils import (
to_bytes,
to_int,
)
from eth_account._utils.transactions import (
ChainAwareUnsignedTransaction,
UnsignedTransaction,
encode_transaction,
serializable_unsigned_transaction_from_dict,
strip_signature,
)
CHAIN_ID_OFFSET = 35
V_OFFSET = ... |
the-stack_106_16489 | """
An example of test script that implements Pytorch-Lightning
@Author: Francesco Picetti
"""
from argparse import ArgumentParser
import os
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import src
from train_cnn_lightning import CNN
try... |
the-stack_106_16494 | #!/usr/bin/env python2.7
# coding=utf-8
"""
Sopel - An IRC Bot
Copyright 2008, Sean B. Palmer, inamidst.com
Copyright © 2012-2014, Elad Alfassa <elad@fedoraproject.org>
Licensed under the Eiffel Forum License 2.
https://sopel.chat
"""
from __future__ import unicode_literals, absolute_import, print_function, division
... |
the-stack_106_16495 | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet balance RPC methods."""
from decimal import Decimal
from test_framework.test_framework impo... |
the-stack_106_16497 | #
# 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 u... |
the-stack_106_16503 | from __future__ import annotations
import numpy as np
from detectron2 import model_zoo
from detectron2.config import get_cfg
from detectron2.engine import DefaultPredictor
from torch.cuda import is_available
from model import helper_functions as help_fn
class SEGMpredictor:
def __init__(self, model_path: str):
... |
the-stack_106_16504 | from RGT.XML.SVG.basicSvgNode import BasicSvgNode
from RGT.XML.SVG.Attribs.positionAttributes import PositionAttributes
from types import StringType
class FePointLightNode(BasicSvgNode, PositionAttributes):
svgNodeType = BasicSvgNode.SVG_FE_POINT_LIGHT_NODE
ATTRIBUTE_Z = 'z'
def __init__(self,... |
the-stack_106_16505 | # TestSwiftExpressionsInMethodsPureSwift.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See htt... |
the-stack_106_16506 | from typing import List
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def backTrack(i):
nonlocal col_set, lc_set, rc_set, path, res
for j in range(n):
if (j in col_set) or ((i + j) in lc_set) or ((i - j) in rc_set):
continue
... |
the-stack_106_16509 | # This workload tests submitting many actor methods.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import ray
from ray.cluster_utils import Cluster
num_redis_shards = 5
redis_max_memory = 10**8
object_store_memory = 10**8
num_nodes = 10
mes... |
the-stack_106_16512 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from main.models import SettingModel
from studies.models import Study
class Intervention(SettingModel):
# This is used internally to provide backwards compatibility with the old version of this model. All old fields are
# s... |
the-stack_106_16513 | from django.db import models
from dcpython.app.models import ServiceSync
import feedparser
from dcpython.events.models import Event
from django.conf import settings
class PlaylistManager(models.Manager):
def sync(self, url=None):
url = url or settings.YOUTUBE_PLAYLIST_FEED
feed = feedparser.parse(... |
the-stack_106_16515 | #! /usr/bin/python3
# Filled orders may not be re‐opened, so only orders not involving BTC (and so
# which cannot have expired order matches) may be filled.
import struct
import decimal
D = decimal.Decimal
import logging
from lib import (config, exceptions, bitcoin, util)
FORMAT = '>QQQQHQ'
LENGTH = 8 + 8 + 8 + 8 +... |
the-stack_106_16516 | # FILE INFO ###################################################
# Author: Jason Liu <jasonxliu2010@gmail.com>
# Created on July 2, 2019
# Last Update: Time-stamp: <2019-09-07 09:18:15 liux>
###############################################################
import math, re
__all__ = ["QDIS", 'WelfordStats', "TimeMarks", ... |
the-stack_106_16518 | """
Finds the lowest sum of a set of five primes for which any two primes concatenate to produce another prime
Author: Juan Rios
"""
import math
from utils import prime_factors
lower_boundary = 10000
primes = prime_factors(lower_boundary)
primes_mod3_1 = []
primes_mod3_2 = []
for i in primes[1:]:
if i%3==1:
... |
the-stack_106_16519 | from argparse import ArgumentParser
from multiprocessing import Pool
from time import sleep
import requests
import os.path
import json
import sys
def args():
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-c', dest='crawl_top', required=False, default=False, ty... |
the-stack_106_16522 | from mle_hyperopt import hyperopt
def test_decorator():
@hyperopt(
strategy_type="Grid",
num_search_iters=25,
real={
"x": {"begin": 0.0, "end": 0.5, "bins": 5},
"y": {"begin": 0, "end": 0.5, "bins": 5},
},
)
def circle(config):
distance = abs... |
the-stack_106_16523 | #!/usr/bin/env python3
from os.path import basename, dirname, exists, join, relpath
import glob, shutil, sys
# Determine the root directory for the source build and the Installed Build
sourceRoot = sys.argv[1]
installedRoot = join(sourceRoot, 'LocalBuilds', 'Engine', 'Linux')
# Locate the bundled toolchain and copy i... |
the-stack_106_16525 | import discord
import string
from discord.ext import commands
from core import DCSServerBot, Plugin
class Help(Plugin):
@commands.command(name='help',
description='The help command!',
usage='<plugin>')
async def help(self, ctx, plugin='all'):
help_embed = ... |
the-stack_106_16526 | import os
from os.path import join as pjoin
import collections
import json
import torch
import numpy as np
import scipy.misc as m
import scipy.io as io
import matplotlib.pyplot as plt
import glob
from PIL import Image
from tqdm import tqdm
from torch.utils import data
from torchvision import transforms
SBD_PATH = '/m... |
the-stack_106_16527 | """Module with microscopic traffic simulation class and additional features."""
from dataclasses import dataclass
from typing import Tuple
import random
import math
from .section import Section
from .vehicle import Vehicle
from model_and_simulate.utilities.simulation import Simulation, SimulationParameters
class Traf... |
the-stack_106_16528 | #!/usr/bin/env python
u"""
esa_costg_swarm_sync.py
Written by Tyler Sutterley (10/2021)
Syncs Swarm gravity field products from the ESA Swarm Science Server
https://earth.esa.int/eogateway/missions/swarm/data
https://www.esa.int/Applications/Observing_the_Earth/Swarm
CALLING SEQUENCE:
python esa_costg_swar... |
the-stack_106_16529 | #!/usr/bin/env python3
import sys
import os
# load parent path of KicadModTree
sys.path.append(os.path.join(sys.path[0], "..", ".."))
from KicadModTree import *
def plcc4(args):
footprint_name = args["name"]
pkgWidth = args["pkg_width"]
pkgHeight = args["pkg_height"]
padXSpacing = args["pad_x_spac... |
the-stack_106_16531 | import argparse
import glob
import logging
import os
import torch
from quobert.model import BertForQuotationAttribution, evaluate
from quobert.utils.data import ConcatParquetDataset, ParquetDataset
logger = logging.getLogger(__name__)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_... |
the-stack_106_16532 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from data_source import DataSource
from future import Future
from operator import itemgetter
import docs_server_utils as utils
class APIListDataSource(... |
the-stack_106_16535 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
the-stack_106_16538 | #!/usr/bin/env python3
import pytest
from runfile.exceptions import RunfileFormatError
from runfile.target import Target
@pytest.mark.parametrize("name,valid", [
['foo', True],
['foo bar', False],
['foo:bar', True],
['FooBar', True],
['foo-bar', False],
[':foo', False],
['bar_', False],
... |
the-stack_106_16543 | # Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above... |
the-stack_106_16547 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Hicham Belhseine"
__email__ = "hbelhsei@purdue.edu"
import logging
import time
import multiprocessing
import cflib.crtp
from cflib.crazyflie import Crazyflie
from cflib.crazyflie.log import LogConfig
from cflib.crazyflie.syncCrazyflie import Sy... |
the-stack_106_16548 | from bolsonaro.data.dataset_parameters import DatasetParameters
from bolsonaro.data.dataset_loader import DatasetLoader
from bolsonaro.models.model_factory import ModelFactory
from bolsonaro.models.model_parameters import ModelParameters
from bolsonaro.models.ensemble_selection_forest_regressor import EnsembleSelection... |
the-stack_106_16552 | #
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""Environment plugin."""
import gettext
import os
import pwd
from otopi import plugin
from otopi import util
from ovirt_engine_setup import constants as osetupcons
from ovirt_engine_setup.engine_com... |
the-stack_106_16556 | """Train a DeepLab v3 plus model using tf.estimator API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
import deeplab_model
from utils import preprocessing
from tensorflow.python import debu... |
the-stack_106_16557 | # coding: utf-8
import warnings
import textwrap
from ruamel.yaml.compat import _F
if False: # MYPY
from typing import Any, Dict, Optional, List, Text # NOQA
__all__ = [
'FileMark',
'StringMark',
'CommentMark',
'YAMLError',
'MarkedYAMLError',
'ReusedAnchorWarning',
'UnsafeLoaderWar... |
the-stack_106_16558 | # -*- coding: utf-8 -*-
"""
Created on 03/09/2020
Author : Carlos Eduardo Barbosa
"""
from __future__ import print_function, division
import os
import itertools
import warnings
import numpy as np
from astropy.io import fits
from astropy.table import Table
import astropy.units as u
import astropy.constants as const... |
the-stack_106_16559 | import os
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
from baselines... |
the-stack_106_16562 | # -*- coding: utf-8 -*-
'''
Primary interfaces for the salt-cloud system
'''
# Need to get data from 4 sources!
# CLI options
# salt cloud config - CONFIG_DIR + '/cloud'
# salt master config (for master integration)
# salt VM config, where VMs are defined - CONFIG_DIR + '/cloud.profiles'
#
# The cli, master and cloud c... |
the-stack_106_16564 | import test.support
# Skip tests if _multiprocessing wasn't built.
test.support.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
test.support.import_module('multiprocessing.synchronize')
# import threading after _multiprocessing to raise a more revelant error
# message: "No module n... |
the-stack_106_16565 | import os
import multiprocessing as mp
from typing import Text, Type, List, Set, Dict, Tuple
from copy import deepcopy
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from appyratus.enum import EnumValueStr
from ravel.util.misc_functions import remove_keys, import_object
from ravel.co... |
the-stack_106_16566 | # Copyright 2015 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 agreed to in writing, s... |
the-stack_106_16570 | from django.utils.translation import gettext_lazy as _
from rest_framework.permissions import BasePermission
from rest_framework.permissions import (
DjangoModelPermissions as BaseDjangoModelPermissions,
)
from swapper import load_model
Organization = load_model('openwisp_users', 'Organization')
class BaseOrgani... |
the-stack_106_16571 | import numbers
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, Union
import warnings
import numpy as np
from pandas._libs import lib, missing as libmissing
from pandas._typing import ArrayLike, DtypeObj
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
fro... |
the-stack_106_16576 | """docter server."""
import os
import sys
import mimetypes
from datetime import datetime
from wsgiref import simple_server
import falcon
from jinja2 import Environment, FileSystemLoader
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
... |
the-stack_106_16577 | import time
from collections import OrderedDict
from ...plugins.Timer import Timer
from ...plugins.MitosPPumpController import MitosPPumpController
from ..Workflow import Workflow
inputs = OrderedDict(
ppumps_setup={},
delay_time=0.,
verbose=False
)
outputs = OrderedDict()
class TarePumps(Workflow):... |
the-stack_106_16578 | from conans.client.output import ScopedOutput
from conans.client.source import complete_recipe_sources
from conans.model.ref import ConanFileReference, PackageReference
from conans.errors import NotFoundException, RecipeNotFoundException
from multiprocessing.pool import ThreadPool
def download(app, ref, package_ids, ... |
the-stack_106_16580 | # Copyright 2016 Red Hat, 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... |
the-stack_106_16586 | import unittest
import json
import sys
from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path
sys.path.insert(0, make_splunkhome_path(["etc", "apps", "amp4e_events_input"]))
from splunklib.client import Service, KVStoreCollection
from bin.amp4e_events_input.amp_storage_wrapper import AmpStorageWrapper
fr... |
the-stack_106_16587 | #!/usr/bin/env python
#
# 'idf.py' is a top-level config/build command line tool for ESP-IDF
#
# You don't have to use idf.py, you can use cmake directly
# (or use cmake in an IDE)
#
#
#
# Copyright 2019 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may n... |
the-stack_106_16589 | # -*- coding: utf-8 -*-
import json
import queue
import random
import time
import pytest
import requests
from botocore.exceptions import ClientError
from localstack import config
from localstack.config import external_service_url
from localstack.constants import TEST_AWS_ACCOUNT_ID
from localstack.http import Request... |
the-stack_106_16590 | import random
import logging
import torch
from classla.models.common.data import map_to_ids, get_long_tensor, get_float_tensor, sort_all
from classla.models.common.vocab import PAD_ID, VOCAB_PREFIX
from classla.models.pos.vocab import CharVocab, WordVocab
from classla.models.ner.vocab import TagVocab, MultiVocab
from ... |
the-stack_106_16591 | import os
import gzip
import json
import click
import pathlib
from pandas import read_csv, read_excel, DataFrame
from cli_util import DipException
class File:
def __init__(self, filename, ext, selected, view_name, is_cli=False):
self.view_name = view_name
self.filename = filename
self.ext... |
the-stack_106_16592 | # Copyright (c) 2018 Pablo Moreno-Munoz
# Universidad Carlos III de Madrid and University of Sheffield
import numpy as np
from GPy.likelihoods import link_functions
from GPy.likelihoods import Likelihood
from scipy.stats import multinomial
from functools import reduce
from GPy.util.misc import safe_exp, safe_square
fr... |
the-stack_106_16593 | # --------------------------------------------------------
# DenseCap-Tensorflow
# Written by InnerPeace
# This file is adapted from Linjie's work
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written b... |
the-stack_106_16594 |
PREAMBLE=[1,12,0,20,8,16]
def get_nth_word_spoken(preamble: list[int], target: int) -> int:
lookup = {val: pos for pos, val in enumerate(preamble[:-1])}
last_number = preamble[-1]
# start at the last number
for num in range(len(preamble)-1, target-1):
last_numbers_position = lookup.get(last_nu... |
the-stack_106_16595 | from django.core.exceptions import ImproperlyConfigured
class BaseIntegration:
required_credentials = []
def __init__(self, **credentials):
for key, value in credentials.items():
setattr(self, key, value)
for credential in self.required_credentials:
if not hasattr(sel... |
the-stack_106_16596 | # Copyright (c) 2014-present PlatformIO <contact@platformio.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 required by appli... |
the-stack_106_16598 | """Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "df59bf832ffdaf7c2179b6f9d80e23aaa57abc03"
TFRT_SHA256 = "40376db39e47a8b61235c40278974ac159543c78e86c6a... |
the-stack_106_16602 | from collections import defaultdict
import os
import argparse
import decimal
from ast import literal_eval
import sys
import json
import subprocess
import copy
import re as re_module
import tables
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse
from sympy import re, im, Float, exp, diff
from pyne... |
the-stack_106_16603 | import numpy as np
import logging
import sys
import matplotlib.pyplot as plt
logging.basicConfig(level=logging.INFO)
ca_file = "ca_red.vec"
es_file = "es_red.vec"
def file2wordsNmatrix(file):
logging.info(f"> Processing file {file}")
words = []
matrix = []
with open(file) as fd:
next(fd) # ... |
the-stack_106_16604 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The 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 cop... |
the-stack_106_16608 | import os
import torch
import math
import numpy as np
from scipy.spatial.transform import Rotation as R
from math import radians
from PIL import Image, ImageFilter
from dataset.data_utils import process_viewpoint_label, TransLightning, resize_pad, random_crop
import torchvision.transforms as transforms
from model.resne... |
the-stack_106_16611 | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
rangeSum = -float("inf")
globalSum = -float("inf")
for i, num in enumerate(nums):
rangeSum = max(rangeSum, 0) + num
globalSum = max(globalSu... |
the-stack_106_16612 | #!/usr/bin/env python3
# Copyright (c) 2016-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
G... |
the-stack_106_16613 | import numpy as np
import matplotlib.pyplot as pt
import pickle as pk
np.set_printoptions(precision=4, linewidth=200)
# g = np.arctanh
# rho = .99
g = lambda x: x
rho = 1
def run_trial(N, P, rho, verbose = False):
X = np.random.choice([-1,1], (N,P)) * rho
Y = np.random.choice([-1,1], (N,P)) * rho
... |
the-stack_106_16614 | from robot.api.parsing import ModelTransformer, Token
try:
from robot.api.parsing import InlineIfHeader
except ImportError:
InlineIfHeader = None
from robotidy.disablers import skip_section_if_disabled
from robotidy.utils import ROBOT_VERSION
EOL = Token(Token.EOL)
CONTINUATION = Token(Token.CONTINUATION)
c... |
the-stack_106_16615 | import click
import progressbar
from ..models import ImageModel
from ..imagebutler import db
@click.group()
def image():
pass
@image.command('gen_thumbnail')
@click.option('--type')
def thumbnail_regen(**kwargs):
"""Generate thumbnail for all|missing images. For first implement, we
do not care about per... |
the-stack_106_16616 | # encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
from __future__ import absolute_import
import io as stdlib_io
import os.path
import stat
import sys
from subprocess import Popen, PIPE
im... |
the-stack_106_16618 | import setuptools
with open("project-description.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name="pyserini",
version="0.16.0",
author="Jimmy Lin",
author_email="jimmylin@uwaterloo.ca",
descriptio... |
the-stack_106_16619 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""
Multi-channel CSC
=================
This example demonstrates solving a convolutional sparse coding problem wi... |
the-stack_106_16620 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
... |
the-stack_106_16622 | import mmcv
import numpy as np
import torch
from torch.utils.data import Dataset
from .builder import DATASETS
def create_real_pyramid(real, min_size, max_size, scale_factor_init):
"""Create image pyramid.
This function is modified from the official implementation:
https://github.com/tamarott/SinGAN/blo... |
the-stack_106_16623 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... |
the-stack_106_16625 | """Launchpad custom external dependencies."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Sanitize a dependency so that it works correctly from code that includes
# Launchpad as a submodule.
def clean_dep(dep):
return str(Label(dep))
def get_python_path(ctx):
path = ctx.os.environ.... |
the-stack_106_16627 | #transmute: benzodiazepine tool
import sqlite3
import tkinter
from tkinter import ttk
class Database(object):
def __init__(self, filename, table):
self.connection = sqlite3.connect(filename)
with self.connection:
self.connection.row_factory = sqlite3.Row
self.cursor = self... |
the-stack_106_16628 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AntMerchantExpandBenefitConfirmModel(object):
def __init__(self):
self._biz_ext = None
self._out_biz_time = None
self._record_id = None
self._user_id... |
the-stack_106_16629 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from itertools import groupby
from operator import itemgetter
import posixpath
from data_source import DataSource
from extensions_paths import JSON_TEMPLATE... |
the-stack_106_16633 | import re
from django.test import Client
from django.test import TestCase
from reviews.models import Publisher
class Exercise3Test(TestCase):
def test_fields_in_view(self):
""" "
Test that fields exist in the rendered template.
"""
c = Client()
response = c.get("/publishe... |
the-stack_106_16634 | import argparse
import signal
from tqdm import tqdm
import catconv.operations as co
import catconv.stabi as sb
exit = False
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
exit = True
parser = argparse.ArgumentParser()
parser.add_argument("source")
parser.add_argument("target")
parser.add_a... |
the-stack_106_16635 | import copy
import logging
import sys
from collections import defaultdict
from typing import Dict
import methodtools
from timebudget import timebudget
from jyotisha.panchaanga.spatio_temporal import daily
from jyotisha.panchaanga.temporal import time, set_constants, ComputationSystem, AngaType
from jyotisha.panchaang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.