code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def __GetLineString(this, data):
"""Turns the given list of bytes into a finished string"""
if (data is None):
return None
string = ""
i = 0
while (i < len(data)):
# Cast 2 bytes to figure out what to do next
value = struct.unpack_from("<H", data, i)[0]
if (value == this.__KEY_TERMINATOR):
br... | Turns the given list of bytes into a finished string | __GetLineString | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __MakeLabelHash(this, f):
"""Returns the label name and a FNV1_64 hash"""
# Next 8 bytes is the hash of the label name
hash = struct.unpack("<Q", f.read(8))[0]
# Next 2 bytes is the label"s name length
nameLength = struct.unpack("<H", f.read(2))[0]
# Read the bytes until 0x0 is found
name = this.__Rea... | Returns the label name and a FNV1_64 hash | __MakeLabelHash | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __ReadUntil(this, f, value):
"""Reads the given file until it reaches the given value"""
string = ""
c = f.read(1)
end = bytes([value])
while (c != end):
# Read one byte at a time to get each character
string += c.decode("utf-8")
c = f.read(1)
return string | Reads the given file until it reaches the given value | __ReadUntil | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def call_phone_number(input: str) -> str:
"""calls a phone number as a bot and returns a transcript of the conversation.
the input to this tool is a pipe separated list of a phone number, a prompt, and the first thing the bot should say.
The prompt should instruct the bot with what to do on the call and be ... | calls a phone number as a bot and returns a transcript of the conversation.
the input to this tool is a pipe separated list of a phone number, a prompt, and the first thing the bot should say.
The prompt should instruct the bot with what to do on the call and be in the 3rd person,
like 'the assistant is per... | call_phone_number | python | vocodedev/vocode-core | apps/langchain_agent/tools/vocode.py | https://github.com/vocodedev/vocode-core/blob/master/apps/langchain_agent/tools/vocode.py | MIT |
async def respond(
self,
human_input: str,
conversation_id: str,
is_interrupt: bool = False,
) -> Tuple[Optional[str], bool]:
"""Generates a response from the SpellerAgent.
The response is generated by joining each character in the human input with a space.
T... | Generates a response from the SpellerAgent.
The response is generated by joining each character in the human input with a space.
The second element of the tuple indicates whether the agent should stop (False means it should not stop).
Args:
human_input (str): The input from the hum... | respond | python | vocodedev/vocode-core | apps/telephony_app/speller_agent.py | https://github.com/vocodedev/vocode-core/blob/master/apps/telephony_app/speller_agent.py | MIT |
def create_agent(self, agent_config: AgentConfig) -> BaseAgent:
"""Creates an agent based on the provided agent configuration.
Args:
agent_config (AgentConfig): The configuration for the agent to be created.
Returns:
BaseAgent: The created agent.
Raises:
... | Creates an agent based on the provided agent configuration.
Args:
agent_config (AgentConfig): The configuration for the agent to be created.
Returns:
BaseAgent: The created agent.
Raises:
Exception: If the agent configuration type is not recognized.
... | create_agent | python | vocodedev/vocode-core | apps/telephony_app/speller_agent.py | https://github.com/vocodedev/vocode-core/blob/master/apps/telephony_app/speller_agent.py | MIT |
def get_metrics_data(self):
"""Reads and returns current metrics from the SDK"""
with self._lock:
self.collect()
metrics_data = self._metrics_data
self._metrics_data = None
return metrics_data | Reads and returns current metrics from the SDK | get_metrics_data | python | vocodedev/vocode-core | playground/streaming/tracing_utils.py | https://github.com/vocodedev/vocode-core/blob/master/playground/streaming/tracing_utils.py | MIT |
def default_env_vars() -> dict[str, str]:
"""
Defines default environment variables for the test session.
This fixture provides a dictionary of default environment variables that are
commonly used across tests. It can be overridden in submodule scoped `conftest.py`
files or directly in tests.
... |
Defines default environment variables for the test session.
This fixture provides a dictionary of default environment variables that are
commonly used across tests. It can be overridden in submodule scoped `conftest.py`
files or directly in tests.
:return: A dictionary of default environment vari... | default_env_vars | python | vocodedev/vocode-core | tests/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/conftest.py | MIT |
def mock_env(
monkeypatch: MonkeyPatch, request: pytest.FixtureRequest, default_env_vars: dict[str, str]
) -> Generator[None, None, None]:
"""
Temporarily sets environment variables for testing.
This fixture allows tests to run with a modified set of environment variables,
either using the default ... |
Temporarily sets environment variables for testing.
This fixture allows tests to run with a modified set of environment variables,
either using the default set provided by `default_env_vars` or overridden by
test-specific parameters. It ensures that changes to environment variables do
not leak bet... | mock_env | python | vocodedev/vocode-core | tests/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/conftest.py | MIT |
def default_env_vars(default_env_vars: dict[str, str]) -> dict[str, str]:
"""
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified envir... |
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified environment variables specific to
the submodule.
:param default_env_vars: The... | default_env_vars | python | vocodedev/vocode-core | tests/streaming/action/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/conftest.py | MIT |
def action_config() -> dict:
"""Provides a common action configuration for tests."""
return {
"processing_mode": "muted",
"name": "name",
"description": "A description",
"url": "https://example.com",
"input_schema": json.dumps(ACTION_INPUT_SCHEMA),
"speak_on_send"... | Provides a common action configuration for tests. | action_config | python | vocodedev/vocode-core | tests/streaming/action/test_external_actions.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/test_external_actions.py | MIT |
def execute_action_setup(mocker, action_config) -> ExecuteExternalAction:
"""Common setup for creating an ExecuteExternalAction instance."""
action = ExecuteExternalAction(
action_config=ExecuteExternalActionVocodeActionConfig(**action_config),
)
mocked_requester = mocker.AsyncMock()
mocked_... | Common setup for creating an ExecuteExternalAction instance. | execute_action_setup | python | vocodedev/vocode-core | tests/streaming/action/test_external_actions.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/test_external_actions.py | MIT |
def default_env_vars(default_env_vars: dict[str, str]) -> dict[str, str]:
"""
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified envir... |
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified environment variables specific to
the submodule.
:param default_env_vars: The... | default_env_vars | python | vocodedev/vocode-core | tests/streaming/synthesizer/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/synthesizer/conftest.py | MIT |
def _patched_serialize_record(text: str, record: dict) -> str:
"""
This function takes a text string and a record dictionary as input and returns a serialized
string representation of the record.
The record dictionary is expected to contain various keys related to logging information such as
'level... |
This function takes a text string and a record dictionary as input and returns a serialized
string representation of the record.
The record dictionary is expected to contain various keys related to logging information such as
'level', 'time', 'elapsed', 'exception', 'extra', 'file', 'function', 'line'... | _patched_serialize_record | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def emit(self, record: logging.LogRecord) -> None: # pragma: no cover
"""
Propagates logs to loguru.
:param record: record to log.
"""
try:
level: str | int = logger.level(record.levelname).name
except ValueError:
level = record.levelno
... |
Propagates logs to loguru.
:param record: record to log.
| emit | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_intercepter() -> None:
"""
Configures the logging system to intercept log messages.
This function sets up an InterceptHandler instance as the main handler for the root logger.
It sets the logging level to INFO, meaning that all messages with severity INFO and above will be handled.
I... |
Configures the logging system to intercept log messages.
This function sets up an InterceptHandler instance as the main handler for the root logger.
It sets the logging level to INFO, meaning that all messages with severity INFO and above will be handled.
It then iterates over all the loggers in the ... | configure_intercepter | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_pretty_logging() -> None:
"""
Configures the logging system to output pretty logs.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler t... |
Configures the logging system to output pretty logs.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler that outputs to stdout with
pretty formattin... | configure_pretty_logging | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_json_logging() -> None:
"""
Configures the logging system to output logs in JSON format.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new han... |
Configures the logging system to output logs in JSON format.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler that outputs to stdout with
JSON for... | configure_json_logging | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
async def check_for_idle(self):
"""Asks if human is still on the line if no activity is detected, and terminates the conversation if not."""
await self.initial_message_tracker.wait()
check_human_present_count = 0
check_human_present_threshold = self.agent.get_agent_config().num_check_hum... | Asks if human is still on the line if no activity is detected, and terminates the conversation if not. | check_for_idle | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def broadcast_interrupt(self):
"""Stops all inflight events and cancels all workers that are sending output
Returns true if any events were interrupted - which is used as a flag for the agent (is_interrupt)
"""
async with self.interrupt_lock:
num_interrupts = 0
... | Stops all inflight events and cancels all workers that are sending output
Returns true if any events were interrupted - which is used as a flag for the agent (is_interrupt)
| broadcast_interrupt | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def send_speech_to_output(
self,
message: str,
synthesis_result: SynthesisResult,
stop_event: threading.Event,
seconds_per_chunk: float,
transcript_message: Optional[Message] = None,
started_event: Optional[threading.Event] = None,
):
"""
... |
- Sends the speech chunk by chunk to the output device
- update the transcript message as chunks come in (transcript_message is always provided for non filler audio utterances)
- If the stop_event is set, the output is stopped
- Sets started_event when the first chunk is sent
... | send_speech_to_output | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def _end_of_run_hook(self) -> None:
"""This method is called at the end of the run method. It is optional but intended to be
overridden if needed."""
pass | This method is called at the end of the run method. It is optional but intended to be
overridden if needed. | _end_of_run_hook | python | vocodedev/vocode-core | vocode/streaming/action/end_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/action/end_conversation.py | MIT |
def merge_event_logs(event_logs: List[EventLog]) -> List[EventLog]:
"""Returns a new list of event logs where consecutive bot messages are merged."""
new_event_logs: List[EventLog] = []
idx = 0
while idx < len(event_logs):
bot_messages_buffer: List[Message] = []
current_log = event_logs[... | Returns a new list of event logs where consecutive bot messages are merged. | merge_event_logs | python | vocodedev/vocode-core | vocode/streaming/agent/openai_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/openai_utils.py | MIT |
def split_sentences(text: str) -> List[str]:
"""Splits text into sentences and preserve trailing periods.
Merge sentences that are just numbers, as they are part of lists.
"""
initial_split = text.split(". ")
final_split = []
buffer = ""
for i, sentence in enumerate(initial_split):
... | Splits text into sentences and preserve trailing periods.
Merge sentences that are just numbers, as they are part of lists.
| split_sentences | python | vocodedev/vocode-core | vocode/streaming/agent/streaming_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/streaming_utils.py | MIT |
def num_tokens_from_messages(messages: List[dict], model: str = "gpt-3.5-turbo-0613"):
"""Return the number of tokens used by a list of messages."""
tokenizer_info = get_tokenizer_info(model)
if tokenizer_info is None:
raise NotImplementedError(
f"""num_tokens_from_messages() is not impl... | Return the number of tokens used by a list of messages. | num_tokens_from_messages | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
def tokens_from_dict(encoding: tiktoken.Encoding, d: Dict[str, Any], tokens_per_name: int) -> int:
"""Return the number of OpenAI tokens in a dict."""
num_tokens: int = 0
for key, value in d.items():
if value is None:
continue
if isinstance(value, str):
num_tokens += ... | Return the number of OpenAI tokens in a dict. | tokens_from_dict | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
def num_tokens_from_functions(functions: List[dict] | None, model="gpt-3.5-turbo-0613") -> int:
"""Return the number of tokens used by a list of functions."""
if not functions:
return 0
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
logger.warning("Warning: ... | Return the number of tokens used by a list of functions. | num_tokens_from_functions | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
async def initialize_source(self, room: rtc.Room):
"""Creates the AudioSource that will be used to capture audio frames.
Can only be called once the room has set up its track callbcks
"""
self.room = room
source = rtc.AudioSource(self.sampling_rate, NUM_CHANNELS)
track =... | Creates the AudioSource that will be used to capture audio frames.
Can only be called once the room has set up its track callbcks
| initialize_source | python | vocodedev/vocode-core | vocode/streaming/output_device/livekit_output_device.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/output_device/livekit_output_device.py | MIT |
async def play(self, chunk: bytes):
"""Sends an audio chunk to immediate playback"""
pass | Sends an audio chunk to immediate playback | play | python | vocodedev/vocode-core | vocode/streaming/output_device/rate_limit_interruptions_output_device.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/output_device/rate_limit_interruptions_output_device.py | MIT |
async def listen() -> None:
"""Listen to the websocket for audio data and stream it."""
first_message = True
buffer = bytearray()
while True:
message = await ws.recv()
if "audio" not in message:
... | Listen to the websocket for audio data and stream it. | listen | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def create_speech_uncached(
self,
message: BaseMessage,
chunk_size: int,
is_first_text_chunk: bool = False,
is_sole_text_chunk: bool = False,
):
"""
Ran when doing utterance parsing.
ie: "Hello, my name is foo."
"""
if not self.we... |
Ran when doing utterance parsing.
ie: "Hello, my name is foo."
| create_speech_uncached | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def send_token_to_synthesizer(self, message: LLMToken, chunk_size: int):
"""
Ran when parsing a single chunk of text.
ie: "Hello,"
"""
self.total_chars += len(message.text)
if not self.websocket_listener:
self.websocket_listener = asyncio.create_task(
... |
Ran when parsing a single chunk of text.
ie: "Hello,"
| send_token_to_synthesizer | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def generate_chunks(
play_ht_chunk: bytes,
cut_leading_silence=False,
) -> AsyncGenerator[bytes, None]:
"""Yields chunks of size chunk_size from play_ht_chunk and leaves the remainder in buffer.
If cut_leading_silence is True, does not yield chunks until it... | Yields chunks of size chunk_size from play_ht_chunk and leaves the remainder in buffer.
If cut_leading_silence is True, does not yield chunks until it detects voice.
| generate_chunks | python | vocodedev/vocode-core | vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | MIT |
async def _cut_out_trailing_silence(
trailing_chunk: bytes,
) -> AsyncGenerator[bytes, None]:
"""Yields chunks of size chunk_size from trailing_chunk until it detects silence."""
for buffer_idx, chunk in self._enumerate_by_chunk_size(trailing_chunk, chunk_size):
... | Yields chunks of size chunk_size from trailing_chunk until it detects silence. | _cut_out_trailing_silence | python | vocodedev/vocode-core | vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | MIT |
def __init__(
self,
prefix: Optional[str] = None,
suffix: Optional[str] = None,
) -> None:
"""
Initialize a RedisGenericMessageQueue instance.
This initializes a Redis client and sets the name of the stream.
"""
self.redis: Redis = initialize_redis()
... |
Initialize a RedisGenericMessageQueue instance.
This initializes a Redis client and sets the name of the stream.
| __init__ | python | vocodedev/vocode-core | vocode/streaming/utils/redis.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/redis.py | MIT |
async def publish(self, message: dict) -> None:
"""
Publishes a message to the Redis stream.
Args:
message (dict): The message to be published.
Returns:
None
"""
logger.info(f"[{self.queue_name}] Publishing message: {message}")
try:
... |
Publishes a message to the Redis stream.
Args:
message (dict): The message to be published.
Returns:
None
| publish | python | vocodedev/vocode-core | vocode/streaming/utils/redis.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/redis.py | MIT |
async def process(self, item):
"""
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully and not re-raise it
"""
raise NotImplementedError |
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully and not re-raise it
| process | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
def interrupt(self) -> bool:
"""
Returns True if the event was interruptible and is now interrupted.
"""
if not self.is_interruptible:
return False
self.interruption_event.set()
return True |
Returns True if the event was interruptible and is now interrupted.
| interrupt | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
async def process(self, item: InterruptibleEventType):
"""
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully:
"""
raise NotImplementedError |
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully:
| process | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
def cancel_current_task(self):
"""Free up the resources. That's useful so implementors do not have to implement this but:
- threads tasks won't be able to be interrupted. Hopefully not too much of a big deal
Threads will also get a reference to the interruptible event
- asyncio tasks... | Free up the resources. That's useful so implementors do not have to implement this but:
- threads tasks won't be able to be interrupted. Hopefully not too much of a big deal
Threads will also get a reference to the interruptible event
- asyncio tasks will still have to handle CancelledError ... | cancel_current_task | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
async def generate_from_async_iter_with_lookahead(
async_iter: AsyncIterator[AsyncIteratorGenericType],
lookahead: int,
) -> AsyncGenerator[List[AsyncIteratorGenericType], None]:
"""Yield sliding window lists of length `lookahead + 1` from an async iterator.
If the length of async iterator < lookahead ... | Yield sliding window lists of length `lookahead + 1` from an async iterator.
If the length of async iterator < lookahead + 1, then it should just yield the whole
async iterator as a list.
| generate_from_async_iter_with_lookahead | python | vocodedev/vocode-core | vocode/streaming/utils/__init__.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/__init__.py | MIT |
async def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
namespace: Optional[str] = None,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
t... | Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of ids to associate with the texts.
namespace: Option... | add_texts | python | vocodedev/vocode-core | vocode/streaming/vector_db/pinecone.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/vector_db/pinecone.py | MIT |
async def similarity_search_with_score(
self,
query: str,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look u... | Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search in '' namespace.
Returns:
... | similarity_search_with_score | python | vocodedev/vocode-core | vocode/streaming/vector_db/pinecone.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/vector_db/pinecone.py | MIT |
def __init__(self, func: Callable, *args: Tuple, **kwargs: Dict) -> None:
"""
Constructs all the necessary attributes for the SentryConfiguredContextManager object.
Args:
func (Callable): The function to be executed.
*args (Tuple): The positional arguments to pass to the... |
Constructs all the necessary attributes for the SentryConfiguredContextManager object.
Args:
func (Callable): The function to be executed.
*args (Tuple): The positional arguments to pass to the function.
**kwargs (Dict): The keyword arguments to pass to the function... | __init__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def is_configured(self) -> bool:
"""
Checks if Sentry is configured.
Returns:
bool: True if Sentry is configured, False otherwise.
"""
client = sentry_sdk.Hub.current.client
if client is not None and client.options is not None and "dsn" in client.options:
... |
Checks if Sentry is configured.
Returns:
bool: True if Sentry is configured, False otherwise.
| is_configured | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def __enter__(self) -> Optional[Any]:
"""
Executes the function if Sentry is configured.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
"""
if self.is_configured:
self.result = self.func(*self.args, **self.kwargs)... |
Executes the function if Sentry is configured.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
| __enter__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def __call__(self) -> Optional[Any]:
"""
Executes the function if Sentry is configured, and prints a message if it's not.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
"""
if self.is_configured:
return self.func(... |
Executes the function if Sentry is configured, and prints a message if it's not.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
| __call__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def synthesizer_base_name_if_should_report_to_sentry(
synthesizer: "BaseSynthesizer",
) -> Optional[str]:
"""Returns a synthesizer name if we should report metrics to Sentry for this
kind of synthesizer; else returns None.
"""
return f"synthesizer.{_SYNTHESIZER_NAMES.get(synthesizer.__class__.__qual... | Returns a synthesizer name if we should report metrics to Sentry for this
kind of synthesizer; else returns None.
| synthesizer_base_name_if_should_report_to_sentry | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def HandleRequest(req, method, post_data=None):
"""Sample dynamic HTTP response handler.
Parameters
----------
req : BaseHTTPServer.BaseHTTPRequestHandler
The BaseHTTPRequestHandler that recevied the request
method: str
The HTTP method, either 'HEAD', 'GET', 'POST' as of this writin... | Sample dynamic HTTP response handler.
Parameters
----------
req : BaseHTTPServer.BaseHTTPRequestHandler
The BaseHTTPRequestHandler that recevied the request
method: str
The HTTP method, either 'HEAD', 'GET', 'POST' as of this writing
post_data: str
The HTTP post data receive... | HandleRequest | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def HandleTcp(sock):
"""Handle a TCP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
"""
while True:
try:
data = None
data = sock.recv(1024)
except socket.timeout:
pass
if not ... | Handle a TCP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
| HandleTcp | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def HandleUdp(sock, data, addr):
"""Handle a UDP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
data : str
The data received
addr : tuple
The host and port of the remote peer
"""
if data:
resp = input('\n... | Handle a UDP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
data : str
The data received
addr : tuple
The host and port of the remote peer
| HandleUdp | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def first_packet_new_session(self):
"""Is this the first datagram from this conversation?
Returns:
True if this pair of endpoints hasn't conversed before, else False
"""
# sessions.get returns (dst_ip, dport, pid, comm, dport0, proto) or
# None. We just want dst_ip a... | Is this the first datagram from this conversation?
Returns:
True if this pair of endpoints hasn't conversed before, else False
| first_packet_new_session | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def _validateBlackWhite(self):
"""Validate that only a black or a white list of either type (host or
process) is configured.
Side-effect:
Raises ListenerBlackWhiteList if invalid
"""
msg = None
fmt = 'Cannot specify both %s blacklist and whitelist for port %d... | Validate that only a black or a white list of either type (host or
process) is configured.
Side-effect:
Raises ListenerBlackWhiteList if invalid
| _validateBlackWhite | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def addListener(self, listener):
"""Add a ListenerMeta under the corresponding protocol and port."""
proto = listener.proto
port = listener.port
if not proto in self.protos:
self.protos[proto] = {}
if port in self.protos[proto]:
raise ListenerAlreadyBoun... | Add a ListenerMeta under the corresponding protocol and port. | addListener | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isHidden(self, proto, port):
"""Is this port associated with a listener that is hidden?"""
listener = self.getListenerMeta(proto, port)
return listener.hidden if listener else False | Is this port associated with a listener that is hidden? | isHidden | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def getExecuteCmd(self, proto, port):
"""Get the ExecuteCmd format string specified by the operator.
Args:
proto: The protocol name
port: The port number
Returns:
The format string if applicable
None, otherwise
"""
listener = self... | Get the ExecuteCmd format string specified by the operator.
Args:
proto: The protocol name
port: The port number
Returns:
The format string if applicable
None, otherwise
| getExecuteCmd | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def _isWhiteListMiss(self, thing, whitelist):
"""Check if thing is NOT in whitelist.
Args:
thing: thing to check whitelist for
whitelist: list of entries
Returns:
True if thing is in whitelist
False otherwise, or if there is no whitelist
... | Check if thing is NOT in whitelist.
Args:
thing: thing to check whitelist for
whitelist: list of entries
Returns:
True if thing is in whitelist
False otherwise, or if there is no whitelist
| _isWhiteListMiss | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def _isBlackListHit(self, thing, blacklist):
"""Check if thing is in blacklist.
Args:
thing: thing to check blacklist for
blacklist: list of entries
Returns:
True if thing is in blacklist
False otherwise, or if there is no blacklist
"""
... | Check if thing is in blacklist.
Args:
thing: thing to check blacklist for
blacklist: list of entries
Returns:
True if thing is in blacklist
False otherwise, or if there is no blacklist
| _isBlackListHit | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isProcessWhiteListMiss(self, proto, port, proc):
"""Check if proc is OUTSIDE the process WHITElist for a port.
Args:
proto: The protocol name
port: The port number
proc: The process name
Returns:
False if no listener on this port
... | Check if proc is OUTSIDE the process WHITElist for a port.
Args:
proto: The protocol name
port: The port number
proc: The process name
Returns:
False if no listener on this port
Return value of _isWhiteListMiss otherwise
| isProcessWhiteListMiss | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isProcessBlackListHit(self, proto, port, proc):
"""Check if proc is IN the process BLACKlist for a port.
Args:
proto: The protocol name
port: The port number
proc: The process name
Returns:
False if no listener on this port
Return... | Check if proc is IN the process BLACKlist for a port.
Args:
proto: The protocol name
port: The port number
proc: The process name
Returns:
False if no listener on this port
Return value of _isBlackListHit otherwise
| isProcessBlackListHit | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isHostWhiteListMiss(self, proto, port, host):
"""Check if host is OUTSIDE the process WHITElist for a port.
Args:
proto: The protocol name
port: The port number
host: The process name
Returns:
False if no listener on this port
Ret... | Check if host is OUTSIDE the process WHITElist for a port.
Args:
proto: The protocol name
port: The port number
host: The process name
Returns:
False if no listener on this port
Return value of _isWhiteListMiss otherwise
| isHostWhiteListMiss | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isHostBlackListHit(self, proto, port, host):
"""Check if host is IN the process BLACKlist for a port.
Args:
proto: The protocol name
port: The port number
host: The process name
Returns:
False if no listener on this port
Return va... | Check if host is IN the process BLACKlist for a port.
Args:
proto: The protocol name
port: The port number
host: The process name
Returns:
False if no listener on this port
Return value of _isBlackListHit otherwise
| isHostBlackListHit | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isDistinct(self, prev, bound_ips):
"""Not quite inequality.
Requires list of bound IPs for that IP protocol version and recognizes
when a foreign-destined packet was redirected to localhost or to an IP
occupied by an adapter local to the system to be able to suppress
output ... | Not quite inequality.
Requires list of bound IPs for that IP protocol version and recognizes
when a foreign-destined packet was redirected to localhost or to an IP
occupied by an adapter local to the system to be able to suppress
output of these near-duplicates.
| isDistinct | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def __init__(self, diverter_config, listeners_config, ip_addrs,
logging_level=logging.INFO):
"""Initialize the DiverterBase.
TODO: Replace the sys.exit() calls from this function with exceptions
or some other mechanism appropriate for allowing the user of this class
to ... | Initialize the DiverterBase.
TODO: Replace the sys.exit() calls from this function with exceptions
or some other mechanism appropriate for allowing the user of this class
to programmatically detect and handle these cases in their own way.
This may entail moving configuration parsing to ... | __init__ | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def set_debug_level(self, lvl, labels={}):
"""Enable debug output if necessary, set the debug output level, and
maintain a reference to the dictionary of labels to print when a given
logging level is encountered.
Args:
lvl: An int mask of all debug logging levels
... | Enable debug output if necessary, set the debug output level, and
maintain a reference to the dictionary of labels to print when a given
logging level is encountered.
Args:
lvl: An int mask of all debug logging levels
labels: A dict of int => str assigning names to each ... | set_debug_level | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def pdebug(self, lvl, s):
"""Log only the debug trace messages that have been enabled via
set_debug_level.
Args:
lvl: An int indicating the debug level of this message
s: The mssage
Returns:
None
"""
if self.pdebug_level & lvl:
... | Log only the debug trace messages that have been enabled via
set_debug_level.
Args:
lvl: An int indicating the debug level of this message
s: The mssage
Returns:
None
| pdebug | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def check_privileged(self):
"""UNIXy and Windows-oriented check for superuser privileges.
Returns:
True if superuser, else False
"""
try:
privileged = (os.getuid() == 0)
except AttributeError:
privileged = (ctypes.windll.shell32.IsUserAnAdmin(... | UNIXy and Windows-oriented check for superuser privileges.
Returns:
True if superuser, else False
| check_privileged | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def parse_listeners_config(self, listeners_config):
"""Parse listener config sections.
TODO: Replace the sys.exit() calls from this function with exceptions
or some other mechanism appropriate for allowing the user of this class
to programmatically detect and handle these cases in their... | Parse listener config sections.
TODO: Replace the sys.exit() calls from this function with exceptions
or some other mechanism appropriate for allowing the user of this class
to programmatically detect and handle these cases in their own way.
This may entail modifying fakenet.py.
... | parse_listeners_config | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def build_cmd(self, pkt, pid, comm):
"""Retrieve the ExecuteCmd directive if applicable and build the
command to execute.
Args:
pkt: An fnpacket.PacketCtx or derived object
pid: Process ID associated with the packet
comm: Process name (command) that sent the pac... | Retrieve the ExecuteCmd directive if applicable and build the
command to execute.
Args:
pkt: An fnpacket.PacketCtx or derived object
pid: Process ID associated with the packet
comm: Process name (command) that sent the packet
Returns:
A str that is ... | build_cmd | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def _build_cmd(self, tmpl, pid, comm, src_ip, sport, dst_ip, dport):
"""Build a command based on the template specified in an ExecuteCmd
config directive, applying the parameters as needed.
Accepts individual arguments instead of an fnpacket.PacketCtx so that
the Diverter can test any E... | Build a command based on the template specified in an ExecuteCmd
config directive, applying the parameters as needed.
Accepts individual arguments instead of an fnpacket.PacketCtx so that
the Diverter can test any ExecuteCmd directives at configuration time
without having to synthesize ... | _build_cmd | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def execute_detached(self, execute_cmd):
"""OS-agnostic asynchronous subprocess creation.
Executes the process with the appropriate subprocess.Popen parameters
for UNIXy or Windows platforms to isolate the process from FakeNet-NG
to prevent it from being interrupted by termination of Fa... | OS-agnostic asynchronous subprocess creation.
Executes the process with the appropriate subprocess.Popen parameters
for UNIXy or Windows platforms to isolate the process from FakeNet-NG
to prevent it from being interrupted by termination of FakeNet-NG,
Ctrl-C, etc.
Args:
... | execute_detached | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def parse_diverter_config(self):
"""Parse [Diverter] config section.
Args: N/A
Side-effects:
Diverter members (whitelists, pcap, etc.) initialized.
Returns:
None
"""
# SingleHost vs MultiHost mode
self.network_mode = 'SingleHost' # Defa... | Parse [Diverter] config section.
Args: N/A
Side-effects:
Diverter members (whitelists, pcap, etc.) initialized.
Returns:
None
| parse_diverter_config | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def write_pcap(self, pkt):
"""Writes a packet to the pcap.
Args:
pkt: A fnpacket.PacketCtx or derived object
Returns:
None
Side-effects:
Calls dpkt.pcap.Writer.writekpt to persist the octets
"""
if self.pcap and self.pcap_lock:
... | Writes a packet to the pcap.
Args:
pkt: A fnpacket.PacketCtx or derived object
Returns:
None
Side-effects:
Calls dpkt.pcap.Writer.writekpt to persist the octets
| write_pcap | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def formatPkt(self, pkt, pid, comm):
"""Format a packet analysis log line for DGENPKTV.
Args:
pkt: A fnpacket.PacketCtx or derived object
pid: Process ID associated with the packet
comm: Process executable name
Returns:
A str containing the log l... | Format a packet analysis log line for DGENPKTV.
Args:
pkt: A fnpacket.PacketCtx or derived object
pid: Process ID associated with the packet
comm: Process executable name
Returns:
A str containing the log line
| formatPkt | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def check_should_ignore(self, pkt, pid, comm):
"""Indicate whether a packet should be passed without mangling.
Checks whether the packet matches black and whitelists, or whether it
signifies an FTP Active Mode connection.
Args:
pkt: A fnpacket.PacketCtx or derived object
... | Indicate whether a packet should be passed without mangling.
Checks whether the packet matches black and whitelists, or whether it
signifies an FTP Active Mode connection.
Args:
pkt: A fnpacket.PacketCtx or derived object
pid: Process ID associated with the packet
... | check_should_ignore | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def check_log_icmp(self, crit, pkt):
"""Log an ICMP packet if the header was parsed as ICMP.
Args:
crit: A DivertParms object
pkt: An fnpacket.PacketCtx or derived object
Returns:
None
"""
if (pkt.is_icmp and (not self.running_on_windows or
... | Log an ICMP packet if the header was parsed as ICMP.
Args:
crit: A DivertParms object
pkt: An fnpacket.PacketCtx or derived object
Returns:
None
| check_log_icmp | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def getOriginalDestPort(self, orig_src_ip, orig_src_port, proto):
"""Return original destination port, or None if it was not redirected.
The proxy listener uses this method to obtain and provide port
information to listeners in the taste() callback as an extra hint as to
whether the tra... | Return original destination port, or None if it was not redirected.
The proxy listener uses this method to obtain and provide port
information to listeners in the taste() callback as an extra hint as to
whether the traffic may be appropriate for parsing by that listener.
Args:
... | getOriginalDestPort | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def maybe_redir_ip(self, crit, pkt, pid, comm):
"""Conditionally redirect foreign destination IPs to localhost.
On Linux, this is used only under SingleHost mode.
Args:
crit: DivertParms object
pkt: fnpacket.PacketCtx or derived object
pid: int process ID as... | Conditionally redirect foreign destination IPs to localhost.
On Linux, this is used only under SingleHost mode.
Args:
crit: DivertParms object
pkt: fnpacket.PacketCtx or derived object
pid: int process ID associated with the packet
comm: Process name (co... | maybe_redir_ip | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def maybe_fixup_srcip(self, crit, pkt, pid, comm):
"""Conditionally fix up the source IP address if the remote endpoint
had their connection IP-forwarded.
Check is based on whether the remote endpoint corresponds to a key in
the IP forwarding table.
Args:
crit: Dive... | Conditionally fix up the source IP address if the remote endpoint
had their connection IP-forwarded.
Check is based on whether the remote endpoint corresponds to a key in
the IP forwarding table.
Args:
crit: DivertParms object
pkt: fnpacket.PacketCtx or derived ... | maybe_fixup_srcip | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def maybe_redir_port(self, crit, pkt, pid, comm):
"""Conditionally send packets to the default listener for this proto.
Args:
crit: DivertParms object
pkt: fnpacket.PacketCtx or derived object
pid: int process ID associated with the packet
comm: Process n... | Conditionally send packets to the default listener for this proto.
Args:
crit: DivertParms object
pkt: fnpacket.PacketCtx or derived object
pid: int process ID associated with the packet
comm: Process name (command) that sent the packet
Side-effects:
... | maybe_redir_port | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def maybe_fixup_sport(self, crit, pkt, pid, comm):
"""Conditionally fix up source port if the remote endpoint had their
connection port-forwarded to the default listener.
Check is based on whether the remote endpoint corresponds to a key in
the port forwarding table.
Side-effec... | Conditionally fix up source port if the remote endpoint had their
connection port-forwarded to the default listener.
Check is based on whether the remote endpoint corresponds to a key in
the port forwarding table.
Side-effects:
May mangle the packet by modifying the source ... | maybe_fixup_sport | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def decide_redir_port(self, pkt, bound_ports):
"""Decide whether to redirect a port.
Optimized logic derived by truth table + k-map. See docs/internals.md
for details.
Args:
pkt: fnpacket.PacketCtx or derived object
bound_ports: Set of ports that are bound for t... | Decide whether to redirect a port.
Optimized logic derived by truth table + k-map. See docs/internals.md
for details.
Args:
pkt: fnpacket.PacketCtx or derived object
bound_ports: Set of ports that are bound for this protocol
Returns:
True if the pac... | decide_redir_port | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def addSession(self, pkt):
"""Add a connection to the sessions hash table.
Args:
pkt: fnpacket.PacketCtx or derived object
Returns:
None
"""
session = namedtuple('session', ['dst_ip', 'dport', 'pid',
'comm', 'dpor... | Add a connection to the sessions hash table.
Args:
pkt: fnpacket.PacketCtx or derived object
Returns:
None
| addSession | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def maybeExecuteCmd(self, pkt, pid, comm):
"""Execute any ExecuteCmd associated with this port/listener.
Args:
pkt: fnpacket.PacketCtx or derived object
pid: int process ID associated with the packet
comm: Process name (command) that sent the packet
Returns:... | Execute any ExecuteCmd associated with this port/listener.
Args:
pkt: fnpacket.PacketCtx or derived object
pid: int process ID associated with the packet
comm: Process name (command) that sent the packet
Returns:
None
| maybeExecuteCmd | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def mapProxySportToOrigSport(self, proto, orig_sport, proxy_sport,
is_ssl_encrypted):
"""Maps Proxy initiated source ports to their original source ports.
The Proxy listener uses this method to notify the diverter about the
proxy originated source port for the original source port. ... | Maps Proxy initiated source ports to their original source ports.
The Proxy listener uses this method to notify the diverter about the
proxy originated source port for the original source port. It also
notifies if the packet uses SSL encryption.
Args:
proto: str protocol of... | mapProxySportToOrigSport | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def logNbi(self, sport, nbi, proto, application_layer_proto,
is_ssl_encrypted):
"""Collects the NBIs from all listeners into a dictionary.
All listeners use this method to notify the diverter about any NBI
captured within their scope.
Args:
sport: int port bound... | Collects the NBIs from all listeners into a dictionary.
All listeners use this method to notify the diverter about any NBI
captured within their scope.
Args:
sport: int port bound by listener
nbi: dict NBI captured within the listener
proto: str protocol use... | logNbi | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def prettyPrintNbi(self):
"""Convenience method to print all NBIs in appropriate format upon
fakenet session termination. Called by stop() method of diverter.
"""
banner = r"""
... | Convenience method to print all NBIs in appropriate format upon
fakenet session termination. Called by stop() method of diverter.
| prettyPrintNbi | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def generate_html_report(self):
"""Generates an interactive HTML report containing NBI summary saved
to the main working directory of flare-fakenet-ng. Called by stop() method
of diverter.
"""
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# Inside a P... | Generates an interactive HTML report containing NBI summary saved
to the main working directory of flare-fakenet-ng. Called by stop() method
of diverter.
| generate_html_report | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isProcessBlackListed(self, proto, sport=None, process_name=None, dport=None):
"""Checks if a process is blacklisted.
Expected arguments are either:
- process_name and dport, or
- sport
"""
pid = None
if self.single_host_mode and proto is not None:
... | Checks if a process is blacklisted.
Expected arguments are either:
- process_name and dport, or
- sport
| isProcessBlackListed | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def logNbi(self, sport, nbi, proto, application_layer_proto,
is_ssl_encrypted):
"""Delegate the logging of NBIs to the diverter.
This method forwards the provided NBI information to the logNbi() method
in the underlying diverter object. Called by all listeners to log NBIs.
"... | Delegate the logging of NBIs to the diverter.
This method forwards the provided NBI information to the logNbi() method
in the underlying diverter object. Called by all listeners to log NBIs.
| logNbi | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def mapProxySportToOrigSport(self, proto, orig_sport, proxy_sport,
is_ssl_encrypted):
"""Delegate the mapping of proxy sport to original sport to the
diverter.
This method forwards the provided parameters to the
mapProxySportToOrigSport() method in the underlying diverter ob... | Delegate the mapping of proxy sport to original sport to the
diverter.
This method forwards the provided parameters to the
mapProxySportToOrigSport() method in the underlying diverter object.
Called by ProxyListener to report the mapping between proxy initiated
source port and o... | mapProxySportToOrigSport | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def configure(self, config_dict, portlists=[], stringlists=[], idlists=[]):
"""Parse configuration.
Does three things:
1.) Turn dictionary keys to lowercase
2.) Turn string lists into arrays for quicker access
3.) Expand port range specifications
"""
... | Parse configuration.
Does three things:
1.) Turn dictionary keys to lowercase
2.) Turn string lists into arrays for quicker access
3.) Expand port range specifications
| configure | python | mandiant/flare-fakenet-ng | fakenet/diverters/fnconfig.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnconfig.py | Apache-2.0 |
def _parseIp(self):
"""Parse IP src/dst fields and next-layer fields if recognized."""
if self._is_ip:
self._src_ip0 = self._src_ip = socket.inet_ntoa(self._hdr.src)
self._dst_ip0 = self._dst_ip = socket.inet_ntoa(self._hdr.dst)
self.proto = self.handled_protocols.get... | Parse IP src/dst fields and next-layer fields if recognized. | _parseIp | python | mandiant/flare-fakenet-ng | fakenet/diverters/fnpacket.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnpacket.py | Apache-2.0 |
def _calcCsums(self):
"""The roundabout dance of inducing dpkt to recalculate checksums..."""
self._hdr.sum = 0
self._hdr.data.sum = 0
# This has the side-effect of invoking dpkt.in_cksum() et al:
str(self._hdr) | The roundabout dance of inducing dpkt to recalculate checksums... | _calcCsums | python | mandiant/flare-fakenet-ng | fakenet/diverters/fnpacket.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnpacket.py | Apache-2.0 |
def _iptables_format(self, chain, iface, argfmt):
"""Format iptables command line with optional interface restriction.
Parameters
----------
chain : string
One of 'OUTPUT', 'POSTROUTING', 'INPUT', or 'PREROUTING', used for
deciding the correct flag (-i versus -o)... | Format iptables command line with optional interface restriction.
Parameters
----------
chain : string
One of 'OUTPUT', 'POSTROUTING', 'INPUT', or 'PREROUTING', used for
deciding the correct flag (-i versus -o)
iface : string or NoneType
Name of inter... | _iptables_format | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
def start(self, timeout_sec=0.5):
"""Binds to the netfilter queue number specified in the ctor, obtains
the netlink socket, sets a timeout of <timeout_sec>, and starts the
thread procedure which checks _stopflag every time the netlink socket
times out.
"""
# Execute ipta... | Binds to the netfilter queue number specified in the ctor, obtains
the netlink socket, sets a timeout of <timeout_sec>, and starts the
thread procedure which checks _stopflag every time the netlink socket
times out.
| start | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
def parse(self, multi=False, max_col=None):
"""Rip through the file and call cb to extract field(s).
Specify multi if you want to collect an aray instead of exiting the
first time the callback returns anything.
Only specify max_col if you are uncertain that the maximum column
n... | Rip through the file and call cb to extract field(s).
Specify multi if you want to collect an aray instead of exiting the
first time the callback returns anything.
Only specify max_col if you are uncertain that the maximum column
number you will access may exist. For procfs files, this... | parse | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
def linux_get_current_nfnlq_bindings(self):
"""Determine what NFQUEUE queue numbers (if any) are already bound by
existing libnfqueue client processes.
Although iptables rules may exist specifying other queues in addition
to these, the netfilter team does not support using libiptc (such... | Determine what NFQUEUE queue numbers (if any) are already bound by
existing libnfqueue client processes.
Although iptables rules may exist specifying other queues in addition
to these, the netfilter team does not support using libiptc (such as
via python-iptables) to detect that conditi... | linux_get_current_nfnlq_bindings | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
def linux_iptables_redir_iface(self, iface):
"""Linux-specific iptables processing for interface-based redirect
rules.
returns:
tuple(bool, list(IptCmdTemplate))
Status of the operation and any successful iptables rules that will
need to be undone.
""... | Linux-specific iptables processing for interface-based redirect
rules.
returns:
tuple(bool, list(IptCmdTemplate))
Status of the operation and any successful iptables rules that will
need to be undone.
| linux_iptables_redir_iface | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
def linux_remove_iptables_rules(self, rules):
"""Execute the iptables command to remove each rule that was
successfully added.
"""
failed = []
for rule in rules:
ret = rule.remove()
if ret != 0:
failed.append(rule)
return failed | Execute the iptables command to remove each rule that was
successfully added.
| linux_remove_iptables_rules | python | mandiant/flare-fakenet-ng | fakenet/diverters/linutil.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.