id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
168,377 | from pathlib import Path
import argparse
from src.utils.common_utils import read_params, clean_prev_dirs_if_exists, create_dir,correlation
import pandas as pd
from src.application_logging.logger import App_Logger
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from sklearn.... | Method Name: data_preprocessing Description: This method performs data preprocessing by reading parameters from param.yaml and then pereforming feature engineering and feature selection based on EDA given in Jupyter notebook notebooks/EDA and preprocessing. Output: Return a preprocessed csv having the data ready for ML... |
168,378 | import os
import shutil
from pathlib import Path
import yaml
import numpy as np
import pickle
import optuna
from sklearn import linear_model
from sklearn import ensemble
import sklearn.svm
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
import xgboost as xgb
from sklearn.model... | Method Name: load_model Description: load the model file to memory Output: The Model file loaded in memory On Failure: Raise Exception Written By: Saurabh Naik Version: 1.0 Revisions: None |
168,379 | from __future__ import print_function
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from skimage import io
import glob
import time
import argparse
from filterpy.kalman import KalmanFilter
np.random.seed(0)
The provided code snippet includes necessar... | Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is the aspect ratio |
168,380 | from __future__ import print_function
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from skimage import io
import glob
import time
import argparse
from filterpy.kalman import KalmanFilter
np.random.seed(0)
The provided code snippet includes necessar... | Takes a bounding box in the centre form [x,y,s,r] and returns it in the form [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right |
168,381 | from __future__ import print_function
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from skimage import io
import glob
import time
import argparse
from filterpy.kalman import KalmanFilter
np.random.seed(0)
def linear_assignment(cost_matrix):
try:
... | Assigns detections to tracked object (both represented as bounding boxes) Returns 3 lists of matches, unmatched_detections and unmatched_trackers |
168,382 | from __future__ import print_function
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from skimage import io
import glob
import time
import argparse
from filterpy.kalman import KalmanFilter
The provided code snippet includes necessary dependencies for... | Parse input arguments. |
168,383 | import streamlit as st
import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer
tokenizer = T5Tokenizer.from_pretrained(model_path)
model = T5ForConditionalGeneration.from_pretrained(model_path)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def generate_summary(text):
#... | null |
168,384 | from steps.preprocess import preprocess
from steps.model_train import train_model
from steps.evaluation import evaluate_model
from pipeline.inference_pipeline import infer_model
def preprocess():
dataset = get_data()
tok_ds = dataset.map(tokenize_data, batched=True)
return tok_ds
def train_model(tok_ds,nu... | null |
168,385 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
logger = logging.getLogger("coinDetLogger")
class Path(PurePat... | reads yaml file and returns Args: path_to_yaml (str): path like input Raises: ValueError: if yaml file is empty e: empty file Returns: ConfigBox: ConfigBox type |
168,386 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
import os
if os.name == 'nt':
# Code ... | create list of directories Args: path_to_directories (list): list of path of directories ignore_log (bool, optional): ignore if multiple dirs is to be created. Defaults to False. |
168,387 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
logger = logging.getLogger("coinDetLogger")
class Path(PurePat... | save json data Args: path (Path): path to json file data (dict): data to be saved in json file |
168,388 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
logger = logging.getLogger("coinDetLogger")
class Path(PurePat... | load json files data Args: path (Path): path to json file Returns: ConfigBox: data as class attributes instead of dict |
168,389 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
logger = logging.getLogger("coinDetLogger")
class Path(PurePat... | save binary file Args: data (Any): data to be saved as binary path (Path): path to binary file |
168,390 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
logger = logging.getLogger("coinDetLogger")
class Path(PurePat... | load binary data Args: path (Path): path to binary file Returns: Any: object stored in the file |
168,391 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
import os
if os.name == 'nt':
# Code ... | get size in KB Args: path (Path): path of the file Returns: str: size in KB |
168,392 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
def decodeImage(imgstring, fileName):
imgdata = base64.b64d... | null |
168,393 | import os
from box.exceptions import BoxValueError
import yaml
from Indian_Coin_Detection import logger
import json
import joblib
from ensure import ensure_annotations
from box import ConfigBox
from pathlib import Path
from typing import Any
import base64
def encodeImageIntoBase64(croppedImagePath):
with open(crop... | null |
168,394 | import streamlit as st
import os
import cv2
from PIL import Image
from Indian_Coin_Detection.pipeline.predict import PredictionPipeline
import subprocess
def train_model():
try:
subprocess.run(["dvc", "repro"], check=True)
st.write("Training successfully completed")
except subprocess.CalledProc... | null |
168,395 | import streamlit as st
import os
import cv2
from PIL import Image
from Indian_Coin_Detection.pipeline.predict import PredictionPipeline
import subprocess
def handle_image_upload():
upload_folder = "uploads"
os.makedirs(upload_folder, exist_ok=True)
image_filename = None
uploaded_image = st.file_uploade... | null |
168,396 | import streamlit as st
import os
import cv2
from PIL import Image
from Indian_Coin_Detection.pipeline.predict import PredictionPipeline
import subprocess
class PredictionPipeline:
def __init__(self,filename:str,model_type:str,threshold:float):
self.filename = filename
self.model_type = model_type
... | null |
168,397 | import streamlit as st
import os
import cv2
from PIL import Image
from Indian_Coin_Detection.pipeline.predict import PredictionPipeline
import subprocess
class Image:
def __init__(self):
def __getattr__(self, name):
def width(self):
def height(self):
def size(self):
def _new(self, im):
... | null |
168,398 | class FormData:
def __init__(self):
self.sku = None
self.national_inv = None
self.lead_time = None
self.in_transit_qty = None
self.forecast_3_month = None
self.forecast_6_month = None
self.forecast_9_month = None
self.sales_1_month = None
self.... | null |
168,399 | import pandas as pd
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from backorder.pipeline import BackorderPredictor
from backorder.utils import get_form_data
from .serializers import ContactUsSe... | null |
168,400 | import pandas as pd
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from backorder.pipeline import BackorderPredictor
from backorder.utils import get_form_data
from .serializers import ContactUsSe... | null |
168,401 | import pandas as pd
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from backorder.pipeline import BackorderPredictor
from backorder.utils import get_form_data
from .serializers import ContactUsSe... | null |
168,402 | import sys, types
from .lock import allocate_lock
from .error import CDefError
from . import model
try:
basestring
except NameError:
# Python 3.x
basestring = str
def _load_backend_lib(backend, name, flags):
import os
if not isinstance(name, basestring):
if sys.platform != "win32" or name is... | null |
168,403 | import sys, types
from .lock import allocate_lock
from .error import CDefError
from . import model
def _builtin_function_type(func):
# a hack to make at least ffi.typeof(builtin_function) work,
# if the builtin function was obtained by 'vengine_cpy'.
import sys
try:
module = sys.modules[func.__... | null |
168,404 | import sys
from . import model
from .error import FFIError
COMMON_TYPES = {}
COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE')
COMMON_TYPES['bool'] = '_Bool'
_CACHE = {}
class FFIError(Exception):
__module__ = 'cffi'
def resolve_common_type(parser, commontype):
try:
return _CACHE[common... | null |
168,405 | import sys
from . import model
from .error import FFIError
def win_common_types():
return {
"UNICODE_STRING": model.StructType(
"_UNICODE_STRING",
["Length",
"MaximumLength",
"Buffer"],
[model.PrimitiveType("unsigned short"),
model.... | null |
168,406 | import os, sys, io
from . import ffiplatform, model
from .error import VerificationError
from .cffi_opcode import *
def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False):
assert preamble is not None
return _make_c_or_py_source(ffi, module_name, preamble, target_c_file,
... | null |
168,407 | import sys, os
from .error import VerificationError
try:
from os.path import samefile
except ImportError:
def samefile(f1, f2):
return os.path.abspath(f1) == os.path.abspath(f2)
def maybe_relative_path(path):
if not os.path.isabs(path):
return path # already relative
dir = path
... | null |
168,408 | import sys, os
from .error import VerificationError
def _flatten(x, f):
if isinstance(x, str):
f.write('%ds%s' % (len(x), x))
elif isinstance(x, dict):
keys = sorted(x.keys())
f.write('%dd' % len(keys))
for key in keys:
_flatten(key, f)
_flatten(x[key], f)... | null |
168,409 | from . import model
from .commontypes import COMMON_TYPES, resolve_common_type
from .error import FFIError, CDefError
import weakref, re, sys
def _workaround_for_static_import_finders():
# Issue #392: packaging tools like cx_Freeze can not find these
# because pycparser uses exec dynamic import. This is an ob... | null |
168,410 | from . import model
from .commontypes import COMMON_TYPES, resolve_common_type
from .error import FFIError, CDefError
import weakref, re, sys
_parser_cache = None
def _get_parser():
global _parser_cache
if _parser_cache is None:
_parser_cache = pycparser.CParser()
return _parser_cache | null |
168,411 | from . import model
from .commontypes import COMMON_TYPES, resolve_common_type
from .error import FFIError, CDefError
import weakref, re, sys
def _warn_for_non_extern_non_static_global_variable(decl):
if not decl.storage:
import warnings
warnings.warn("Global variable '%s' in cdef(): for consistenc... | null |
168,412 | from . import model
from .commontypes import COMMON_TYPES, resolve_common_type
from .error import FFIError, CDefError
import weakref, re, sys
_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$",
re.DOTALL | re.MULTILINE)
_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)"
... | null |
168,413 | from . import model
from .commontypes import COMMON_TYPES, resolve_common_type
from .error import FFIError, CDefError
import weakref, re, sys
_r_words = re.compile(r"\w+|\S")
COMMON_TYPES = {}
COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE')
COMMON_TYPES['bool'] = '_Bool'
def _common_type_names(csource... | null |
168,414 | import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform
from .error import VerificationError
if sys.version_info >= (3, 3):
import importlib.machinery
else:
import imp
if sys.version_info >= (3,):
NativeIO = io.StringIO
else:
_FORCE_GENERIC_ENGINE = False
d... | null |
168,415 | import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform
from .error import VerificationError
_TMPDIR = None
The provided code snippet includes necessary dependencies for implementing the `set_tmpdir` function. Write a Python function `def set_tmpdir(dirname)` to solve ... | Set the temporary directory to use instead of __pycache__. |
168,416 | import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform
from .error import VerificationError
def _caller_dir_pycache():
if _TMPDIR:
return _TMPDIR
result = os.environ.get('CFFI_TMPDIR')
if result:
return result
filename = sys._getframe(2)... | Clean up the temporary directory by removing all files in it called `_cffi_*.{c,so}` as well as the `build` subdirectory. |
168,417 | import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform
from .error import VerificationError
def _ensure_dir(filename):
dirname = os.path.dirname(filename)
if dirname and not os.path.isdir(dirname):
os.makedirs(dirname) | null |
168,418 | from .error import VerificationError
def format_four_bytes(num):
return '\\x%02X\\x%02X\\x%02X\\x%02X' % (
(num >> 24) & 0xFF,
(num >> 16) & 0xFF,
(num >> 8) & 0xFF,
(num ) & 0xFF) | null |
168,419 | import sys, os, subprocess
from .error import PkgConfigError
def merge_flags(cfg1, cfg2):
"""Merge values from cffi config flags cfg2 to cf1
Example:
merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
{"libraries": ["one", "two"]}
"""
for key, value in cfg2.items():
if k... | r"""Return compiler line flags for FFI.set_source based on pkg-config output Usage ... ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"]) If pkg-config is installed on build machine, then arguments include_dirs, library_dirs, libraries, define_macros, extra_compile_args and extra_link_args are ext... |
168,420 | import os
import sys
try:
basestring
except NameError:
# Python 3.x
basestring = str
def add_cffi_module(dist, mod_spec):
def cffi_modules(dist, attr, value):
assert attr == 'cffi_modules'
if isinstance(value, basestring):
value = [value]
for cffi_module in value:
add_cffi_modu... | null |
168,421 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
Q_CONST = 0x01
Q_RESTRICT = 0x02
Q_VOLATILE = 0x04
def qualify(quals, replace_with):
if quals & Q_CONST:
replace_with = ' const ' + replace_with.lstrip()
if quals & Q_VOLA... | null |
168,422 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
Q_CONST = 0x01
class PointerType(BaseType):
_attrs_ = ('totype', 'quals')
def __init__(self, totype, quals=0):
self.totype = totype
self.quals = quals
extra... | null |
168,423 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
class StructType(StructOrUnion):
kind = 'struct'
def unknown_type(name, structname=None):
if structname is None:
structname = '$%s' % name
tp = StructType(structname, Non... | null |
168,424 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
class NamedPointerType(PointerType):
_attrs_ = ('totype', 'name')
def __init__(self, totype, name, quals=0):
PointerType.__init__(self, totype, quals)
self.name = name... | null |
168,425 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
global_lock = allocate_lock()
_typecache_cffi_backend = weakref.WeakValueDictionary()
def get_typecache(backend):
# returns _typecache_cffi_backend if backend is the _cffi_backend
# ... | null |
168,426 | import types
import weakref
from .lock import allocate_lock
from .error import CDefError, VerificationError, VerificationMissing
def attach_exception_info(e, name):
if e.args and type(e.args[0]) is str:
e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:] | null |
168,427 | from datetime import tzinfo, timedelta, datetime
from pytz import HOUR, ZERO, UTC
import time as _time
class timedelta(SupportsAbs[timedelta]):
min: ClassVar[timedelta]
max: ClassVar[timedelta]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __init__(
self,
... | null |
168,428 | from datetime import datetime
from struct import unpack, calcsize
from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
from pytz.tzinfo import memorized_datetime, memorized_timedelta
def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII')
_NULL = _b... | null |
168,429 | from datetime import datetime, timedelta, tzinfo
from bisect import bisect_right
import pytz
from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
The provided code snippet includes necessary dependencies for implementing the `_to_seconds` function. Write a Python function `def _to_seconds(td)` to solve... | Convert a timedelta to seconds |
168,430 | from datetime import datetime, timedelta, tzinfo
from bisect import bisect_right
import pytz
from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
def memorized_timedelta(seconds):
'''Create only one instance of each distinct timedelta'''
try:
return _timedelta_cache[seconds]
except K... | Factory function for unpickling pytz tzinfo instances. This is shared for both StaticTzInfo and DstTzInfo instances, because database changes could cause a zones implementation to switch between these two base classes and we can't break pickles on a pytz version upgrade. |
168,432 | STDOUT = -11
try:
import ctypes
from ctypes import LibraryLoader
windll = LibraryLoader(ctypes.WinDLL)
from ctypes import wintypes
except (AttributeError, ImportError):
windll = None
SetConsoleTextAttribute = lambda *_: None
winapi_test = lambda *_: None
else:
from ctypes import byref, S... | null |
168,445 | import os
import platform
from pathlib import Path
from cffi import FFI
def _get_target_platform(arch_flags, default):
flags = [f for f in arch_flags.split(" ") if f.strip() != ""]
try:
pos = flags.index("-arch")
return flags[pos + 1].lower()
except ValueError:
pass
return def... | null |
168,446 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | List all the subcommands of a group that start with the incomplete value and aren't hidden. :param ctx: Invocation context for the group. :param incomplete: Value being completed. May be empty. |
168,447 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | null |
168,448 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | null |
168,449 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | Context manager that attaches extra information to exceptions. |
168,450 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. |
168,451 | import enum
import errno
import inspect
import os
import sys
import typing as t
from collections import abc
from contextlib import contextmanager
from contextlib import ExitStack
from functools import partial
from functools import update_wrapper
from gettext import gettext as _
from gettext import ngettext
from itertoo... | Check if the value is iterable but not a string. Raises a type error, or return an iterator over the value. |
168,452 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Wraps a function so that it swallows exceptions. |
168,453 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Converts a value into a valid string. |
168,454 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Returns a condensed version of help string. |
168,455 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Returns a system stream for byte processing. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` |
168,456 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'... |
168,457 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This... |
168,458 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Formats a filename for user display. The main purpose of this function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename. :param filename: form... |
168,459 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ... |
168,460 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Determine the command used to run the program, for use in help text. If a file or entry point was executed, the file name is returned. If ``python -m`` was used to execute a module or package, ``python -m name`` is returned. This doesn't try to be too precise, the goal is to give a concise name for help text. Files are... |
168,461 | import os
import re
import sys
import typing as t
from functools import update_wrapper
from types import ModuleType
from ._compat import _default_text_stderr
from ._compat import _default_text_stdout
from ._compat import _find_binary_writer
from ._compat import auto_wrap_for_ansi
from ._compat import binary_streams
fro... | Simulate Unix shell expansion with Python functions. See :func:`glob.glob`, :func:`os.path.expanduser`, and :func:`os.path.expandvars`. This is intended for use on Windows, where the shell does not do any expansion. It may not exactly match what a Unix shell would do. :param args: List of command line arguments to expa... |
168,462 | import typing as t
from contextlib import contextmanager
from gettext import gettext as _
from ._compat import term_len
from .parser import split_opt
def term_len(x: str) -> int:
return len(strip_ansi(x))
def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:
widths: t.Dict[int, int] = {... | null |
168,463 | import typing as t
from contextlib import contextmanager
from gettext import gettext as _
from ._compat import term_len
from .parser import split_opt
def iter_rows(
rows: t.Iterable[t.Tuple[str, str]], col_count: int
) -> t.Iterator[t.Tuple[str, ...]]:
for row in rows:
yield row + ("",) * (col_count - ... | null |
168,464 | import typing as t
from contextlib import contextmanager
from gettext import gettext as _
from ._compat import term_len
from .parser import split_opt
def term_len(x: str) -> int:
return len(strip_ansi(x))
class TextWrapper(textwrap.TextWrapper):
def _handle_long_word(
self,
reversed_chunks: t.... | A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line co... |
168,465 | import typing as t
from contextlib import contextmanager
from gettext import gettext as _
from ._compat import term_len
from .parser import split_opt
def split_opt(opt: str) -> t.Tuple[str, str]:
first = opt[:1]
if first.isalnum():
return "", opt
if opt[1:2] == first:
return opt[:2], opt[2:... | Given a list of option strings this joins them in the most appropriate way and returns them in the form ``(formatted_string, any_prefix_is_slash)`` where the second item in the tuple is a flag that indicates if any of the option prefixes was a slash. |
168,466 | import typing as t
from collections import deque
from gettext import gettext as _
from gettext import ngettext
from .exceptions import BadArgumentUsage
from .exceptions import BadOptionUsage
from .exceptions import NoSuchOption
from .exceptions import UsageError
if t.TYPE_CHECKING:
import typing_extensions as te
... | Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the... |
168,467 | import typing as t
from collections import deque
from gettext import gettext as _
from gettext import ngettext
from .exceptions import BadArgumentUsage
from .exceptions import BadOptionUsage
from .exceptions import NoSuchOption
from .exceptions import UsageError
if t.TYPE_CHECKING:
import typing_extensions as te
... | null |
168,468 | import typing as t
from collections import deque
from gettext import gettext as _
from gettext import ngettext
from .exceptions import BadArgumentUsage
from .exceptions import BadOptionUsage
from .exceptions import NoSuchOption
from .exceptions import UsageError
if t.TYPE_CHECKING:
import typing_extensions as te
... | Split an argument string as with :func:`shlex.split`, but don't fail if the string is incomplete. Ignores a missing closing quote or incomplete escape sequence and uses the partial token as-is. .. code-block:: python split_arg_string("example 'my file") ["example", "my file"] split_arg_string("example my\\") ["example"... |
168,469 | import os
import re
import typing as t
from gettext import gettext as _
from .core import Argument
from .core import BaseCommand
from .core import Context
from .core import MultiCommand
from .core import Option
from .core import Parameter
from .core import ParameterSource
from .parser import split_arg_string
from .util... | Perform shell completion for the given CLI program. :param cli: Command being called. :param ctx_args: Extra arguments to pass to ``cli.make_context``. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. :param instruction: ... |
168,470 | import os
import re
import typing as t
from gettext import gettext as _
from .core import Argument
from .core import BaseCommand
from .core import Context
from .core import MultiCommand
from .core import Option
from .core import Parameter
from .core import ParameterSource
from .parser import split_arg_string
from .util... | Register a :class:`ShellComplete` subclass under the given name. The name will be provided by the completion instruction environment variable during completion. :param cls: The completion class that will handle completion for the shell. :param name: Name to register the class under. Defaults to the class's ``name`` att... |
168,471 | import os
import re
import typing as t
from gettext import gettext as _
from .core import Argument
from .core import BaseCommand
from .core import Context
from .core import MultiCommand
from .core import Option
from .core import Parameter
from .core import ParameterSource
from .parser import split_arg_string
from .util... | Produce the context hierarchy starting with the command and traversing the complete arguments. This only follows the commands, it doesn't trigger input prompts or callbacks. :param cli: Command being called. :param prog_name: Name of the executable in the shell. :param args: List of complete args before the incomplete ... |
168,472 | import os
import re
import typing as t
from gettext import gettext as _
from .core import Argument
from .core import BaseCommand
from .core import Context
from .core import MultiCommand
from .core import Option
from .core import Parameter
from .core import ParameterSource
from .parser import split_arg_string
from .util... | Find the Click object that will handle the completion of the incomplete value. Return the object and the incomplete value. :param ctx: Invocation context for the command represented by the parsed complete args. :param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May... |
168,473 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Marks a callback as wanting to receive the current context object as first argument. |
168,474 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. |
168,475 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(... |
168,476 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Create a decorator that passes a key from :attr:`click.Context.meta` as the first argument to the decorated function. :param key: Key in ``Context.meta`` to pass. :param doc_description: Description of the object being passed, inserted into the decorator's docstring. Defaults to "the 'key' key from Context.meta". .. ve... |
168,477 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | null |
168,478 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | null |
168,479 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. .. versionchanged:: 8.1 This decorator can be applied without parentheses. |
168,480 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. :param cls: ... |
168,481 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. :param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passed to :func:`option`. |
168,482 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation. :param param_decls: One or more option names. Defaults to the single value ``"--password"``. :param kwargs: Extra arguments are passed to :func:`option`. |
168,483 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Add a ``--version`` option which immediately prints the version number and exits the program. If ``version`` is not provided, Click will try to detect it using :func:`importlib.metadata.version` to get the version for the ``package_name``. On Python < 3.8, the ``importlib_metadata`` backport must be installed. If ``pac... |
168,484 | import inspect
import types
import typing as t
from functools import update_wrapper
from gettext import gettext as _
from .core import Argument
from .core import Command
from .core import Context
from .core import Group
from .core import Option
from .core import Parameter
from .globals import get_current_context
from .... | Add a ``--help`` option which immediately prints the help page and exits the program. This is usually unnecessary, as the ``--help`` option is added to each command automatically unless ``add_help_option=False`` is passed. :param param_decls: One or more option names. Defaults to the single value ``"--help"``. :param k... |
168,485 | import io
import sys
import time
import typing as t
from ctypes import byref
from ctypes import c_char
from ctypes import c_char_p
from ctypes import c_int
from ctypes import c_ssize_t
from ctypes import c_ulong
from ctypes import c_void_p
from ctypes import POINTER
from ctypes import py_object
from ctypes import Struc... | null |
168,486 | import io
import sys
import time
import typing as t
from ctypes import byref
from ctypes import c_char
from ctypes import c_char_p
from ctypes import c_int
from ctypes import c_ssize_t
from ctypes import c_ulong
from ctypes import c_void_p
from ctypes import POINTER
from ctypes import py_object
from ctypes import Struc... | null |
168,487 | import io
import sys
import time
import typing as t
from ctypes import byref
from ctypes import c_char
from ctypes import c_char_p
from ctypes import c_int
from ctypes import c_ssize_t
from ctypes import c_ulong
from ctypes import c_void_p
from ctypes import POINTER
from ctypes import py_object
from ctypes import Struc... | null |
168,488 | import os
import typing as t
from gettext import gettext as _
from gettext import ngettext
from ._compat import get_text_stderr
from .utils import echo
if t.TYPE_CHECKING:
from .core import Context
from .core import Parameter
def _join_param_hints(
param_hint: t.Optional[t.Union[t.Sequence[str], str]]
) ->... | null |
168,489 | import typing as t
from threading import local
_local = local()
The provided code snippet includes necessary dependencies for implementing the `push_context` function. Write a Python function `def push_context(ctx: "Context") -> None` to solve the following problem:
Pushes a new context to the current stack.
Here is ... | Pushes a new context to the current stack. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.