filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_16224 | from JumpScale import j
import argparse
import sys
class ArgumentParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
if message:
self._print_message(message, sys.stderr)
if j.application.state == "RUNNING":
j.application.stop(status)
else:
... |
the-stack_0_16226 | """The :mod:`interpreter` module defines the ``PushInterpreter`` used to run Push programs."""
import traceback
from typing import Union
import time
from enum import Enum
from pyshgp.push.instruction import Instruction
from pyshgp.push.program import Program
from pyshgp.push.state import PushState
from pyshgp.push.ins... |
the-stack_0_16228 | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from os import path
from config import INPUT_PATH, OUTPUT_PATH
def draw_response_times_plot(input_file, output_file):
sns.set_style("ticks", {"'xtick.major.size'": "0"})
response_times = pd.read_csv(path.join(INPUT_PATH, input_file), ... |
the-stack_0_16230 | import subprocess, json, re
command = "Get-Service -Name Audiosrv -ComputerName asl-ad04"
p = subprocess.Popen(
[
"powershell.exe",
"({}) | ConvertTo-Json -Compress".format(command)
],
stdout=subprocess.PIPE
)
result = (p.communicate()[0]).decode('cp1252')
if re.sea... |
the-stack_0_16231 | #!/usr/bin/env python -tt
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
#PHENOS
"""
"""
def check_directories():
"""
Ensure all expected directories (and set-up files) are present and correct.
Create any paths that are missing.
"""
expected_directories=["DAT files... |
the-stack_0_16232 | from setuptools import setup
import os
import glob
package_name = 'rastreator_simulation'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ... |
the-stack_0_16233 | #!/usr/bin/env python3
"""The Graph package contains the Graph class
that carries the results from scrapping/exploring nlp models etc...
The class inherit from :obj:`rdflib.Graph`.
"""
import logging
from requests.utils import quote
import rdflib
import xlsxwriter
from rdflib.plugins.sparql.parser import parseQuery
... |
the-stack_0_16234 | m = int(input())
scores = list(map(int,input().split()))
scores = sorted(set(scores),reverse = True)
m=len(scores)
n = int(input())
alice = list(map(int,input().split()))
for score in alice:
if score >= scores[0] :
print (1)
elif score == scores[-1] :
print (m)
elif score < scores[-1] :... |
the-stack_0_16237 | import multiprocessing
import os
import subprocess
import traceback
from itertools import product
import numpy as np
import seaborn
import torch
from matplotlib import pyplot as plt
seaborn.set()
SMALL_SIZE = 18
MEDIUM_SIZE = 22
BIGGER_SIZE = 26
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('a... |
the-stack_0_16240 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 14:19:36 2021
@author: bressler
"""
from PICOcode.REFPROP.SeitzModel import SeitzModel
import numpy as np
import matplotlib.pyplot as plt
from baxterelectronrecoilmodel import BTM
with open('/coupp/data/home/coupp/users/bressler/output/argonspi... |
the-stack_0_16241 | '''
Created on Apr 4, 2022
@author: mballance
'''
import dataclasses
from rctgen.impl.ctor import Ctor
from rctgen.impl.type_info import TypeInfo
from rctgen.impl.type_kind_e import TypeKindE
from rctgen.impl.exec_group import ExecGroup
from rctgen.impl.rand_t import RandT
from rctgen.impl.scalar_t import ScalarT
from... |
the-stack_0_16246 | import unittest
from cybercaptain.processing.filter import processing_filter
class ProcessingFilterEQTest(unittest.TestCase):
"""
Test the filters for EQ
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
arguments = {'src': '.',
'filterby':... |
the-stack_0_16249 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab... |
the-stack_0_16253 | import torch
from .misc import _convert_to_tensor, _dot_product
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: functio... |
the-stack_0_16254 | import codecs
from typing import Any
from flask import Blueprint, jsonify
from werkzeug.exceptions import abort
from shrunk.client import ShrunkClient
from shrunk.client.exceptions import NoSuchObjectException
from shrunk.util.decorators import require_login
__all__ = ['bp']
bp = Blueprint('request', __name__, url_... |
the-stack_0_16255 | import numpy as np
from scipy.interpolate.interpolate import interp1d
import matplotlib.pyplot as plt
import os
path_104 = os.path.abspath('../../../Downloads/realTime-master-AlAl-data_trial5/AlAl/data_trial5/104S/')
files_104_unsorted = os.listdir(path_104)
order = [int(str.split(ff, "_")[1]) for ff in files... |
the-stack_0_16257 | #########################
# Imports
#########################
from bs4 import BeautifulSoup
from fuzzywuzzy import fuzz
import bs4, requests, json
from secrets import *
#########################
# Headers
#########################
headers = {
'Authorization': 'Bearer ' + ACCESS_TOKEN,
}
########################... |
the-stack_0_16259 | import numpy as np
from REESMath.quaternion import to_matrix
from math import atan2, asin, pi
class EulerXYZ:
def __init__(self, alpha, beta, gamma):
self.alpha = alpha # Rotation angle around x-axis in radians
self.beta = beta # Rotation angle around y-axis in radians
self.g... |
the-stack_0_16261 | from pathlib import Path
import pytest
from hookman.hookman_generator import HookManGenerator
def test_hook_man_generator(datadir, file_regression):
# Pass a folder
with pytest.raises(FileNotFoundError, match=f"File not found: *"):
HookManGenerator(hook_spec_file_path=datadir)
# Pass a invalid ... |
the-stack_0_16263 | #!/usr/bin/env python3
''' decrypts the first passage'''
from Vigenere import Vigenere
keyword_1 = 'kryptos'
keyword_2 = 'abscissa'
with open('text_b.txt', 'r') as f:
text = f.read().replace('\n', '').lower()
text = text[:text.index('?')]
# cut into 14x24 matrix
matrix = []
for i in range(14):
matrix.append(... |
the-stack_0_16264 | #!/usr/bin/env python
#
# Electrum - lightweight STRAKS client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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 ... |
the-stack_0_16267 | # coding: utf-8
# Copyright 2017-2019 The FIAAS 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 ... |
the-stack_0_16268 | import os
from collections import OrderedDict
from conans.client import tools
from conans.client.build.compiler_flags import architecture_flag, parallel_compiler_cl_flag
from conans.client.build.cppstd_flags import cppstd_from_settings, cppstd_flag_new as cppstd_flag
from conans.client.tools import cross_building
from... |
the-stack_0_16269 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-keras.py
# Author: Yuxin Wu
import tensorflow as tf
from tensorflow import keras
from tensorpack import *
from tensorpack.contrib.keras import KerasPhaseCallback
from tensorpack.dataflow import dataset
from tensorpack.utils.argtools import memoized
KL = ker... |
the-stack_0_16270 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, traceback
import simplejson
import openpyxl
from optparse import OptionParser
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.... |
the-stack_0_16271 | """Module providing custom logging formatters and colorization for ANSI
compatible terminals."""
import inspect
import logging
import os
import random
import threading
from logging import LogRecord
from typing import Any, List
DEFAULT_LOG_FILE = os.path.join(os.sep, 'tmp', 'dftimewolf.log')
MAX_BYTES = 5 * 1024 * 1024... |
the-stack_0_16272 | # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
the-stack_0_16274 | """
Copyright (C) 2020 Piek Solutions LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
... |
the-stack_0_16275 | # -*- coding: utf-8 -*-
def main():
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
n = int(input())
graph = [[] for _ in range(n)]
ab = list()
dp = [0] * n
for _ in range(n - 1):
ai, bi = map(int, input().split())
ai -= 1
bi -= 1
... |
the-stack_0_16276 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth', # noqa
backbone=dict(
type='VisionTransformer',
img_size=(51... |
the-stack_0_16277 | #!/usr/bin/env python3
import argparse
import logging
import mariadb
import yaml
import sys
# Setup logging
# Create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Setup console logging
logging_console_handler = logging.StreamHandler()
logging_formatter = logging.Formatter("%(asctime)s [%(... |
the-stack_0_16280 | import uuid
import arrow
def is_uuid(data):
"""Check is data is a valid uuid. If data is a list,
checks if all elements of the list are valid uuids"""
temp = [data] if not isinstance(data, list) else data
for i in temp:
try:
uuid.UUID(str(i), version=4)
except ValueError:
... |
the-stack_0_16282 | # -*- coding:utf-8 -*-
from __future__ import print_function
from setuptools import setup, find_packages
from glob import glob
import pyprobar
with open(glob('requirements.*')[0], encoding='utf-8') as f:
all_reqs = f.read().split('\n')
install_requires = [x.strip() for x in all_reqs if 'git+' not in x]
with open... |
the-stack_0_16284 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_16285 | # Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, visit
# https://nvlabs.github.io/stylegan2/license.html
"""TensorFlow custom ops builder.
"""
import os
import re
import uuid
import hashlib
import ... |
the-stack_0_16286 | from __future__ import (
absolute_import,
unicode_literals,
)
import abc
from typing import (
Dict,
FrozenSet,
Type,
)
import six
__all__ = (
'Serializer',
)
class _SerializerMeta(abc.ABCMeta):
_mime_type_to_serializer_map = {} # type: Dict[six.text_type, Type[Serializer]]
_all_su... |
the-stack_0_16287 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_0_16288 | """Fast thresholded subspace-constrained mean shift for geospatial data.
Introduction:
-------------
DREDGE, short for 'density ridge estimation describing geospatial evidence',
arguably an unnecessarily forced acronym, is a tool to find density ridges.
Based on the subspace-constrained mean shift algorithm [1], it ap... |
the-stack_0_16290 | import os
from io import BytesIO
import mimetypes
from django.db.models.fields.files import ImageField
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import signals
from PIL import Image
# todo: Add 'delete_with_model' option that will delete thumbnail and image when model is d... |
the-stack_0_16292 | class ContentFilteringRules(object):
def __init__(self, session):
super(ContentFilteringRules, self).__init__()
self._session = session
def getNetworkContentFiltering(self, networkId: str):
"""
**Return the content filtering settings for an MX network**
https://api.m... |
the-stack_0_16293 | import os
from pikka_bird_collector.collectors.mysql import Mysql
from pikka_bird_collector.collectors.base_port_command import BasePortCommand
class TestMysql:
@staticmethod
def fixture_path(filename):
return os.path.join(os.path.dirname(__file__), '../fixtures', filename)
@staticmetho... |
the-stack_0_16294 | # Copyright 2013-2015 DataStax, 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 agreed to in writi... |
the-stack_0_16297 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import datetime
import logging
from flexget import plugin
from flexget.config_schema import one_or_more
from flexget.event import event
from flexget.plugin import PluginWa... |
the-stack_0_16298 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_16302 | from os import path
from setuptools import setup, find_packages
import sys
import versioneer
# NOTE: This file must remain Python 2 compatible for the foreseeable future,
# to ensure that we error out properly for people with outdated setuptools
# and/or pip.
if sys.version_info < (3, 6):
error = """
niio does no... |
the-stack_0_16304 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import boto3
from redis.sentinel import Sentinel
ALERT_EMAILS = ['cejay@126.com']
REDIS_SENTINEL_LIST = [("47.94.197.140",6379)]
#[("192.168.0.62", 26379), ("192.168.0.63", 26379), ("192.168.0.64", 26379)]
def send_email(to_address, subject, content):
ses = b... |
the-stack_0_16305 | from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.urls import include, path
from django.views.generic import TemplateView
urlpatterns = [
path(
"",
login_require... |
the-stack_0_16306 | # -*- coding: utf-8 -*-
from .socketservice import get_instance
from .alarm_service import AlarmService
import binascii
import time
from app.models.device import Device as DeviceModel
from app.models.line import Line
from app.models.monitor import Monitor
from datetime import datetime
from app.libs.utils import dynamic... |
the-stack_0_16307 | """ module to methods to main """
import sys
import logging
from .migrate_isis import migrate_isis_parser
from .migrate_articlemeta import migrate_articlemeta_parser
from .tools import tools_parser
logger = logging.getLogger(__name__)
def main_migrate_articlemeta():
""" method main to script setup.py """
... |
the-stack_0_16309 | from modelvshuman import Plot, Evaluate
from modelvshuman import constants as c
from plotting_definition import plotting_definition_template
def run_evaluation():
models = ["resnet50", "bagnet33", "simclr_resnet50x1"]
datasets = c.DEFAULT_DATASETS # or e.g. ["cue-conflict", "uniform-noise"]
params = {"bat... |
the-stack_0_16311 | """
=====================================================================
Compute Power Spectral Density of inverse solution from single epochs
=====================================================================
Compute PSD of dSPM inverse solution on single trial epochs restricted
to a brain label. The PSD is compu... |
the-stack_0_16312 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: game.py
# -------------------
# Divine Oasis
# Text Based RPG Game
# By wsngamerz
# -------------------
import divineoasis
import logging
import logging.config
import os
import platform
import pyglet
import sys
from divineoasis.assets import Assets, Directo... |
the-stack_0_16313 | """
Programmer : EOF
File : config.py
Date : 2016.01.06
E-mail : jasonleaster@163.com
License : MIT License
Description :
This is a configure file for this project.
"""
DEBUG_MODEL = True
USING_CASCADE = False
# training set directory for face and non-face images
TRAINING_FAC... |
the-stack_0_16316 | import os
import torch
import torch.nn as nn
from torch.autograd import Variable
import dataset84
import model
from unet import UNet,CNNEncoder
def main():
# init conv net
print("init net")
unet = UNet(3,1)
if os.path.exists("./unet.pkl"):
unet.load_state_dict(torch.load("./unet.pkl"))
print("load unet")
u... |
the-stack_0_16317 | from django.template.response import TemplateResponse
from rest_framework.settings import api_settings
from django.core.paginator import Paginator
from rest_framework import viewsets, permissions
from . import models
from . import serializers
class ProductViewset(viewsets.ModelViewSet):
permission_classes = [perm... |
the-stack_0_16319 | """
MNIST example with training and validation monitoring using TensorboardX and Tensorboard.
Requirements:
TensorboardX (https://github.com/lanpa/tensorboard-pytorch): `pip install tensorboardX`
Tensorboard: `pip install tensorflow` (or just install tensorboard without the rest of tensorflow)
Usage:
Sta... |
the-stack_0_16320 | import csv
import email.message
import json
import logging
import pathlib
import re
import zipfile
from typing import (
IO,
TYPE_CHECKING,
Collection,
Container,
Iterable,
Iterator,
List,
Optional,
Tuple,
Union,
)
from pip._vendor.packaging.requirements import Requirement
from p... |
the-stack_0_16321 | # -*- coding: utf-8 -*-
# @Author : ydf
# @Time : 2021/4/3 0008 13:32
from function_scheduling_distributed_framework.publishers.base_publisher import AbstractPublisher
from function_scheduling_distributed_framework.utils import RedisMixin
class RedisStreamPublisher(AbstractPublisher, RedisMixin):
"""
redi... |
the-stack_0_16324 | from abstract.instruccion import *
from tools.console_text import *
from tools.tabla_tipos import *
from instruccion.create_column import *
from storage import jsonMode as funciones
from error.errores import *
from tools.tabla_simbolos import *
class create_table(instruccion):
def __init__(self, id_table, columnas... |
the-stack_0_16328 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2019, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
the-stack_0_16329 | import urllib.request
from bs4 import BeautifulSoup
from assets import data
from assets import functions
from models.Fish import Fish
page = functions.scrape_file("fish.html")
table = page.find('table', {"class": "wikitable"})
tableRows = table.find_all('tr')
rowCount = 0
for row in tableRows:
rowCount = rowCoun... |
the-stack_0_16331 | r"""
Orthogonal arrays (OA)
This module gathers some construction related to orthogonal arrays (or
transversal designs). One can build an `OA(k,n)` (or check that it can be built)
from the Sage console with ``designs.orthogonal_arrays.build``::
sage: OA = designs.orthogonal_arrays.build(4,8)
See also the modules... |
the-stack_0_16333 | import numpy as np
import os
import json
import time
from .utils import log
import pdb
def get_relationship_feat(committee, pairs):
start = time.time()
votefeat = []
for i,cmt in enumerate(committee):
log("\t\tprocessing: {}/{}".format(i, len(committee)))
knn = cmt[0]
k = knn.shape... |
the-stack_0_16335 | from logging import getLogger, StreamHandler, DEBUG, INFO
from sys import stdout
def setup_logging(debug=False):
logger = getLogger('raptiformica')
logger.setLevel(DEBUG if debug else INFO)
console_handler = StreamHandler(stdout)
logger.addHandler(console_handler)
return logger
|
the-stack_0_16338 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from PIL import Image
import numpy as np
import time
import os
from fully_conv_nets import VGGNet, F... |
the-stack_0_16339 | # -*- coding: utf-8 -*-
"""
Created on Sat May 18 12:31:06 2019
@author: MAGESHWARAN
"""
import cv2
import numpy as np
from image_processing import one_over_other
def detect_edges(image, kernel=np.ones((5, 5), dtype=np.uint8)):
""" Perform Edge detection on the image using Morphology Gradient
Inputs:
... |
the-stack_0_16340 | from octopus.core import app
from octopus.modules.jper import models
from octopus.lib import http, dates
import json
class JPERException(Exception):
pass
class JPERConnectionException(JPERException):
pass
class JPERAuthException(JPERException):
pass
class ValidationException(JPERException):
pass
cl... |
the-stack_0_16342 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import os
import unittest
import frappe
from frappe.utils import cint
from frappe.model.naming import revert_series_if_last, make_autoname, parse_naming_series
class TestDocume... |
the-stack_0_16343 | """
Common Python utilities for interacting with the dashboard infra.
"""
import argparse
import datetime
import json
import logging
import os
import sys
def print_log(msg, dec_char='*'):
padding = max(list(map(len, str(msg).split('\n'))))
decorate = dec_char * (padding + 4)
print(f'{decorate}\n{msg}\n{de... |
the-stack_0_16344 | from inspect import signature
from collections import namedtuple
import time
import numpy as np
import pandas as pd
from functools import singledispatch
#####################
# utils
#####################
class Timer():
def __init__(self):
self.times = [time.time()]
self.total_time = 0.0
def ... |
the-stack_0_16346 | # from framework.utils.analyzer_pydantic import ModelFieldEx
import inspect
from dataclasses import field
from typing import Any, Dict, List, Optional, Type, TypedDict
from fastapi import Query
from pydantic import BaseConfig, BaseModel, Field
from pydantic.fields import FieldInfo, ModelField, NoArgAnyCallable, Union,... |
the-stack_0_16348 | import copy
import json
import re
import unittest
from django.contrib import admin
from django.contrib.auth import get_permission_codename
from django.contrib.auth.models import Permission
from django.template import RequestContext
from django.utils.encoding import force_str
from django.utils.html import escape
from d... |
the-stack_0_16350 | from typing import List
import inspect
from functools import partial, wraps
from json import JSONEncoder
class JsonSerializable(JSONEncoder):
_klasses: List[type] = []
def __init__(self, kls):
super().__init__()
self.__kls = kls
self._klasses.append(kls)
def get_json_members(se... |
the-stack_0_16351 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somap = 0
maior = 0
for l in range(0, 3):
for a in range(0, 3):
matriz[l][a] = int(input(f'Digite um valor para [{l}, {a}]: '))
print('-='*30)
for r in range(0, 3):
for i in range(0, 3):
print(f'[{matriz[r][i]:^5}]', end='')
'''
if matri... |
the-stack_0_16353 | class Heap:
def __init__(self, A:list(int)=[]) -> None:
"""
A heap represents a nearly-complete binary tree that maintains a heap property between parents and children.
A heap represents a nearly-complete binary tree that maintains a heap property between parents and children.
... |
the-stack_0_16354 | """This is a test to test the paraview proxy manager API."""
from paraview import servermanager
import sys
servermanager.Connect()
sources = servermanager.sources.__dict__
for source in sources:
try:
sys.stderr.write('Creating %s...'%(source))
s = sources[source]()
s.UpdateVTKObjects()
sys.stderr.wr... |
the-stack_0_16356 | #!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = \
'''
This program is a basic python conversion of Mick Watson's Ideel.
It reads one or more input FASTA files and for each file it will use
prodigal for rapid annotation, then run diamond blast, then compare the
query length to hit length.
It... |
the-stack_0_16360 | import sys
import toml
import nltk
import logging
from typing import List
from pathlib import Path
logging.basicConfig(
format="%(asctime)s (PID %(process)d) [%(levelname)s] %(filename)s:%(lineno)d %(message)s",
level=logging.INFO,
handlers=[logging.StreamHandler(sys.stdout)],
)
BASE_DIR = Path(__file__... |
the-stack_0_16362 | # vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
from scipy.optimize import linear_sum_assignment
from . import kalman_filter
INFTY_COST = 1e+5
def min_cost_matching(
distance_metric, max_distance, tracks, detections, track_indices=None,
detection_indices=None):
... |
the-stack_0_16363 | import sys
import argparse
from svtools.external_cmd import ExternalCmd
class BedpeSort(ExternalCmd):
def __init__(self):
super(BedpeSort, self).__init__('bedpesort', 'bin/bedpesort')
def description():
return 'sort a BEDPE file'
def epilog():
return 'To read in stdin and output to a file, use /d... |
the-stack_0_16364 | import asyncio
from weakref import ref
from decimal import Decimal
import re
import threading
import traceback, sys
from typing import TYPE_CHECKING, List
from kivy.app import App
from kivy.cache import Cache
from kivy.clock import Clock
from kivy.compat import string_types
from kivy.properties import (ObjectProperty,... |
the-stack_0_16365 | import os
import re
regex = list()
dir_path = os.path.dirname(os.path.realpath(__file__))
f = open(dir_path + '/../regex.txt')
lines = f.readlines()
for line in lines:
if (len(line) > 10):
# Remove the \n at the end
regex.append(re.compile('^' + line[1:-2] + '$'))
class Pincode:
@staticmethod... |
the-stack_0_16367 | import custom_paths
from pathlib import Path
import utils
import shutil
from typing import *
# This file contains some utility functions to modify/rename/remove saved results.
# It can be used for example if the names of some experiment results should be changed.
def rename_alg(exp_name: str, old_name: str, new_name... |
the-stack_0_16368 | # 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_0_16370 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_Fl... |
the-stack_0_16375 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from dotenv import load_dotenv
import os
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
# with app.app_context():
basedir = os.path.abspath... |
the-stack_0_16379 | # Imports
from os import path
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def _weights_init(m):
classname = m.__class__.__name__
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weigh... |
the-stack_0_16380 | # 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_0_16381 | from h2o.estimators import H2ODeepLearningEstimator, H2OGradientBoostingEstimator, H2OGeneralizedLinearEstimator, \
H2ONaiveBayesEstimator, H2ORandomForestEstimator
from sklearn.base import BaseEstimator
import h2o
import pandas as pd
class H2ODecorator(BaseEstimator):
def __init__(self, est_type, est_params,... |
the-stack_0_16382 | #! /usr/bin/env python
# example patch call:
# ./extract_patches.py -subset 202 -slices 64 -dim 64
#### ---- Imports & Dependencies ---- ####
import sys
import os
import argparse
from configparser import ConfigParser
import pathlib
from glob import glob
from random import shuffle
import SimpleITK as sitk # pip instal... |
the-stack_0_16387 | from argparse import ArgumentParser
from fmovies_api import Fmovies, FmoviesConfig
import os
import re
class Application():
def __init__(self):
self.config_data = {}
def setup_parser():
parser = ArgumentParser()
parser.add_argument("-u", "--base-url",
hel... |
the-stack_0_16389 | """
A backend to export DXF using a custom DXF renderer.
This allows saving of DXF figures.
Use as a matplotlib external backend:
import matplotlib
matplotlib.use('module://mpldxf.backend_dxf')
or register:
matplotlib.backend_bases.register_backend('dxf', FigureCanvasDxf)
Based on matplotlib.backends.backen... |
the-stack_0_16391 | """File for Azure Event Hub models."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from azure.eventhub.aio import EventHubProducerClient, EventHubSharedKeyCredential
from .const import ADDITIONAL_ARGS, CONF_EVENT_HUB_CON_STRING
_LOGGER = logging.getLogger(__name__)
@datacla... |
the-stack_0_16393 | # coding=utf-8
# Copyright 2018 David Mack
#
# 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 t... |
the-stack_0_16397 | from __future__ import print_function
"""
Before running this script there is a
dependency for reading WMO BUFR:
pip install pybufrkit
This library has a way to work within the python script
but as of now it works using a command line interface.
It is important to download the files from the ftp using binary mode!
... |
the-stack_0_16398 | """ Default (fixed) hyperparameter values used in Neural network model """
from ....constants import BINARY, MULTICLASS, REGRESSION
def get_fixed_params():
""" Parameters that currently cannot be searched during HPO """
fixed_params = {
'num_epochs': 500, # maximum number of epochs for training NN
... |
the-stack_0_16399 | """
The Ravel backend PostgreSQL database
"""
import psycopg2
from ravel.log import logger
from ravel.util import resource_file
ISOLEVEL = psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT
BASE_SQL = resource_file("ravel/sql/base.sql")
FLOW_SQL = resource_file("ravel/sql/flows.sql")
NOFLOW_SQL = resource_file("ravel/s... |
the-stack_0_16401 | import numpy as np
from .customKF import CustomKF
class CustomRTS():
def __init__(self, z, del_t):
self.z = z
self.del_t = del_t
def run(self, initial_mean, initial_variance, Q, sigma_square):
# Forward batch filter
kf = CustomKF(Q, sigma_square)
prior_means, prior_vari... |
the-stack_0_16402 | from setuptools import find_packages, setup
with open("README.md", "r") as f:
README = f.read()
setup(
name='yappa',
version='0.4.19',
url='https://github.com/turokg/yappa',
description='Easy serverless deploy of python web applications',
long_description_content_type="text/markdown",
long... |
the-stack_0_16403 | """Support for Xiaomi Mi Air Quality Monitor (PM2.5)."""
import logging
from miio import AirQualityMonitor, DeviceException
import voluptuous as vol
from homeassistant.components.air_quality import PLATFORM_SCHEMA, AirQualityEntity
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.