text stringlengths 2 999k |
|---|
"""Reports views"""
# Django
from django.views.generic import TemplateView
# Shortcuts
from django.shortcuts import render
from django.shortcuts import redirect, reverse, get_object_or_404
from django.contrib.auth import authenticate
from django.http import (
HttpResponse,
HttpResponseNotFound,
HttpRespons... |
import unittest
import random
import subprocess
import signal
import sys
import os
import thread_affinity
# Test results may vary if executed in different systems
# with different amount of CPUUs
def get_random_mask():
"""Return a random, valid affinity mask
Which is a subset of {0, 1, ..., 2 ** num_procs - 1}
""... |
# sqlalchemy/log.py
# Copyright (C) 2006-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
# Includes alterations by Vinay Sajip vinay_sajip@yahoo.co.uk
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Logging control ... |
"""
Stream IO interposition
"""
import io
class InterposedStringIO(io.StringIO):
def __init__(self, newline="\n", line_buffering = False, onflush=None):
super().__init__(newline=newline)
self._line_buffering = line_buffering
self._onflush = onflush
def flush(self):
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- 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
#... |
"""
========================================================
06. Remove epochs based on peak-to-peak (PTP) amplitudes
========================================================
Epochs containing peak-to-peak above the thresholds defined
in the 'reject' parameter are removed from the data.
This step will drop epochs con... |
import datetime
import hashlib
import json
import numpy as np
import pandas as pd
import tifffile
def timestamp():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
class MicroManagerTIFF:
def __init__(self, src_filepath, verbose=True):
'''
'''
self.verbose = verbose
... |
#!/usr/bin/env python3
import tkinter as tk
import binascii, pyaes, sys, base64, os.path, os
from tkinter import *
from pathlib import Path
from tkinter.font import Font
from tkinter.filedialog import askopenfilename
import secrets
import string
def main():
global entry3
input2 = entry3.get()
# Open file
... |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... |
from . import models
import datetime
from discord import utils, TextChannel
def generate_id():
return utils.time_snowflake(datetime.datetime.now())
async def add_permanent_role(user_id: int, role_id: int):
await add_dbmember_if_not_exist(user_id)
if not await models.PermanentRole.query.where((models.Per... |
import torch
import torch.nn as nn
from .base import BaseDetector
from .test_mixins import RPNTestMixin, BBoxTestMixin, MaskTestMixin
from .. import builder
from ..registry import DETECTORS
from mmdet.core import bbox2roi, bbox2result, build_assigner, build_sampler
@DETECTORS.register_module
class TwoStageDetector(B... |
from __future__ import division
import discord, math, operator
from discord.ext import commands
from pyparsing import (Literal,CaselessLiteral,Word,Combine,Group,Optional,
ZeroOrMore,Forward,nums,alphas,oneOf)
__author__='Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20... |
import onfido
from onfido.regions import Region
import io
api = onfido.Api("<AN_API_TOKEN>", region=Region.EU)
fake_uuid = "58a9c6d2-8661-4dbd-96dc-b9b9d344a7ce"
def test_upload_photo(requests_mock):
mock_upload = requests_mock.post("https://api.eu.onfido.com/v3.2/live_photos/", json=[])
sample_file = open... |
#import OpenStack connection class from the SDK
from openstack import connection
# Create a connection object by calling the constructor and pass the security information
conn = connection.Connection(auth_url="http://192.168.0.106/identity",
project_name="demo",
username="admin",
password="manoj",
user_domain_id="defa... |
# -*- coding: utf-8 -*-
"""Top-level package for {{ cookiecutter.project_name }}"""
__version__ = '0.0.1'
|
np.tanh(x) |
import asyncio
import aioredis
async def main():
sentinel = await aioredis.create_sentinel(
["redis://localhost:26379", "redis://sentinel2:26379"]
)
redis = sentinel.master_for("mymaster")
ok = await redis.set("key", "value")
assert ok
val = await redis.get("key", encoding="utf-8")
... |
import logging
from .DatabaseBase import DatabaseBase
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
class ImageResource(DatabaseBase):
def __init__(self):
super().__init__()
def get_product_images_by_id(self, id):
search_image_query = """Select * From images w... |
"""weather_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
"""Utility for currying functions."""
from functools import wraps
from inspect import signature, isbuiltin, isclass
def curry(func, args=None, kwargs=None, n=None, use_defaults=False):
if use_defaults:
return CurriedDefault(func, args, kwargs, n)
return Curried(func, args, kwargs, n)
class Curried... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ... |
# -*- coding: utf-8 -*-
'''
flask.ext.login
---------------
This module provides user session management for Flask. It lets you log
your users in and out in a database-independent manner.
:copyright: (c) 2011 by Matthew Frazier.
:license: MIT/X11, see LICENSE for more details.
'''
__version_i... |
#!/usr/bin/env python
##
# Python script to tidy mediasession.bs
#
# adapted from: https://github.com/w3c/webvtt/blob/41cac9c211f9c581de466bb9b8b5dd11a160ffad/format.py
##
import re
import sys
# http://stackoverflow.com/q/1732348
pattern = re.compile(r'<(\w+).*?>|</(\w+)>|<!--(.*?)-->', re.DOTALL)
INDENT = ' '
COL... |
# We want 1/2==0.5
from __future__ import division
"""Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import math
class lykke (Exchange):
def describe(self):
return self.deep_extend(supe... |
from unittest import TestCase, skip
import copy
import numpy as np
from giant import rotations as at
from giant.ray_tracer import kdtree, shapes, rays
class TestKDTree(TestCase):
def setUp(self):
self.max_depth = 4
tri1 = np.array([[-5, -4, -4.5],
[0, 0, 1],
... |
#!/usr/bin/python3
from subprocess import call;
from sys import argv
from os import path
outPath = argv[1] if(len(argv)>1) else "/etc/dipicar/creds"
duration = 365
rsaLength = 4096
#Generate ssl keys
call([
"openssl",
"req",
"-x509",
"-newkey",
"rsa:"+str(rsaLength),
"-keyout", path.join... |
import requests
import os
ROOT_URL = 'http://datamall2.mytransport.sg/ltaodataservice'
def get_taxi_availability_request():
result = None
try:
url = '{}/Taxi-Availability'.format(ROOT_URL)
headers = {
'AccountKey': os.getenv('ACCOUNT_KEY'),
'Accept': 'application/json... |
# The MIT License (MIT)
# Copyright (c) 2018 by EUMETSAT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify,... |
import re
from collections import defaultdict
from datetime import datetime
from elasticsearch_dsl import Keyword, Text
from protean import BaseAggregate, BaseValueObject
from protean.core.model import BaseModel
from protean.fields import DateTime, Integer, String
from protean.fields import Text as ProteanText
from ... |
# https://leetcode.com/problems/design-twitter/
#
# algorithms
# Medium (27.98%)
# Total Accepted: 37,655
# Total Submissions: 134,594
from collections import defaultdict
from bisect import insort
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""... |
from const import result
import random
C, D = True, False
def opponent(r):
if r == result.COOP or r == result.DEFECT:
return True
return False
# tit for tat
class Tft:
def __init__(self) -> None:
self.score = 0
self.last_reaction = C
def run(self):
return self.last_... |
import os
import pytest
import sys
import numpy as np
import shutil
import subprocess
try:
import pymake
except:
msg = "Error. Pymake package is not available.\n"
msg += "Try installing using the following command:\n"
msg += " pip install https://github.com/modflowpy/pymake/zipball/master"
raise Ex... |
import numpy as np
# Read scec input file
fid = open("tpv29_tpv30_geometry_25m_data.txt")
line = fid.readline()
line = fid.readline()
header = [float(a) for a in line.split()]
nx, ny, lx, ly = header
roughness = np.loadtxt(fid)
roughness = roughness[:, 4]
fid.close()
# create x and y vectors
x = np.linspace(-lx / 2, ... |
import pytest
from ebonite.client import Ebonite
from tests.client.conftest import create_client_hooks
@pytest.fixture
def inmemory_ebnt():
ebnt = Ebonite.inmemory()
yield ebnt
pytest_runtest_protocol, pytest_collect_file = create_client_hooks(inmemory_ebnt, 'inmemory')
|
"""
example1.py
"A simple example how to use the CubeSat-Power-Estimation tool."
@author: Johan Monster (https://github.com/Hans-Bananendans/)
"""
# Import packages
import numpy as np
import pandas as pd
from mission import Mission
# Defining the config
config = {
"years_passed" : 0, # How many [years] the sat... |
from __future__ import annotations
from coredis.response.callbacks import (
DictCallback,
ResponseCallback,
SimpleStringCallback,
)
from coredis.response.utils import flat_pairs_to_dict
from coredis.typing import Any, AnyStr, Mapping, Tuple, Union
class ACLLogCallback(ResponseCallback):
def transform... |
#!/usr/bin/env python
#
# Public Domain 2014-2017 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compil... |
from tensornetwork.network_components import Node, CopyNode, Edge
_COMPONENTS = {
"Node": Node,
"CopyNode": CopyNode,
"Edge": Edge,
}
def get_component(name):
if name not in _COMPONENTS:
raise ValueError("Component {} does not exist".format(name))
return _COMPONENTS[name]
|
from .util import BitFormat
from . import packet
__all__ = ('ImageF0', 'ImageF1', 'ImageF2')
class ImageMessage:
def __repr__(self):
return '<Image Segment>'
class ImageF0(packet.Packet):
"""Image data
.. py:attribute:: segment_length
.. py:attribute:: iph
.. py:attribute:: sum
... |
from SDWLE.cards.base import HeroCard
from SDWLE.constants import CHARACTER_CLASS, MINION_TYPE
from SDWLE.powers import MagePower, DruidPower, HunterPower, PaladinPower, PriestPower, RoguePower,\
ShamanPower, WarlockPower, WarriorPower, JaraxxusPower, DieInsect
class Malfurion(HeroCard):
def __init__(self):
... |
# Cooccurrence matrix construction tools
# for fitting the GloVe model.
import numpy as np
try:
# Python 2 compat
import cPickle as pickle
except ImportError:
import pickle
from .corpus_cython import construct_cooccurrence_matrix
class Corpus(object):
"""
Class for constructing a cooccurrence mat... |
r"""Compute action detection performance for the AVA dataset.
Please send any questions about this code to the Google Group ava-dataset-users:
https://groups.google.com/forum/#!forum/ava-dataset-users
Example usage:
python -O get_ava_performance.py \
-l ava/ava_action_list_v2.1_for_activitynet_2018.pbtxt.txt \
-g... |
from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
|
import logging
import asyncio
from asyncio import CancelledError
from aiohttp import ClientSession, WSMsgType, ClientTimeout, WSServerHandshakeError
import json
import datetime
import traceback
import typing
from .const import (
LOGIN_URL,
DEX_URL,
Guid
)
from .space import NoonSpace
from .line import NoonL... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Modified by BaseDetection, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in cvpod... |
# Generated by Django 3.2.3 on 2021-05-17 16:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0072_alter_product_region'),
]
operations = [
migrations.RenameField(
model_name='product',
old_name='name_lt',
... |
__author__ = 'Alexandre Calil Martins Fonseca, github: xandao6'
# region TUTORIAL
'''
Go to region 'FOR SCRIPTING' and use the methods in your script!
EXAMPLE OF USAGE:
from wplay.pyppeteerUtils import pyppeteerConfig as pypConfig
from wplay.pyppeteerUtils import pyppeteerSearch as pypSearch
async def my_script(tar... |
def beg(arr):
a = []
b = []
c = []
for i in arr:
if i == 0:
a.append(i)
if i == 1:
b.append(i)
if i == 2:
c.append(i)
return a+b+c
a = []
b = [0,0,0]
c = [1,2,1,1,2,1,2]
d = [0,2,1,0,1,0,2,2,2,1,0,2,1,0,1,2,0]
print(beg(a))
print(beg(b)... |
from django.apps import AppConfig
class MasterAppConfig(AppConfig):
name = 'msa.contrib.master'
verbose_name = 'Master Service'
|
import importlib
import json
import os
import shutil
import subprocess
from pathlib import Path
from shutil import which
from typing import List, Optional, Tuple
from setuptools import find_packages
from typer import Argument, Option, Typer
from .paths import (
GLOBAL_APP_DIR,
GLOBAL_EXTENSIONS_DIR,
GLOBA... |
from socorepo.locators import github_tags, nexus3, pypi
LOCATOR_PARSERS = {
"github_tags": github_tags.parse_locator,
"nexus3": nexus3.parse_locator,
"pypi": pypi.parse_locator
}
|
from flask import Flask, render_template, request
import json
import requests
app = Flask(__name__)
@app.route('/')
def stop_words():
URL_prefix = 'https://api.github.com/search/code?q='
URL_suffix = '+repo:spotify/mkdocs-monorepo-plugin/docs'
reportfile = open('./templates/stopWordsSearch.html', 'w')
... |
from django.apps import apps
from django.db import DEFAULT_DB_ALIAS, router
from django.db.models import signals
from django.utils.encoding import smart_text
from django.utils import six
from django.utils.six.moves import input
def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS,... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Logistic Regression Gradient Descent
"""
import numpy as np
class LogisticRegressionGD(object):
"""Logistic Regression Classifier using gradient descent.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter :... |
# -*- 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
#... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Tiling(_BaseTraceHierarchyType):
# flip
# ----
@property
def flip(self):
"""
Determines if the positions obtained from solver are flipped on
each axis.
Th... |
from django.conf.urls import url,include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('instagram.urls')),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^logout/$', views.logout, {"next... |
import chainer
from chainer import training
from chainer.training import extensions
from chainer.datasets import TupleDataset
from chainer import Chain
from chainer import links as L
from chainer import functions as F
from chainer import reporter
from chainer import cuda
import numpy as np
def dot(a, b):
""" Sim... |
import json
from pathlib import Path
from typing import Optional
import typer
from . import utils
from .utils import example
from .utils.iohelper import AltTemporaryDirectory
@example()
def check(
project_dir: Path = Path("."), checkout: Optional[str] = None, strict: bool = True
) -> bool:
"""Checks to see ... |
#!/usr/bin/env python2
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Copyright (c) 2014-2020 The Skicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test merkleblock fetch/validation
#
from test_... |
"""Test zha switch."""
from unittest.mock import call, patch
import pytest
import zigpy.zcl.clusters.general as general
import zigpy.zcl.foundation as zcl_f
from homeassistant.components.switch import DOMAIN
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE
from .common import (
async_enable... |
"""
This file contains all routes for the /search API
"""
from sanic import Blueprint
from sanic.response import HTTPResponse
from dp4py_sanic.api.response.json_response import json
from dp_conceptual_search.config import CONFIG
from dp_conceptual_search.api.request import ONSRequest
from dp_conceptual_search.ons.sea... |
# -*- coding: UTF-8 -*-
from common_utils.new_log import NewLog
class LogDecorator:
log = NewLog(__name__)
logger = log.get_log()
def __call__(self, func):
def wrapper(*args, **kw):
self.logger.debug("call method %s ===============" % func.__name__)
self.logger.debug("me... |
# -*- coding: utf-8 -*-
'''
Covenant Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
"""Helper functions for the distribution."""
import importlib
import json
import pathlib
import subprocess
import sys
import types
import os
from typing import Optional, List
import requests
import repobee_plug as plug
import _repobee.ext
from _repobee import distinfo
from _repobee import plugin
class DependencyRe... |
from pyspark import SparkConf, SparkContext
import collections
conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)
lines = sc.textFile("D:/celebal/resources/ml-100k/u.data")
ratings = lines.map(lambda x: x.split()[2])
result = ratings.countByValue()
sortedResults = col... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2014-02-08 22:37:13
import os
import time
import shutil
import unittest2 as unittest
import logging
import logging.config
logging.config.fileConfig("pyspid... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.conf import settings
class UserProfileManager(BaseUserManager):
"""Manager for user profiles"""
def c... |
"""
factor.py
"""
from functools import wraps
from operator import attrgetter
from numbers import Number
from numpy import inf, where
from toolz import curry
from zipline.errors import UnknownRankMethod
from zipline.lib.normalize import naive_grouped_rowwise_apply
from zipline.lib.rank import masked_rankdata_2d
from ... |
#!/usr/bin/env python
# Copyright 2019 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 ... |
#!/usr/bin/python
import os
import re
from datetime import datetime, timedelta
from trac.tests.functional import *
from trac.util.datefmt import utc, localtz, format_date
class TestTickets(FunctionalTwillTestCaseSetup):
def runTest(self):
"""Create a ticket, comment on it, and attach a file"... |
"""Polygons and their linear ring components
"""
from ctypes import c_double, c_void_p, cast, POINTER
from ctypes import ArgumentError
import weakref
from shapely.algorithms.cga import signed_area
from shapely.coords import required
from shapely.geos import lgeos
from shapely.geometry.base import BaseGeometry
from sh... |
x=2
print(x == 2)
print(x == 3)
print(x<3)
#Boolean operators
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
if name == "John" or name == "Rick":
print("Your name is either John or Rick.")
# in operator
#The "in" operator co... |
from . import Base
from sqlalchemy import Column, Integer, Text, DateTime, ForeignKey
from datetime import datetime
class Chapter(Base):
__tablename__ = "chapters"
id = Column(Integer, primary_key=True, autoincrement=True)
manga_id = Column(Integer, ForeignKey("manga.id"))
chapter_no = Column(Integer)... |
from systems.plugins.index import BaseProvider
import re
import shlex
class Provider(BaseProvider('task', 'command')):
def execute(self, results, params):
env = self._env_vars(params)
stdin = params.pop('input', self.field_input)
cwd = params.pop('cwd', self.field_cwd)
display = ... |
"""
Tests for `kolibri.utils.cli` module.
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
import os
import tempfile
import pytest
from django.db.utils import OperationalError
from mock import patch
import kolibri
from kolibri.plugins.utils import autoremove_unavailable... |
class Person:
name='zhangsan'
age=20
p = Person()
print(p) # <__main__.Person object at 0x10073e668>
print('⭐️ ' * 20)
class Stu:
name='zhangsan'
age=20
def __str__(self):
return "name: %s; age: %d"%(self.name, self.age)
s = Stu()
print(s) # name: zhangsan; age: 20 |
""" Define the sublayers in encoder/decoder layer """
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class ScaledDotProductAttention(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
se... |
'''Standard challenge module.'''
import os
import shutil
import fcntl
from cffi import FFI
from tornado import gen, concurrent, process
from tornado.stack_context import StackContext
from tornado.ioloop import IOLoop
import PyExt
import Privilege
import Config
from Utils import FileUtils
STATUS_NONE = 0
STATUS_AC = ... |
n, m = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
mini = l[m-1] - l[0]
for i in range(m-n+1):
mini = min(mini, l[i+n-1]-l[i])
print(mini)
|
# global
from typing import Union, Optional, Tuple, Literal
from collections import namedtuple
# local
import ivy
from ivy.framework_handler import current_framework as _cur_framework
inf = float('inf')
# Array API Standard #
# -------------------#
def matrix_transpose(x: Union[ivy.Array, ivy.NativeArray])\
... |
from django.contrib.postgres.fields import JSONField
from django.db import models
from surfsara.models.permission import Permission
class Task(models.Model):
RUNNING = "running"
SUCCESS = "success"
ERROR = "error"
OUTPUT_RELEASED = "output_released"
RELEASE_REJECTED = "release_rejected"
TASK_... |
# Author: Tom Dupre la Tour
# Joan Massich <mailsik@gmail.com>
#
# License: BSD 3 clause
import numpy as np
import pytest
import scipy.sparse as sp
from numpy.testing import assert_array_equal
from sklearn.utils._seq_dataset import (
ArrayDataset32, ArrayDataset64, CSRDataset32, CSRDataset64)
from sklearn... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# bug-report: feilengcui008@gmail.com
""" api for docker registry """
import urllib2
import urllib
import json
import base64
class RegistryException(Exception):
""" registry api related exception """
pass
class RegistryApi(object):
""" interact with docker ... |
#!/usr/bin/env python3
#
# Copyright 2017 Google 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 ... |
#
# Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
#
""" This module provides access to the Deephaven server configuration. """
import jpy
from deephaven import DHError
from deephaven.time import TimeZone
_JDHConfig = jpy.get_type("io.deephaven.configuration.Configuration")
_JDateTimeZone = jpy.get_... |
import torch
from torch import nn, optim, multiprocessing
from torch.utils.data import DataLoader
from torch.utils.tensorboard.writer import SummaryWriter
from tqdm import tqdm
from time import time
from collections import defaultdict
from utils.run_utils import get_logger
from utils.train_utils import CheckpointMan... |
from nodes import *
from tokens import Token, TokenType
class Interpreter:
def __init__(self, ast):
self.ast = ast
def eval(self):
return self.evalHelper(self.ast)
def evalHelper(self, ast):
if isinstance(ast, NumberNode):
return ast.node
elif isinstance(ast, ... |
import hashlib
import json
import os
import boto3
from .retry import retry_on_aws_too_many_requests
batch = boto3.client('batch')
class JobDefinition:
@classmethod
def clear_all(cls):
deleted_count = 0
for jobdef in batch.describe_job_definitions(status='ACTIVE')['jobDefinitions']:
... |
n = int(input())
total_sum = 0
for i in range(1,n+1):
letter = input()
total_sum += ord(letter)
print(f"The sum equals: {total_sum}") |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import PermissionDe... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 14:16:27 2013
@author: Lucio
Program for assessing the memory footprint of the simulation. Needs the
memory_profiler module (installed on the milano cluster).
"""
import os
import time
import sys
import simpactpurple
from memory_profiler import profile
@profile
de... |
# -*- coding: utf-8 -*-
try:
import django
except ImportError as e:
django = None
django_import_error = e
def check_django_import():
if django is None:
raise django_import_error
class django_required(object):
def __call__(self, func):
def wrapper(self, *args, **kwargs):
... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
from airtest.utils.logger import get_logger
from airtest.utils.safesocket import SafeSocket
from airtest.utils.nbsp import NonBlockingStreamReader
from airtest.utils.snippet import on_method_ready, reg_cleanup
from airtest.core.android.yosemite import Yosemite
import struct
LOGGING = get_logger(... |
#
# @lc app=leetcode id=447 lang=python
#
# [447] Number of Boomerangs
#
# https://leetcode.com/problems/number-of-boomerangs/description/
#
# algorithms
# Easy (49.20%)
# Likes: 296
# Dislikes: 447
# Total Accepted: 54.7K
# Total Submissions: 109.6K
# Testcase Example: '[[0,0],[1,0],[2,0]]'
#
# Given n points i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
import shutil
class LibtiffConan(ConanFile):
name = "libtiff"
description = "Library for Tag Image File Format (TIFF)"
url = "https://github.com/conan-io/conan-center-index"
author = "Bincrafters <bincr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.