id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
141,760 | import atexit
import sys
from importlib.metadata import version
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple
import click
from rich.console import Console
from rich.panel import Panel
from rich.style import Style
from rich.table import Table
from structlog import get_logger
from unb... | null |
141,761 | import itertools
from lark.exceptions import UnexpectedInput
from lark.lark import Lark
from lark.visitors import Transformer
_hex_string_parser = Lark(
"""
%import common.HEXDIGIT
%import common.NUMBER
%import common.NEWLINE
%import common.WS
%ignore WS
COMMENT: "//" /(.)+/ NEWLINE?
%i... | null |
141,762 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | bit-wise reading of file in little-endian mode. |
141,763 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Round down size to the alignment boundary. |
141,764 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Convert 2 byte integer to a Python int. |
141,765 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | null |
141,766 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Iterate on the file searching for pattern until all occurences has been found. Seek the file pointer to the next byte of where we found the pattern or seek back to the initial position when the iterator is exhausted. |
141,767 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Scan the whole file by increment of DEFAULT_BUFSIZE using Hyperscan's streaming mode. |
141,768 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Read a four bytes magic and derive endianness from it. It compares the read data with the big endian magic. It reads four bytes and seeks back after that. |
141,769 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Read a four bytes magic and derive endianness from it. It compares the read data with the big endian magic. It reads four bytes and seeks back after that. |
141,770 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Make absolute paths relative by chopping off the root. |
141,771 | import enum
import functools
import hashlib
import io
import math
import mmap
import os
import re
import shutil
import struct
import unicodedata
from pathlib import Path
from typing import Iterable, Iterator, List, Literal, Optional, Tuple, Union
from dissect.cstruct import Instance, cstruct
from structlog import get_l... | Make a human readable, safe path. |
141,772 | import errno
import os
from pathlib import Path
from typing import Union
from structlog import get_logger
from .file_utils import carve, is_safe_path
from .models import Chunk, File, PaddingChunk, TaskResult, UnknownChunk, ValidChunk
from .report import MaliciousSymlinkRemoved
def fix_permission(path: Path):
if not... | null |
141,773 | import errno
import os
from pathlib import Path
from typing import Union
from structlog import get_logger
from .file_utils import carve, is_safe_path
from .models import Chunk, File, PaddingChunk, TaskResult, UnknownChunk, ValidChunk
from .report import MaliciousSymlinkRemoved
logger = get_logger()
def carve_chunk_to_f... | null |
141,774 | import errno
import os
from pathlib import Path
from typing import Union
from structlog import get_logger
from .file_utils import carve, is_safe_path
from .models import Chunk, File, PaddingChunk, TaskResult, UnknownChunk, ValidChunk
from .report import MaliciousSymlinkRemoved
logger = get_logger()
def carve_chunk_to_f... | null |
141,775 | from typing import List, Type
import pluggy
from unblob.models import DirectoryHandler, Handler
class Handler(abc.ABC):
"""A file type handler is responsible for searching, validating and "unblobbing" files from Blobs."""
NAME: str
PATTERNS: List[Pattern]
# We need this, because not every match reflec... | Register handler types to known handlers. :returns: The list of handlers to be registered |
141,776 | from typing import List, Type
import pluggy
from unblob.models import DirectoryHandler, Handler
class DirectoryHandler(abc.ABC):
"""A directory type handler is responsible for searching, validating and "unblobbing" files from multiple files in a directory."""
NAME: str
EXTRACTOR: DirectoryExtractor
... | Register directory handler types to known handlers. :returns: The list of directory handlers to be registered |
141,777 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | null |
141,778 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | null |
141,779 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | null |
141,780 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | Remove all chunks from the list which are within another bigger chunks. |
141,781 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | Calculate the empty gaps between chunks. |
141,782 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | Calculate and log shannon entropy divided by 8 for the file in chunks. Shannon entropy returns the amount of information (in bits) of some numeric sequence. We calculate the average entropy of byte chunks, which in theory can contain 0-8 bits of entropy. We normalize it for visualization to a 0-100% scale, to make it e... |
141,783 | import multiprocessing
import shutil
from operator import attrgetter
from pathlib import Path
from typing import Iterable, List, Optional, Sequence, Set, Tuple, Type, Union
import attr
import magic
import plotext as plt
from structlog import get_logger
from unblob_native import math_tools as mt
from unblob.handlers imp... | null |
141,784 | import hashlib
import os
import stat
import traceback
from enum import Enum
from pathlib import Path
from typing import List, Optional, Set, Union, final
import attr
def _convert_exception_to_str(obj: Union[str, Exception]) -> str:
if isinstance(obj, str):
return obj
if isinstance(obj, Exception):
... | null |
141,785 | import functools
import signal
from structlog import get_logger
logger = get_logger()
class ShutDownRequired(BaseException):
def __init__(self, signal: str):
super().__init__()
self.signal = signal
def terminate_gracefully(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
... | null |
141,786 | import abc
import multiprocessing as mp
import os
import queue
import sys
import threading
from multiprocessing.queues import JoinableQueue
from typing import Any, Callable, Union
from .logging import multiprocessing_breakpoint
_SENTINEL = _Sentinel
def multiprocessing_breakpoint():
"""Call this in Process forks i... | null |
141,787 | import functools
import click
)
def decorator(*args, **kwargs):
return func(*args, **kwargs)
return decorator
def verbosity_option(func):
@click.option(
"-v",
"--verbose",
count=True,
help="Verbosity level, counting, maximum level: 3 (use: -v, -vv, -vvv)",
)
... | null |
141,788 | import itertools
from typing import List
def pairwise(iterable):
# Copied from Python 3.10
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
The provided code snippet includes necessary dependencies for implementing the `get_intervals` functio... | Get all the intervals between numbers. It's similar to numpy.diff function. Example: ------- >>> get_intervals([1, 4, 5, 6, 10]) [3, 1, 1, 4] |
141,789 | import platform
import getpass
USERNAME = getpass.getuser()
OPERATING_SYSTEM = platform.system()
PYTHON_VERSION = platform.python_version()
def USER_MESSAGE(goal, current_dir): return f"""(USER: {USERNAME})
(DIRECTORY: {current_dir})
Write {OPERATING_SYSTEM} python {PYTHON_VERSION} code so I can achieve my goal by run... | null |
141,790 | import platform
import getpass
def DEBUG_MESSAGE(code, error):
return f"""```python
{code}
```
The above code returns the error "{error}". Please briefly explain why the error is happening, then write the corrected code.""" # CoT prompting improves debugging | null |
141,791 | from openai import OpenAI
import time
from colorama import Fore, Style
import os
import sys
from prompts import *
from keys import *
import subprocess
import io
import contextlib
import platform
import traceback
def print_console_prompt():
def print_success(status):
print_console_prompt()
print(Style.RESET_ALL... | null |
141,792 | from openai import OpenAI
import time
from colorama import Fore, Style
import os
import sys
from prompts import *
from keys import *
import subprocess
import io
import contextlib
import platform
import traceback
def print_console_prompt():
print(engshell_PREVIX(), end="")
def print_err(status):
print_console_p... | null |
141,793 | from openai import OpenAI
import time
from colorama import Fore, Style
import os
import sys
from prompts import *
from keys import *
import subprocess
import io
import contextlib
import platform
import traceback
def print_console_prompt():
def print_code(status):
print_console_prompt()
print(Style.RESET_ALL + ... | null |
141,794 | from openai import OpenAI
import time
from colorama import Fore, Style
import os
import sys
from prompts import *
from keys import *
import subprocess
import io
import contextlib
import platform
import traceback
MAX_DEBUG_ATTEMPTS = 3
RETRY_ERRORS = ["The server had an error while processing your request. Sorry about t... | null |
141,795 | from openai import OpenAI
import time
from colorama import Fore, Style
import os
import sys
from prompts import *
from keys import *
import subprocess
import io
import contextlib
import platform
import traceback
memory = []
def clear_memory():
global memory
memory = [
{"role": "system", "content": ... | null |
141,796 | import pathlib
from pathlib import Path
def generate_img_tag(file):
return f'<a href="https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/{file.name}"><img src="https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/{file.name}" alt="{file.stem}" height="50"></a>' | null |
141,797 | import time, _thread, machine
def task(n, delay):
led = machine.Pin("LED", machine.Pin.OUT)
for i in range(n):
led.high()
time.sleep(delay)
led.low()
time.sleep(delay)
print('done') | null |
141,798 | from machine import Pin, Timer
led = Pin("LED", Pin.OUT)
def tick(timer):
global led
led.toggle() | null |
141,799 | import array, time
from machine import Pin
import rp2
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() ... | null |
141,800 | import time
import rp2
from machine import Pin
def blink():
wrap_target()
set(pins, 1) [31]
nop() [31]
nop() [31]
nop() [31]
nop() [31]
set(pins, 0) [31]
nop() [31]
nop() [31]
nop() [31]
nop() [31]
... | null |
141,801 | import time
from machine import Pin
import rp2
def prog():
pass | null |
141,802 | import time
from machine import Pin
import rp2
def wait_pin_low():
wrap_target()
wait(0, pin, 0)
irq(block, rel(0))
wait(1, pin, 0)
wrap() | null |
141,803 | import time
from machine import Pin
import rp2
def handler(sm):
# Print a (wrapping) timestamp, and the state machine object.
print(time.ticks_ms(), sm) | null |
141,804 | from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
def uart_tx():
# Block with TX deasserted until data available
pull()
# Initialise bit counter, assert start bit for 8 cycles
set(x, 7) .side(0) [7]
# Shift out 8 data bits, 8 execution cycles per bit
label("bitloop")
... | null |
141,805 | from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
def pio_uart_print(sm, s):
for c in s:
sm.put(ord(c)) | null |
141,807 | import array, time
from machine import Pin
import rp2
ar = array.array("I", [0 for _ in range(NUM_LEDS)])
def pixels_set(i, color):
ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
def pixels_fill(color):
for i in range(len(ar)):
pixels_set(i, color) | null |
141,808 | import array, time
from machine import Pin
import rp2
NUM_LEDS = 16
def pixels_show():
def pixels_set(i, color):
def color_chase(color, wait):
for i in range(NUM_LEDS):
pixels_set(i, color)
time.sleep(wait)
pixels_show()
time.sleep(0.2) | null |
141,809 | import array, time
from machine import Pin
import rp2
NUM_LEDS = 16
def pixels_show():
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
... | null |
141,810 | import rp2
from machine import Pin
def spi_cpha0():
# Note X must be preinitialised by setup code before first byte, we reload after sending each byte
# Would normally do this via exec() but in this case it's in the instruction memory and is only run once
set(x, 6)
# Actual program body follows
wra... | null |
141,811 | import time
from machine import Pin
import rp2
def blink_1hz():
# Cycles: 1 + 1 + 6 + 32 * (30 + 1) = 1000
irq(rel(0))
set(pins, 1)
set(x, 31) [5]
label("delay_high")
nop() [29]
jmp(x_dec, "delay_high")
# Cycles: 1 + 7 + 32 * (30 + 1) = 1000
s... | null |
141,812 | from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
from time import sleep
def pwm_prog():
pull(noblock) .side(0)
mov(x, osr) # Keep most recent pull data stashed in X, for recycling by noblock
mov(y, isr) # ISR must be preloaded with PWM count max
label("pwmloop")
jmp(x_not_y, "skip... | null |
141,813 | import time
import rp2
def irq_test():
wrap_target()
nop() [31]
nop() [31]
nop() [31]
nop() [31]
irq(0)
nop() [31]
nop() [31]
nop() [31]
nop() [31]
irq(1)
wrap() | null |
141,814 | import bluetooth
import random
import struct
import time
import micropython
from ble_advertising import decode_services, decode_name
from micropython import const
from machine import Pin
def sleep_ms_flash_led(self, flash_count, delay_ms):
self._led.off()
while(delay_ms > 0):
for i in range(flash_count)... | null |
141,815 | import bluetooth
import random
import struct
import time
import machine
import ubinascii
from ble_advertising import advertising_payload
from micropython import const
from machine import Pin
class BLETemperature:
def __init__(self, ble, name=""):
self._sensor_temp = machine.ADC(4)
self._ble = ble
... | null |
141,816 | from micropython import const
import struct
import bluetooth
def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):
payload = bytearray()
def _append(adv_type, value):
nonlocal payload
payload += struct.pack("BB", len(value) + 1, adv_type) + value
... | null |
141,817 | import logging
import re
from typing import Any, List, Set, Tuple, Type
from jinja2.exceptions import TemplateError
from langroid.language_models.base import LanguageModel, LLMMessage, Role
from langroid.language_models.config import HFPromptFormatterConfig
from langroid.language_models.prompt_formatter.base import Pro... | null |
141,818 | import asyncio
import logging
import random
import time
from typing import Any, Callable, Dict, List
import aiohttp
import openai
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
The provided code snippet includes necessary dependencies for implementing the `retry_with_exponential_... | Retry a function with exponential backoff. |
141,819 | import asyncio
import logging
import random
import time
from typing import Any, Callable, Dict, List
import aiohttp
import openai
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
The provided code snippet includes necessary dependencies for implementing the `async_retry_with_expone... | Retry a function with exponential backoff. |
141,820 | import ast
import hashlib
import json
import logging
import os
import sys
import warnings
from enum import Enum
from functools import cache
from itertools import chain
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
no_type_check,
)
import openai
from ht... | null |
141,821 | import ast
import hashlib
import json
import logging
import os
import sys
import warnings
from enum import Enum
from functools import cache
from itertools import chain
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
no_type_check,
)
import openai
from ht... | Does nothing. |
141,822 | import ast
import hashlib
import json
import logging
import os
import sys
import warnings
from enum import Enum
from functools import cache
from itertools import chain
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
no_type_check,
)
import openai
from ht... | Logging function for litellm |
141,823 | import ast
import asyncio
import json
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import aiohttp
from pydantic import BaseModel, BaseSettings, Field
from langroid.cachedb.momento_cachedb... | null |
141,824 | import os
from typing import Callable, List
import tiktoken
from dotenv import load_dotenv
from openai import OpenAI
from langroid.embedding_models.base import EmbeddingModel, EmbeddingModelsConfig
from langroid.mytypes import Embeddings
from langroid.parsing.utils import batched
class OpenAIEmbeddings(EmbeddingModel):... | Args: embedding_fn_type: "openai" or "sentencetransformer" # others soon Returns: EmbeddingModel |
141,825 | import asyncio
from typing import List, Tuple
import aiohttp
from langroid.language_models.base import LanguageModel
from langroid.mytypes import Document
from langroid.prompts.dialog import collate_chat_history
from langroid.prompts.templates import EXTRACTION_PROMPT
async def _get_verbatim_extracts(
question: str... | From each passage, extract verbatim text that is relevant to a question, using concurrent API calls to the LLM. Args: question: question to be answered passages: list of passages from which to extract relevant verbatim text LLM: LanguageModel to use for generating the prompt and extract Returns: list of verbatim extrac... |
141,826 | import asyncio
from typing import List, Tuple
import aiohttp
from langroid.language_models.base import LanguageModel
from langroid.mytypes import Document
from langroid.prompts.dialog import collate_chat_history
from langroid.prompts.templates import EXTRACTION_PROMPT
class LanguageModel(ABC):
"""
Abstract bas... | Given a chat history and a question, convert it to a standalone question. Args: chat_history: list of tuples of (question, answer) query: follow-up question Returns: standalone version of the question |
141,827 | import hashlib
import json
import logging
import os
import uuid
from typing import List, Optional, Sequence, Tuple, TypeVar
from dotenv import load_dotenv
from qdrant_client import QdrantClient
from qdrant_client.conversions.common_types import ScoredPoint
from qdrant_client.http.models import (
Batch,
Collecti... | null |
141,828 | import hashlib
import json
import logging
import os
import uuid
from typing import List, Optional, Sequence, Tuple, TypeVar
from dotenv import load_dotenv
from qdrant_client import QdrantClient
from qdrant_client.conversions.common_types import ScoredPoint
from qdrant_client.http.models import (
Batch,
Collecti... | Check if a given string is a valid UUID. |
141,829 | import asyncio
import copy
import inspect
from typing import Any, Callable, Coroutine, List
from dotenv import load_dotenv
from rich.console import Console
from langroid.agent.base import Agent
from langroid.agent.chat_document import ChatDocument
from langroid.agent.task import Task
from langroid.utils.configuration i... | Run copies of `task` async/concurrently one per item in `items` list. For each item, apply `input_map` to get the initial message to process. For each result, apply `output_map` to get the final result. Args: task (Task): task to run items (List[Any]): list of items to process input_map (Callable[[Any], str|ChatDocumen... |
141,830 | import asyncio
import copy
import inspect
from typing import Any, Callable, Coroutine, List
from dotenv import load_dotenv
from rich.console import Console
from langroid.agent.base import Agent
from langroid.agent.chat_document import ChatDocument
from langroid.agent.task import Task
from langroid.utils.configuration i... | null |
141,831 | import asyncio
import copy
import inspect
from typing import Any, Callable, Coroutine, List
from dotenv import load_dotenv
from rich.console import Console
from langroid.agent.base import Agent
from langroid.agent.chat_document import ChatDocument
from langroid.agent.task import Task
from langroid.utils.configuration i... | null |
141,832 | import json
import logging
import textwrap
from typing import Any, Callable, Dict, List, Literal, Optional, no_type_check
from pydantic import BaseSettings
from chainlit import run_sync
from chainlit.config import config
from chainlit.logger import logger
import langroid as lr
import langroid.language_models as lm
from... | null |
141,833 | import json
import logging
import textwrap
from typing import Any, Callable, Dict, List, Literal, Optional, no_type_check
from pydantic import BaseSettings
from chainlit import run_sync
from chainlit.config import config
from chainlit.logger import logger
import langroid as lr
import langroid.language_models as lm
from... | null |
141,834 | import json
import logging
import textwrap
from typing import Any, Callable, Dict, List, Literal, Optional, no_type_check
from pydantic import BaseSettings
from chainlit import run_sync
from chainlit.config import config
from chainlit.logger import logger
import langroid as lr
import langroid.language_models as lm
from... | Wrap text preserving paragraph breaks. Typically used to format an agent_response output, which may have long lines with no newlines or paragraph breaks. |
141,835 | from __future__ import annotations
import copy
import logging
import re
from collections import Counter
from types import SimpleNamespace
from typing import (
Any,
Callable,
Coroutine,
Dict,
List,
Optional,
Set,
Tuple,
Type,
cast,
)
from rich import print
from rich.markup import ... | null |
141,836 | from typing import List, Optional
import pandas as pd
import typer
from rich.console import Console
from langroid.agent.special.neo4j.neo4j_chat_agent import (
Neo4jChatAgent,
Neo4jChatAgentConfig,
)
from langroid.agent.tool_message import ToolMessage
from langroid.language_models.openai_gpt import OpenAIChatMo... | Preprocess a DataFrame for Neo4j import by fixing mismatched quotes in string columns and handling null or missing values. Args: df (DataFrame): The DataFrame to be preprocessed. default_value (str, optional): The default value to replace null values. This is ignored if remove_null_rows is True. Defaults to None. remov... |
141,837 | from typing import Any, Dict, List, Optional
from sqlalchemy import inspect, text
from sqlalchemy.engine import Engine
def extract_postgresql_descriptions(
engine: Engine,
multi_schema: bool = False,
) -> Dict[str, Dict[str, Any]]:
"""
Extracts descriptions for tables and columns from a PostgreSQL datab... | Extracts the schema descriptions from the database connected to by the engine. Args: engine (Engine): SQLAlchemy engine instance. multi_schema (bool): Generate descriptions for all schemas in the database. Returns: Dict[str, Dict[str, Any]]: A dictionary representation of table and column descriptions. |
141,838 | import logging
from langroid.agent.chat_agent import ChatAgent
from langroid.agent.chat_document import ChatDocument
from langroid.agent.special.lance_rag.query_planner_agent import (
LanceQueryPlanAgentConfig,
)
from langroid.agent.special.lance_tools import (
QueryPlanAnswerTool,
QueryPlanFeedbackTool,
)
... | null |
141,839 | import io
import logging
import sys
from typing import List, Optional, no_type_check
import numpy as np
import pandas as pd
from rich.console import Console
import langroid as lr
from langroid.agent import ChatDocument
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.tool_message imp... | Generate a structured summary for a pandas DataFrame containing numerical and categorical values. Args: df (pd.DataFrame): The input DataFrame to summarize. Returns: str: A nicely structured and formatted summary string. |
141,840 | import asyncio
import inspect
import json
import logging
from abc import ABC
from contextlib import ExitStack
from types import SimpleNamespace
from typing import (
Any,
Callable,
Coroutine,
Dict,
List,
Optional,
Set,
Tuple,
Type,
cast,
no_type_check,
)
from pydantic import B... | null |
141,841 | import json
import re
from typing import Any, Iterator, List
from pyparsing import nestedExpr, originalTextFor
The provided code snippet includes necessary dependencies for implementing the `flatten` function. Write a Python function `def flatten(nested_list) -> Iterator[str]` to solve the following problem:
Flatten a... | Flatten a nested list into a single list of strings |
141,842 | import json
import re
from typing import Any, Iterator, List
from pyparsing import nestedExpr, originalTextFor
def extract_top_level_json(s: str) -> List[str]:
"""Extract all top-level JSON-formatted substrings from a given string.
Args:
s (str): The input string to search for JSON substrings.
Retur... | Extract the value of a field f from a top-level JSON object. If there are multiple, just return the first. Args: s (str): The input string to search for JSON substrings. f (str): The field to extract from the JSON object. Returns: str: The value of the field f in the top-level JSON object, if any. Otherwise, return an ... |
141,843 | from typing import Tuple, no_type_check
from pyparsing import Empty, Literal, ParseException, SkipTo, StringEnd, Word, alphanums
The provided code snippet includes necessary dependencies for implementing the `parse_message` function. Write a Python function `def parse_message(msg: str) -> Tuple[str, str]` to solve the... | Parse the intended recipient and content of a message. Message format is assumed to be TO[<recipient>]:<message>. The TO[<recipient>]: part is optional. Args: msg (str): message to parse Returns: str, str: task-name of intended recipient, and content of message (if recipient is not specified, task-name is empty string) |
141,844 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | Batch data into tuples of length n. The last batch may be shorter. |
141,845 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | null |
141,846 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | null |
141,847 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | null |
141,848 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | Strip any leading and trailing whitespaces from the input text beyond length k. This is useful for removing leading/trailing whitespaces from a text while preserving paragraph structure. Args: s (str): The input text. k (int): The number of leading and trailing whitespaces to retain. Returns: str: The text with leading... |
141,849 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | Remove extra whitespace from the input text, while preserving paragraph structure. |
141,850 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | Extract specified segments from a numbered text, preserving paragraph structure. Args: s (str): The input text containing numbered segments. specs (str): A string containing segment numbers and/or ranges (e.g., "3,5,7-10"). Returns: str: Extracted segments, keeping original paragraph structures. Example: >>> text = "(1... |
141,851 | import difflib
import logging
import random
import re
from functools import cache
from itertools import islice
from typing import Any, Iterable, List
import nltk
from faker import Faker
from langroid.mytypes import Document
from langroid.parsing.parser import Parser, ParsingConfig
from langroid.parsing.repo_loader impo... | Extract the content from a file path or URL, or a list of file paths or URLs. Args: path (str | List[str]): The file path or URL, or a list of file paths or URLs. parsing (ParsingConfig): The parsing configuration. Returns: str | List[str]: The extracted content if a single file path or URL is provided, or a list of ex... |
141,852 | import os
from typing import Dict, List
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from duckduckgo_search import DDGS
from googleapiclient.discovery import Resource, build
from requests.models import Response
class WebSearchResult:
def __init__(
self,
title... | null |
141,853 | import os
from typing import Dict, List
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from duckduckgo_search import DDGS
from googleapiclient.discovery import Resource, build
from requests.models import Response
class WebSearchResult:
"""
Class representing a Web Search result, co... | Method that makes an API call by Metaphor client that queries the top num_results links that matches the query. Returns a list of WebSearchResult objects. Args: query (str): The query body that users wants to make. num_results (int): Number of top matching results that we want to grab |
141,854 | import os
from typing import Dict, List
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from duckduckgo_search import DDGS
from googleapiclient.discovery import Resource, build
from requests.models import Response
class WebSearchResult:
"""
Class representing a Web Search result, co... | Method that makes an API call by DuckDuckGo client that queries the top `num_results` links that matche the query. Returns a list of WebSearchResult objects. Args: query (str): The query body that users wants to make. num_results (int): Number of top matching results that we want to grab |
141,855 | import re
from typing import Callable, List
from bs4 import BeautifulSoup
def remove_extra_whitespace(s: str) -> str:
lines = s.split("\n")
cleaned_lines = [" ".join(line.split()) for line in lines]
return "\n".join(cleaned_lines) | null |
141,856 | import re
from typing import Callable, List
from bs4 import BeautifulSoup
def custom_sent_tokenize(text: str) -> List[str]:
sentences = [
sentence.strip()
for sentence in re.split(r"\.\s|\.\n", text)
if sentence.strip()
]
# append a period if the sentence does not end with one
re... | null |
141,857 | import logging
import os
import tempfile
import urllib.parse
import urllib.robotparser
from typing import List, Optional, Set, Tuple
from urllib.parse import urldefrag, urljoin, urlparse
import fire
import requests
from bs4 import BeautifulSoup
from pydantic import BaseModel, HttpUrl, ValidationError, parse_obj_as
from... | Fetch content from the given URL and save it to a temporary local file. Args: url (str): The URL of the content to fetch. Returns: str: The path to the temporary file where the content is saved. Raises: HTTPError: If there's any issue fetching the content. |
141,858 | import logging
import os
import tempfile
import urllib.parse
import urllib.robotparser
from typing import List, Optional, Set, Tuple
from urllib.parse import urldefrag, urljoin, urlparse
import fire
import requests
from bs4 import BeautifulSoup
from pydantic import BaseModel, HttpUrl, ValidationError, parse_obj_as
from... | Prompt the user for input. Args: msg: printed prompt color: color of the prompt Returns: user input |
141,859 | import logging
import os
import tempfile
import urllib.parse
import urllib.robotparser
from typing import List, Optional, Set, Tuple
from urllib.parse import urldefrag, urljoin, urlparse
import fire
import requests
from bs4 import BeautifulSoup
from pydantic import BaseModel, HttpUrl, ValidationError, parse_obj_as
from... | Prompt the user for inputs. Args: prompt: printed prompt n: how many inputs to prompt for. If None, then prompt until done, otherwise quit after n inputs. Returns: list of input strings |
141,860 | import logging
import os
import tempfile
import urllib.parse
import urllib.robotparser
from typing import List, Optional, Set, Tuple
from urllib.parse import urldefrag, urljoin, urlparse
import fire
import requests
from bs4 import BeautifulSoup
from pydantic import BaseModel, HttpUrl, ValidationError, parse_obj_as
from... | Crawl starting at the url and return a list of URLs to be parsed, up to a maximum of `max_urls`. This has not been tested to work as intended. Ignore. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.