id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
37,891
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,892
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,893
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,894
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,895
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,896
import os import asyncio from datetime import datetime, timedelta from typing import List from matplotlib import pyplot as plt from aiocqhttp.exceptions import ActionFailed from nonebot import NoneBot from nonebot import MessageSegment as ms from nonebot.typing import Context_T from hoshino import util, priv from . imp...
null
37,897
from datetime import datetime, timezone, timedelta from hoshino import util from .dao.sqlitedao import ClanDao, MemberDao, BattleDao from .exception import NotFoundError def get_config(): return util.load_config(__file__)
null
37,898
import re from hoshino import util from ..exception import ParseError from ..battlemaster import BattleMaster _unit_rate = {'': 1, 'k': 1000, 'w': 10000, '千': 1000, '万': 10000} _rex_dint = re.compile(r'^(\d+)([wk千万]?)$', re.I) class ParseError(ClanBattleError): def damage_int(x:str) -> int: x = util.normalize_str...
null
37,899
import re from hoshino import util from ..exception import ParseError from ..battlemaster import BattleMaster x1_bcode = re.compile(r'^老?([1-5])王?$') _rex2_bcode = re.compile(r'^老?([一二三四五])王?$') class ParseError(ClanBattleError): pass def boss_code(x:str) -> int: x = util.normalize_str(x) if m := _rex1_bc...
null
37,900
import re from hoshino import util from ..exception import ParseError from ..battlemaster import BattleMaster re.compile(r'^[1-9]\d{0,2}$') class ParseError(ClanBattleError): pass def round_code(x:str) -> int: x = util.normalize_str(x) if _rex_rcode.match(x): return int(x) raise ParseError('周目...
null
37,901
import re from hoshino import util from ..exception import ParseError from ..battlemaster import BattleMaster class ParseError(ClanBattleError): class BattleMaster(object): def __init__(self, group): def get_timezone_num(server): def get_yyyymmdd(time, zone_num:int=8): def next_boss(round_:int, bo...
null
37,902
import re import random from hoshino import Service from hoshino.typing import CQEvent from hoshino.util import filt_message async def do_dice(bot, ev, num, min_, max_, opr, offset, TIP="的掷骰结果是:"): async def dice(bot, ev): num, min_, max_, opr, offset = 1, 1, 100, 1, 0 match = ev['match'] if s := match.gro...
null
37,903
import re import random from hoshino import Service from hoshino.typing import CQEvent from hoshino.util import filt_message async def do_dice(bot, ev, num, min_, max_, opr, offset, TIP="的掷骰结果是:"): if num == 0: await bot.send(ev, '咦?我骰子呢?') return min_, max_ = min(min_, max_), max(min_, max_) ...
null
37,904
from nonebot.command import SwitchException from hoshino import CanceledException, message_preprocessor, trigger from hoshino.typing import CQEvent async def handle_message(bot, event: CQEvent, _): if event.detail_type != 'group': return for t in trigger.chain: for service_func in t.find_hand...
null
37,905
from datetime import datetime import hoshino from hoshino import config from hoshino.typing import CQEvent _black_group = {} def set_block_group(group_id, time): _black_group[group_id] = datetime.now() + time
null
37,906
from datetime import datetime import hoshino from hoshino import config from hoshino.typing import CQEvent _black_group = {} def check_block_group(group_id): if group_id in _black_group and datetime.now() > _black_group[group_id]: del _black_group[group_id] # 拉黑时间过期 return False return bool(gr...
null
37,907
import logging import os import sys default_handler = logging.StreamHandler(sys.stdout) default_handler.setFormatter(formatter) error_handler = logging.FileHandler(_error_log_file, encoding='utf8') error_handler.setLevel(logging.ERROR) error_handler.setFormatter(formatter) critical_handler = logging.FileHandler(_critic...
null
37,908
import asyncio from functools import partial from typing import Optional, Any import requests from requests import * async def run_sync_func(func, *args, **kwargs) -> Any: return await asyncio.get_event_loop().run_in_executor( None, partial(func, *args, **kwargs)) class AsyncResponse: def __init__(self,...
null
37,909
import asyncio from functools import partial from typing import Optional, Any import requests from requests import * async def run_sync_func(func, *args, **kwargs) -> Any: return await asyncio.get_event_loop().run_in_executor( None, partial(func, *args, **kwargs)) class AsyncResponse: def __init__(self,...
null
37,910
import asyncio from functools import partial from typing import Optional, Any import requests from requests import * async def run_sync_func(func, *args, **kwargs) -> Any: class AsyncResponse: def __init__(self, response: requests.Response): def ok(self) -> bool: def status_code(self) -> int: def he...
null
37,911
import asyncio from functools import partial from typing import Optional, Any import requests from requests import * async def run_sync_func(func, *args, **kwargs) -> Any: return await asyncio.get_event_loop().run_in_executor( None, partial(func, *args, **kwargs)) class AsyncResponse: def __init__(self,...
null
37,912
import asyncio from functools import partial from typing import Optional, Any import requests from requests import * async def run_sync_func(func, *args, **kwargs) -> Any: return await asyncio.get_event_loop().run_in_executor( None, partial(func, *args, **kwargs)) class AsyncResponse: def __init__(self,...
null
37,913
import asyncio import os import random import re from collections import defaultdict from functools import wraps import nonebot import pytz from nonebot.command import SwitchException, _FinishException, _PauseException from nonebot.message import CanceledException, Message import hoshino from hoshino import log, priv, ...
null
37,914
import asyncio import os import random import re from collections import defaultdict from functools import wraps import nonebot import pytz from nonebot.command import SwitchException, _FinishException, _PauseException from nonebot.message import CanceledException, Message import hoshino from hoshino import log, priv, ...
null
37,915
import asyncio import os import random import re from collections import defaultdict from functools import wraps import nonebot import pytz from nonebot.command import SwitchException, _FinishException, _PauseException from nonebot.message import CanceledException, Message import hoshino from hoshino import log, priv, ...
null
37,916
from collections import defaultdict import re class DFAFilter(): '''Filter Messages from keywords Use DFA to keep algorithm perform constantly >>> f = DFAFilter() >>> f.add("sexy") >>> f.filter("hello sexy baby") hello **** baby ''' def __init__(self): self.keyword_chains = {} ...
null
37,917
from __future__ import annotations import typing from contextlib import suppress from datapane.client.exceptions import DPClientError from datapane.client.utils import display_msg from .environment import get_environment from .exceptions import BlocksNotFoundException, NotebookParityException if typing.TYPE_CHECKING: ...
Convert IPython notebook cells to a list of Datapane Blocks Recognized cell tags: - `dp-exclude` - Exclude this cell (when opt_out=True) - `dp-include` - Include this cell (when opt_out=False) - `dp-show-code` - Show the input code for this cell - `dp-show-markdown` - Show the markdown for this cell ..note:: IPython ou...
37,918
from __future__ import annotations import typing as t from abc import abstractmethod import datapane.blocks as b from datapane.client.utils import display_msg from datapane.ipython.exceptions import BlocksNotFoundException BlockFilterF = t.Callable[[b.BaseBlock], bool] BaseElementList = t.List[b.BaseBlock] def partitio...
Partition blocks by types
37,919
from __future__ import annotations import typing as t from abc import abstractmethod import datapane.blocks as b from datapane.client.utils import display_msg from datapane.ipython.exceptions import BlocksNotFoundException BaseElementList = t.List[b.BaseBlock] _registry: t.Dict[str, t.Type[IPythonTemplate]] = {} def fi...
Guess the template to use based on the blocks provided
37,920
from __future__ import annotations import secrets from .base import BaseBlock, BlockId The provided code snippet includes necessary dependencies for implementing the `gen_name` function. Write a Python function `def gen_name() -> str` to solve the following problem: Return a (safe) name for use in a Block Here is the...
Return a (safe) name for use in a Block
37,921
from __future__ import annotations import typing as t from abc import ABC from lxml.builder import ElementMaker from datapane.client import DPClientError, log from datapane.common.viewxml_utils import is_valid_id, mk_attribs if t.TYPE_CHECKING: from typing_extensions import Self from datapane.blocks import Bloc...
null
37,922
import atexit import os import shutil import time from datetime import timedelta from pathlib import Path from tempfile import gettempdir, mkdtemp, mkstemp from typing_extensions import Self from datapane.client import log from datapane.common import MIME, guess_type tmp_dir = Path(mkdtemp(prefix="dp-tmp-", dir=cache_d...
Ensure we cleanup the tmp_dir on Python VM exit
37,923
from __future__ import annotations from packaging import version as v from packaging.specifiers import SpecifierSet from datapane.client import log def _check_version(name: str, _v: v.Version, ss: SpecifierSet): if _v not in ss: log.warning( f"{name} version {_v} is not supported, these plots m...
null
37,924
from __future__ import annotations import dataclasses as dc import typing as t from collections import namedtuple from lxml import etree from lxml.builder import ElementMaker from multimethod import DispatchError, multimethod from datapane import DPClientError from datapane.blocks import BaseBlock from datapane.blocks....
null
37,925
from __future__ import annotations import json import pickle import typing as t from contextlib import suppress from io import TextIOWrapper import pandas as pd from altair.utils import SchemaBase from multimethod import multimethod from packaging import version as v from packaging.specifiers import SpecifierSet from p...
null
37,926
import random import typing as t from pathlib import Path import altair as alt import importlib_resources as ir import numpy as np import pandas as pd from datapane import Blocks from datapane import blocks as b from datapane.common import NPath The provided code snippet includes necessary dependencies for implementin...
Attach code fragment to an existing plot/figure/dataframe for use within a report Args: block: The existing object to add code to - can be either an existing dp Block or an Python object code: The code fragment to add language: The language of the code fragment (optional) Returns: A Select block that provides the figur...
37,927
import random import typing as t from pathlib import Path import altair as alt import importlib_resources as ir import numpy as np import pandas as pd from datapane import Blocks from datapane import blocks as b from datapane.common import NPath The provided code snippet includes necessary dependencies for implementin...
An easy way to build a complete report from a single top-level markdown text / file template. Any additional context can be passed in and will be inserted into the Markdown template. Args: text_or_file: The markdown text, or path to a markdown file, using {{}} for templating *args: positional template context arguments...
37,928
import random import typing as t from pathlib import Path import altair as alt import importlib_resources as ir import numpy as np import pandas as pd from datapane import Blocks from datapane import blocks as b from datapane.common import NPath def gen_df(dim: int = 4) -> pd.DataFrame: """Return a test simple df""...
Generate a sample Altair plot
37,929
import random import typing as t from pathlib import Path import altair as alt import importlib_resources as ir import numpy as np import pandas as pd from datapane import Blocks from datapane import blocks as b from datapane.common import NPath def gen_df(dim: int = 4) -> pd.DataFrame: """Return a test simple df""...
Generate a sample demo view Returns: A datapane View object for saving or uploading
37,930
from __future__ import annotations import os import typing as t from pathlib import Path from shutil import rmtree from datapane.client import DPClientError from datapane.common import NPath from datapane.view import Blocks, BlocksT from .file_store import B64FileEntry, GzipTmpFileEntry from .processors import ( Co...
Build an (static) app with a directory structure, which can be served by a local http server !!! note This outputs compressed assets into the dir as well, may be an issue if self-hosting Args: blocks: The `Blocks` object or a list of Blocks name: The name of the app directory to be created dest: File path to store the ...
37,931
from __future__ import annotations import os import typing as t from pathlib import Path from shutil import rmtree from datapane.client import DPClientError from datapane.common import NPath from datapane.view import Blocks, BlocksT from .file_store import B64FileEntry, GzipTmpFileEntry from .processors import ( Co...
Save the app document to a local HTML file Args: blocks: The `Blocks` object or a list of Blocks path: File path to store the document open: Open in your browser after creating (default: False) name: Name of the document (optional: uses path if not provided) formatting: Sets the basic app styling
37,932
from __future__ import annotations import os import typing as t from pathlib import Path from shutil import rmtree from datapane.client import DPClientError from datapane.common import NPath from datapane.view import Blocks, BlocksT from .file_store import B64FileEntry, GzipTmpFileEntry from .processors import ( Co...
Stringify the app document to a HTML string Args: blocks: The `Blocks` object or a list of Blocks name: Name of the document (optional: uses path if not provided) formatting: Sets the basic app styling
37,933
from __future__ import annotations import os import typing as t from pathlib import Path from shutil import rmtree from datapane.client import DPClientError from datapane.common import NPath from datapane.view import Blocks, BlocksT from .file_store import B64FileEntry, GzipTmpFileEntry from .processors import ( Co...
(No longer supported). Upload as a report, including its attached assets, to the logged-in Datapane Server.
37,934
from __future__ import annotations import dataclasses as dc import typing as t from enum import Enum from pathlib import Path from datapane.common import ViewXML from datapane.view import Blocks from .file_store import DummyFileEntry, FileEntry, FileStore class ViewState: # maybe a FileHandler interface?? block...
null
37,935
from __future__ import print_function import sys def _cli_parse(args): # pragma: no coverage from argparse import ArgumentParser parser = ArgumentParser(prog=args[0], usage="%(prog)s [options] package.module:app") opt = parser.add_argument opt("--version", action="store_true", help="show version number...
null
37,936
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,937
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,938
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Turn all capturing groups in a regular expression pattern into non-capturing groups.
37,939
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,940
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,941
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,942
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
37,943
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Open a file in a safe way and return an instance of :exc:`HTTPResponse` that can be sent back to the client. :param filename: Name or path of the file to send, relative to ``root``. :param root: Root path for file lookups. Should be an absolute directory path. :param mimetype: Provide the content-type header (default: ...
37,944
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,945
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
37,946
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results. :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``) :return: List of (value, params) tuple...
37,947
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
null
37,948
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Encode and sign a pickle-able object. Return a (byte) string
37,949
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Verify and decode an encoded string. Return an object or None.
37,950
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Escape and quote a string to be used as an HTTP attribute.
37,951
from __future__ import print_function import sys if __name__ == '__main__': _cli_patch(sys.argv) import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedat...
Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/<x>/<y>' c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>' d(x=5, y=6) -> '/d' and '/d...
37,952
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
37,953
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
37,954
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Return a callable that relays calls to the current default app.
37,955
from __future__ import print_function import sys import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, datetime, timedelta from tempfile import NamedTem...
Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(di...
37,956
from __future__ import print_function import sys __version__ = '0.13-dev' def _cli_parse(args): import base64, calendar, cgi, email.utils, functools, hmac, itertools,\ mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib from types import FunctionType from datetime import date as datedate, da...
null
37,957
import locale import logging import mimetypes import re import sys import typing as t from pathlib import Path import chardet import importlib_resources as ir from chardet.universaldetector import UniversalDetector from .dp_types import MIME mimetypes.init(files=[str(ir.files("datapane.resources") / "mime.types")]) dou...
null
37,958
import locale import logging import mimetypes import re import sys import typing as t from pathlib import Path import chardet import importlib_resources as ir from chardet.universaldetector import UniversalDetector from .dp_types import MIME def guess_encoding(fn: str) -> str: with open(fn, "rb") as f: det...
null
37,959
import locale import logging import mimetypes import re import sys import typing as t from pathlib import Path import chardet import importlib_resources as ir from chardet.universaldetector import UniversalDetector from .dp_types import MIME log = logging.getLogger("datapane") ON_WINDOWS = sys.platform == "win32" The ...
Encoding-aware text reader - handles cases like on Windows where a file is UTF-8, but default locale is windows-1252
37,960
import locale import logging import mimetypes import re import sys import typing as t from pathlib import Path import chardet import importlib_resources as ir from chardet.universaldetector import UniversalDetector from .dp_types import MIME The provided code snippet includes necessary dependencies for implementing th...
Return a new dict with the empty/falsey values removed
37,961
import locale import logging import mimetypes import re import sys import typing as t from pathlib import Path import chardet import importlib_resources as ir from chardet.universaldetector import UniversalDetector from .dp_types import MIME _SHOULD_COMPRESS_MIME_TYPE_REGEXPS = [ re.compile(p) for p in [ ...
null
37,962
import datetime from numbers import Number from typing import Any import numpy as np import pandas as pd from packaging.specifiers import SpecifierSet from packaging.version import Version The provided code snippet includes necessary dependencies for implementing the `bipartite_to_bool` function. Write a Python functi...
Converts biperatite numeric {0, 1} columns to bool.
37,963
import datetime from numbers import Number from typing import Any import numpy as np import pandas as pd from packaging.specifiers import SpecifierSet from packaging.version import Version def convert_axis(df: pd.DataFrame): """flatten both columns and indexes""" # flatten hierarchical columns and convert to st...
Processing steps needed before writing / after reading We only modify the dataframe to optimise size, rather than convert/infer types, e.g. no longer parsing dates from strings NOTE - this mutates the dataframe by default but returns it - use the returned copy!
37,964
import datetime from numbers import Number from typing import Any import numpy as np import pandas as pd from packaging.specifiers import SpecifierSet from packaging.version import Version The provided code snippet includes necessary dependencies for implementing the `to_df` function. Write a Python function `def to_d...
Converts a python object, i.e. a app's output, to a dataframe NOTE - this returns a new DF each time
37,965
import datetime from numbers import Number from typing import Any import numpy as np import pandas as pd from packaging.specifiers import SpecifierSet from packaging.version import Version TRUNCATE_CELLS = 10000 TRUNCATE_ROWS = 1000 The provided code snippet includes necessary dependencies for implementing the `trunca...
Truncate a pandas dataframe if needed
37,966
from typing import Union from packaging import version as v from packaging.specifiers import SpecifierSet from .dp_types import log class VersionMismatch(Exception): pass log = logging.getLogger("datapane") The provided code snippet includes necessary dependencies for implementing the `is_version_compatible` func...
Check provider supports consumer and throws exception if not Set the spec so that the consumer has to be within a micro/patch release of the provider NOTE - this isn't semver - breaks when have > v1 release as then treats minor as breaking, e.g. 2.2.5 is not compat with 2.1.5
37,967
import dataclasses as dc import json import math import re import typing as t from collections.abc import Sized from numbers import Number import importlib_resources as ir from lxml import etree from lxml.etree import DocumentInvalid from lxml.etree import _Element as ElementT from micawber import ProviderException, bo...
null
37,968
import dataclasses as dc import json import math import re import typing as t from collections.abc import Sized from numbers import Number import importlib_resources as ir from lxml import etree from lxml.etree import DocumentInvalid from lxml.etree import _Element as ElementT from micawber import ProviderException, bo...
(cached) regex to check for a xsd:ID name
37,969
import dataclasses as dc import json import math import re import typing as t from collections.abc import Sized from numbers import Number import importlib_resources as ir from lxml import etree from lxml.etree import DocumentInvalid from lxml.etree import _Element as ElementT from micawber import ProviderException, bo...
Validate the model against the schema, throws an etree.DocumentInvalid if not
37,970
import dataclasses as dc import json import math import re import typing as t from collections.abc import Sized from numbers import Number import importlib_resources as ir from lxml import etree from lxml.etree import DocumentInvalid from lxml.etree import _Element as ElementT from micawber import ProviderException, bo...
convert attributes, dropping None and empty values
37,971
import dataclasses as dc import json import math import re import typing as t from collections.abc import Sized from numbers import Number import importlib_resources as ir from lxml import etree from lxml.etree import DocumentInvalid from lxml.etree import _Element as ElementT from micawber import ProviderException, bo...
Return html for an embeddable URL
37,972
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS log = logging...
Log an internal process
37,973
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS The provided ...
Creates a NamedTemporaryFile that doesn't disappear on .close()
37,974
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS The provided ...
Wrapper to generate a temporary filename only that is deleted on leaving context
37,975
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS NPath = t.Uni...
(UNIX only) Return path to a compressed version of the input filename
37,976
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS NPath = t.Uni...
(UNIX only) Return path to a compressed version of the input filename
37,977
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS NPath = t.Uni...
(X-Plat) Return path to a compressed version of the input filename
37,978
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS The provided ...
(x-plat) Memory-based gzip compression
37,979
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS The provided ...
Set working dir to a tempdir for duration of context
37,980
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS NPath = t.Uni...
Switch dir and push it onto the (call-)stack
37,981
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS def get_files...
null
37,982
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS def walk_path...
null
37,983
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS def unixtime(...
null
37,984
import datetime import gzip import io import os import shutil import subprocess import time import typing as t from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory, mkstemp from .dp_types import NPath, log from .utils import ON_WINDOWS The provided ...
Return ISO timestamp for a datetime
37,985
import abc import enum from typing import IO, Dict, Type, Union import pandas as pd import pyarrow as pa from pandas.errors import ParserError from pyarrow import RecordBatchFileWriter from .df_processor import obj_to_str, process_df, str_to_arrow_str from .dp_types import ARROW_EXT, ARROW_MIMETYPE, MIME, log from .uti...
Write an arrow table to a file
37,986
from __future__ import annotations import enum import logging import logging.config import os import string import sys import typing as t def _setup_dp_logging(verbosity: int = 0, logs_stream: t.TextIO = None) -> None: global _have_setup_logging log_level = "WARNING" if verbosity == 1: log_level = "...
Enable logging for debug purposes
37,987
from __future__ import annotations import enum import logging import logging.config import os import string import sys import typing as t The provided code snippet includes necessary dependencies for implementing the `print_debug_info` function. Write a Python function `def print_debug_info()` to solve the following p...
Print useful debugging information
37,988
from __future__ import annotations import enum import logging import logging.config import os import string import sys import typing as t def get_environment() -> PythonEnvironment: """Returns the current IPython environment""" global _env if _env is None: _env = _get_environment() log.info...
Open the given URL in the user's browser
37,989
from __future__ import annotations import enum import logging import logging.config import os import string import sys import typing as t class DPMode(enum.Enum): """DP can operate in multiple modes as specified by this Enum""" SCRIPT = enum.auto() # run from the cmd-line LIBRARY = enum.auto() # imported ...
null
37,990
import typing as t from typing import Optional from .utils import log class Config: def is_public(self) -> bool: return True def is_org(self) -> bool: return not self.is_public def is_authenticated(self) -> bool: return False def is_anonymous(self) -> bool: return True de...
Init an API config - this MUST handle being called multiple times and only from the main-thread