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 updateFromRaw(self):
"""Updates Ui representation of the internal :obj:`PyFlow.Core.structs.splineRamp`
"""
try:
for item in self.items():
self._scene.removeItem(item)
del item
for x in self._rawRamp.sortedItems():
self.... | Updates Ui representation of the internal :obj:`PyFlow.Core.structs.splineRamp`
| updateFromRaw | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def __getitem__(self, index):
"""
:param index: What UiTick to get, ordered by U
:type index: int
:returns: Ui Tick
:rtype: :obj:`UiTick`
"""
if index in range(0, len(self.items())):
return self.sortedItems()[index]
else:
return Non... |
:param index: What UiTick to get, ordered by U
:type index: int
:returns: Ui Tick
:rtype: :obj:`UiTick`
| __getitem__ | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def sortedItems(self):
"""Returns all the :obj:`UiTick` in the ramp sorted by x position
:returns: all :obj:`UiTick` in the ramp
:rtype: list(:obj:`UiTick`)
"""
itms = list(self.items())
itms.sort(key=lambda x: x.getU())
return itms | Returns all the :obj:`UiTick` in the ramp sorted by x position
:returns: all :obj:`UiTick` in the ramp
:rtype: list(:obj:`UiTick`)
| sortedItems | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def addItem(self, u=0, v=0, raw_item=None):
"""Adds a new Item to the ramp
:param u: X position for the item, defaults to 0
:type u: float, optional
:param v: Y position for the item, defaults to 0
:type v: float, optional
:param raw_item: Existing :obj:`PyFlow.Core.stru... | Adds a new Item to the ramp
:param u: X position for the item, defaults to 0
:type u: float, optional
:param v: Y position for the item, defaults to 0
:type v: float, optional
:param raw_item: Existing :obj:`PyFlow.Core.structs.Tick` to link with, if none, one new created , defa... | addItem | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def setU(self, u, index=-1):
"""Sets the X position for the selected item if no index provided
:param u: New x position
:type u: float
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selected Ticks, defaults to -1
... | Sets the X position for the selected item if no index provided
:param u: New x position
:type u: float
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selected Ticks, defaults to -1
:type index: int, optional
... | setU | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def setV(self, v, index=-1):
"""Sets the Y position for the selected item if no index provided
:param v: New y position
:type v: float
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selected Ticks, defaults to -1
... | Sets the Y position for the selected item if no index provided
:param v: New y position
:type v: float
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selected Ticks, defaults to -1
:type index: int, optional
... | setV | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def addItem(self, u=0, v=(0, 0, 0), raw_item=None):
"""Adds a new Item to the ramp
:param u: X position for the item, defaults to 0
:type u: float, optional
:param v: color value for the item, defaults to (0,0,0)
:type v: [float,float,float], optional
:param raw_item: Ex... | Adds a new Item to the ramp
:param u: X position for the item, defaults to 0
:type u: float, optional
:param v: color value for the item, defaults to (0,0,0)
:type v: [float,float,float], optional
:param raw_item: Existing :obj:`PyFlow.Core.structs.Tick` to link with, if none, o... | addItem | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def setColor(self, color, index=-1):
"""Sets the color value for the selected item if no index provided
:param color: New color
:type color: [float,float,float]
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selecte... | Sets the color value for the selected item if no index provided
:param color: New color
:type color: [float,float,float]
:param index: Index of the tick to set the value in, ordered by current X position, if -1 will try to set value in all selected Ticks, defaults to -1
:type index: int... | setColor | python | pedroCabrera/PyFlow | PyFlow/UI/Widgets/QtSliders.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/UI/Widgets/QtSliders.py | Apache-2.0 |
def parseFunctionFile(self, defname):
#https://nedbatchelder.com/text/python-parsers.html
#Maybe use Code Parser
''' Function Dictionary Structure
["Name"] - Function Name
["Order"] - Order in Appearanc... | Function Dictionary Structure
["Name"] - Function Name
["Order"] - Order in Appearance
["Meta"] - Meta Data
["Inputs"] - Pin Input List
["... | parseFunctionFile | python | pedroCabrera/PyFlow | PyFlow/Wizards/PackageBuilder.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/Wizards/PackageBuilder.py | Apache-2.0 |
def on_tblFInputPins_clicked(self, index):
'''print(index)
print("Click", self.ui.tblFInputPins.model().index(index.row(), 0).data())
print("Row %d and Column %d was clicked" % (index.row(), index.column()))
print(self.ui.tblFInputPins.model().data(index, QtCore.Qt.UserRole))'''
... | print(index)
print("Click", self.ui.tblFInputPins.model().index(index.row(), 0).data())
print("Row %d and Column %d was clicked" % (index.row(), index.column()))
print(self.ui.tblFInputPins.model().data(index, QtCore.Qt.UserRole)) | on_tblFInputPins_clicked | python | pedroCabrera/PyFlow | PyFlow/Wizards/PackageBuilder.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/Wizards/PackageBuilder.py | Apache-2.0 |
def loadInit(self, f):
'''["Class Imports", "Pins", "Functions", "Nodes", "Factories", "Prefs widgets",
"Foo Dict", "Node Dict", "Pin Dict", "Toolbar Dict", "Export", "Preferred Widgets",
"Base Package"]'''
packageRoot = Packages.__path__[0]
s... | ["Class Imports", "Pins", "Functions", "Nodes", "Factories", "Prefs widgets",
"Foo Dict", "Node Dict", "Pin Dict", "Toolbar Dict", "Export", "Preferred Widgets",
"Base Package"] | loadInit | python | pedroCabrera/PyFlow | PyFlow/Wizards/PackageBuilder.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/Wizards/PackageBuilder.py | Apache-2.0 |
def onerror(func, path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerro... |
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
| onerror | python | pedroCabrera/PyFlow | PyFlow/Wizards/PkgGen.py | https://github.com/pedroCabrera/PyFlow/blob/master/PyFlow/Wizards/PkgGen.py | Apache-2.0 |
def process_history(history: list[Conversation]):
"""
Process the input history to extract the query and the history pairs.
Args:
History(list[Conversation]): A list of Conversation objects representing all conversations.
Returns:
query(str): The current user input st... |
Process the input history to extract the query and the history pairs.
Args:
History(list[Conversation]): A list of Conversation objects representing all conversations.
Returns:
query(str): The current user input string.
history_pairs(list[(str,str)]): A list ... | process_history | python | THUDM/CogVLM | composite_demo/client.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/client.py | Apache-2.0 |
def generate_stream(self,
history: list,
grounding: bool = False,
model_use: str = 'agent_chat',
**parameters: Any
) -> Iterable[TextGenerationStreamResponse]:
"""
Generates a stream o... |
Generates a stream of text responses based on the input history and selected model.
This method facilitates a chat-like interaction with the models. Depending on the
model selected and whether grounding is enabled, it alters the behavior of the text
generation process.
Args:
... | generate_stream | python | THUDM/CogVLM | composite_demo/client.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/client.py | Apache-2.0 |
def preprocess_text(history: list[Conversation], ) -> str:
"""
Prepares the conversation history for processing by concatenating the content of each turn.
Args:
history (list[Conversation]): The conversation history, a list of Conversation objects.
Returns:
str: A single string that co... |
Prepares the conversation history for processing by concatenating the content of each turn.
Args:
history (list[Conversation]): The conversation history, a list of Conversation objects.
Returns:
str: A single string that concatenates the content of each conversation turn, followed by
... | preprocess_text | python | THUDM/CogVLM | composite_demo/conversation.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/conversation.py | Apache-2.0 |
def postprocess_text(template: str, text: str) -> str:
"""
Post-processes the generated text by incorporating it into a given template.
Args:
template (str): A template string containing a placeholder for the generated text.
text (str): The generated text to be incorporated into the template... |
Post-processes the generated text by incorporating it into a given template.
Args:
template (str): A template string containing a placeholder for the generated text.
text (str): The generated text to be incorporated into the template.
Returns:
str: The template with the generated t... | postprocess_text | python | THUDM/CogVLM | composite_demo/conversation.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/conversation.py | Apache-2.0 |
def postprocess_image(text: str, img: Image) -> (str, Image):
"""
Processes the given text to identify and draw bounding boxes on the provided image.
This function searches for patterns in the text that represent coordinates for bounding
boxes and draws rectangles on the image at these coordinates. Each... |
Processes the given text to identify and draw bounding boxes on the provided image.
This function searches for patterns in the text that represent coordinates for bounding
boxes and draws rectangles on the image at these coordinates. Each box is drawn in a
different color for distinction.
Args:
... | postprocess_image | python | THUDM/CogVLM | composite_demo/conversation.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/conversation.py | Apache-2.0 |
def translate_baidu(translate_text, source_lan, target_lan):
"""
Translates text using Baidu's translation service. (if you are not use English)
This function sends a request to the Baidu translation API to translate the provided text
from the source language to the target language.
... |
Translates text using Baidu's translation service. (if you are not use English)
This function sends a request to the Baidu translation API to translate the provided text
from the source language to the target language.
Args:
translate_text (str): The text to be translated.... | translate_baidu | python | THUDM/CogVLM | composite_demo/conversation.py | https://github.com/THUDM/CogVLM/blob/master/composite_demo/conversation.py | Apache-2.0 |
def to_tensor(value):
"""Converts lists or numpy arrays to tensors."""
if isinstance(value, list):
return torch.tensor(value)
elif isinstance(value, np.ndarray):
return torch.from_numpy(value)
return value | Converts lists or numpy arrays to tensors. | to_tensor | python | THUDM/CogVLM | finetune_demo/evaluate_cogagent_demo.py | https://github.com/THUDM/CogVLM/blob/master/finetune_demo/evaluate_cogagent_demo.py | Apache-2.0 |
def concatenate_tensors(attribute, key):
"""Concatenates tensors for a specific attribute and key."""
if attribute is None:
return torch.cat([ex[key] for ex in examples if isinstance(ex[key], torch.Tensor)])
else:
return torch.cat([ex[attribute][key] for ex in examples if... | Concatenates tensors for a specific attribute and key. | concatenate_tensors | python | THUDM/CogVLM | finetune_demo/evaluate_cogagent_demo.py | https://github.com/THUDM/CogVLM/blob/master/finetune_demo/evaluate_cogagent_demo.py | Apache-2.0 |
def to_tensor(value):
"""Converts lists or numpy arrays to tensors."""
if isinstance(value, list):
return torch.tensor(value)
elif isinstance(value, np.ndarray):
return torch.from_numpy(value)
return value | Converts lists or numpy arrays to tensors. | to_tensor | python | THUDM/CogVLM | finetune_demo/finetune_cogagent_demo.py | https://github.com/THUDM/CogVLM/blob/master/finetune_demo/finetune_cogagent_demo.py | Apache-2.0 |
def concatenate_tensors(attribute, key):
"""Concatenates tensors for a specific attribute and key."""
if attribute is None:
return torch.cat([ex[key] for ex in examples if isinstance(ex[key], torch.Tensor)])
else:
return torch.cat([ex[attribute][key] for ex in examples if... | Concatenates tensors for a specific attribute and key. | concatenate_tensors | python | THUDM/CogVLM | finetune_demo/finetune_cogagent_demo.py | https://github.com/THUDM/CogVLM/blob/master/finetune_demo/finetune_cogagent_demo.py | Apache-2.0 |
async def lifespan(app: FastAPI):
"""
An asynchronous context manager for managing the lifecycle of the FastAPI app.
It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.
"""
yield
if torch.cuda.is_availabl... |
An asynchronous context manager for managing the lifecycle of the FastAPI app.
It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.
| lifespan | python | THUDM/CogVLM | openai_demo/openai_api.py | https://github.com/THUDM/CogVLM/blob/master/openai_demo/openai_api.py | Apache-2.0 |
async def list_models():
"""
An endpoint to list available models. It returns a list of model cards.
This is useful for clients to query and understand what models are available for use.
"""
model_card = ModelCard(id="cogvlm-chat-17b") # can be replaced by your model id like cogagent-chat-18b
r... |
An endpoint to list available models. It returns a list of model cards.
This is useful for clients to query and understand what models are available for use.
| list_models | python | THUDM/CogVLM | openai_demo/openai_api.py | https://github.com/THUDM/CogVLM/blob/master/openai_demo/openai_api.py | Apache-2.0 |
async def predict(model_id: str, params: dict):
"""
Handle streaming predictions. It continuously generates responses for a given input stream.
This is particularly useful for real-time, continuous interactions with the model.
"""
global model, tokenizer
choice_data = ChatCompletionResponseStr... |
Handle streaming predictions. It continuously generates responses for a given input stream.
This is particularly useful for real-time, continuous interactions with the model.
| predict | python | THUDM/CogVLM | openai_demo/openai_api.py | https://github.com/THUDM/CogVLM/blob/master/openai_demo/openai_api.py | Apache-2.0 |
def generate_cogvlm(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, params: dict):
"""
Generates a response using the CogVLM model. It processes the chat history and image data, if any,
and then invokes the model to generate a response.
"""
for response in generate_stream_cogvlm(model, toke... |
Generates a response using the CogVLM model. It processes the chat history and image data, if any,
and then invokes the model to generate a response.
| generate_cogvlm | python | THUDM/CogVLM | openai_demo/openai_api.py | https://github.com/THUDM/CogVLM/blob/master/openai_demo/openai_api.py | Apache-2.0 |
def generate_stream_cogvlm(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, params: dict):
"""
Generates a stream of responses using the CogVLM model in inference mode.
It's optimized to handle continuous input-output interactions with the model in a streaming manner.
"""
messages = params["m... |
Generates a stream of responses using the CogVLM model in inference mode.
It's optimized to handle continuous input-output interactions with the model in a streaming manner.
| generate_stream_cogvlm | python | THUDM/CogVLM | openai_demo/openai_api.py | https://github.com/THUDM/CogVLM/blob/master/openai_demo/openai_api.py | Apache-2.0 |
def __init__(self, args, vitclass):
'''
args: the args to initialize the vit model
vitclass: the class of VIT model, must be a subclass of BaseModel
project_dim: the dimension of the projection layer
default_load: the default load path for the vit model
... |
args: the args to initialize the vit model
vitclass: the class of VIT model, must be a subclass of BaseModel
project_dim: the dimension of the projection layer
default_load: the default load path for the vit model
model_parallel_size: the model parallel size ... | __init__ | python | THUDM/CogVLM | utils/models/cogagent_model.py | https://github.com/THUDM/CogVLM/blob/master/utils/models/cogagent_model.py | Apache-2.0 |
def normalize_img_path(img: str):
"""Normalizes the image path for output."""
if os.name == 'nt':
# On Windows, the JSON.dump ends up outputting un-escaped backslash breaking
# the ability to read colors.json. Windows supports forward slash, so we can
# use that for now
return im... | Normalizes the image path for output. | normalize_img_path | python | dylanaraps/pywal | pywal/colors.py | https://github.com/dylanaraps/pywal/blob/master/pywal/colors.py | MIT |
def colors_to_dict(colors, img):
"""Convert list of colors to pywal format."""
return {
"wallpaper": normalize_img_path(img),
"alpha": util.Color.alpha_num,
"special": {
"background": colors[0],
"foreground": colors[15],
"cursor": colors[15]
}... | Convert list of colors to pywal format. | colors_to_dict | python | dylanaraps/pywal | pywal/colors.py | https://github.com/dylanaraps/pywal/blob/master/pywal/colors.py | MIT |
def get_backend(backend):
"""Figure out which backend to use."""
if backend == "random":
backends = list_backends()
random.shuffle(backends)
return backends[0]
return backend | Figure out which backend to use. | get_backend | python | dylanaraps/pywal | pywal/colors.py | https://github.com/dylanaraps/pywal/blob/master/pywal/colors.py | MIT |
def template(colors, input_file, output_file=None):
"""Read template file, substitute markers and
save the file elsewhere."""
# pylint: disable-msg=too-many-locals
template_data = util.read_file_raw(input_file)
for i, l in enumerate(template_data):
for match in re.finditer(r"(?<=(?<!\{))(... | Read template file, substitute markers and
save the file elsewhere. | template | python | dylanaraps/pywal | pywal/export.py | https://github.com/dylanaraps/pywal/blob/master/pywal/export.py | MIT |
def flatten_colors(colors):
"""Prepare colors to be exported.
Flatten dicts and convert colors to util.Color()"""
all_colors = {"wallpaper": colors["wallpaper"],
"alpha": colors["alpha"],
**colors["special"],
**colors["colors"]}
return {k: util.Co... | Prepare colors to be exported.
Flatten dicts and convert colors to util.Color() | flatten_colors | python | dylanaraps/pywal | pywal/export.py | https://github.com/dylanaraps/pywal/blob/master/pywal/export.py | MIT |
def get_export_type(export_type):
"""Convert template type to the right filename."""
return {
"css": "colors.css",
"dmenu": "colors-wal-dmenu.h",
"dwm": "colors-wal-dwm.h",
"st": "colors-wal-st.h",
"tabbed": "colors-wal-tabbed.h",
"gtk2": "colors-gtk2.rc",
... | Convert template type to the right filename. | get_export_type | python | dylanaraps/pywal | pywal/export.py | https://github.com/dylanaraps/pywal/blob/master/pywal/export.py | MIT |
def get_image_dir_recursive(img_dir):
"""Get all images in a directory recursively."""
current_wall = wallpaper.get()
current_wall = os.path.basename(current_wall)
file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif")
images = []
for path, _, files in os.walk(img_dir):
for name in fil... | Get all images in a directory recursively. | get_image_dir_recursive | python | dylanaraps/pywal | pywal/image.py | https://github.com/dylanaraps/pywal/blob/master/pywal/image.py | MIT |
def get_random_image(img_dir, recursive):
"""Pick a random image file from a directory."""
if recursive:
images, current_wall = get_image_dir_recursive(img_dir)
else:
images, current_wall = get_image_dir(img_dir)
if len(images) > 2 and current_wall in images:
images.remove(curre... | Pick a random image file from a directory. | get_random_image | python | dylanaraps/pywal | pywal/image.py | https://github.com/dylanaraps/pywal/blob/master/pywal/image.py | MIT |
def get_next_image(img_dir, recursive):
"""Get the next image in a dir."""
if recursive:
images, current_wall = get_image_dir_recursive(img_dir)
else:
images, current_wall = get_image_dir(img_dir)
images.sort(key=lambda img: [int(x) if x.isdigit() else x
... | Get the next image in a dir. | get_next_image | python | dylanaraps/pywal | pywal/image.py | https://github.com/dylanaraps/pywal/blob/master/pywal/image.py | MIT |
def xrdb(xrdb_files=None):
"""Merge the colors into the X db so new terminals use them."""
xrdb_files = xrdb_files or \
[os.path.join(CACHE_DIR, "colors.Xresources")]
if shutil.which("xrdb") and OS != "Darwin":
for file in xrdb_files:
subprocess.run(["xrdb", "-merge", "-quiet", ... | Merge the colors into the X db so new terminals use them. | xrdb | python | dylanaraps/pywal | pywal/reload.py | https://github.com/dylanaraps/pywal/blob/master/pywal/reload.py | MIT |
def gtk():
"""Reload GTK theme on the fly."""
# Here we call a Python 2 script to reload the GTK themes.
# This is done because the Python 3 GTK/Gdk libraries don't
# provide a way of doing this.
if shutil.which("python2"):
gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py")
... | Reload GTK theme on the fly. | gtk | python | dylanaraps/pywal | pywal/reload.py | https://github.com/dylanaraps/pywal/blob/master/pywal/reload.py | MIT |
def set_special(index, color, iterm_name="h", alpha=100):
"""Convert a hex color to a special sequence."""
if OS == "Darwin" and iterm_name:
return "\033]P%s%s\033\\" % (iterm_name, color.strip("#"))
if index in [11, 708] and alpha != "100":
return "\033]%s;[%s]%s\033\\" % (index, alpha, co... | Convert a hex color to a special sequence. | set_special | python | dylanaraps/pywal | pywal/sequences.py | https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py | MIT |
def set_color(index, color):
"""Convert a hex color to a text color sequence."""
if OS == "Darwin" and index < 20:
return "\033]P%1x%s\033\\" % (index, color.strip("#"))
return "\033]4;%s;%s\033\\" % (index, color) | Convert a hex color to a text color sequence. | set_color | python | dylanaraps/pywal | pywal/sequences.py | https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py | MIT |
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False):
"""Send colors to all open terminals."""
if OS == "Darwin":
tty_pattern = "/dev/ttys00[0-9]*"
else:
tty_pattern = "/dev/pts/[0-9]*"
sequences = create_sequences(colors, vte_fix)
# Writing to "/dev/pts/[0-9] lets y... | Send colors to all open terminals. | send | python | dylanaraps/pywal | pywal/sequences.py | https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py | MIT |
def list_out():
"""List all themes in a pretty format."""
dark_themes = [theme.name.replace(".json", "")
for theme in list_themes()]
ligh_themes = [theme.name.replace(".json", "")
for theme in list_themes(dark=False)]
user_themes = [theme.name.replace(".json", "")
... | List all themes in a pretty format. | list_out | python | dylanaraps/pywal | pywal/theme.py | https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py | MIT |
def terminal_sexy_to_wal(data):
"""Convert terminal.sexy json schema to wal."""
data["colors"] = {}
data["special"] = {
"foreground": data["foreground"],
"background": data["background"],
"cursor": data["color"][9]
}
for i, color in enumerate(data["color"]):
data["co... | Convert terminal.sexy json schema to wal. | terminal_sexy_to_wal | python | dylanaraps/pywal | pywal/theme.py | https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py | MIT |
def get_random_theme_user():
"""Get a random theme file from user theme directories."""
themes = [theme.path for theme in list_themes_user()]
random.shuffle(themes)
return themes[0] | Get a random theme file from user theme directories. | get_random_theme_user | python | dylanaraps/pywal | pywal/theme.py | https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py | MIT |
def hex_to_xrgba(color):
"""Convert a hex color to xrdb rgba."""
col = color.lower().strip("#")
return "%s%s/%s%s/%s%s/ff" % (*col,) | Convert a hex color to xrdb rgba. | hex_to_xrgba | python | dylanaraps/pywal | pywal/util.py | https://github.com/dylanaraps/pywal/blob/master/pywal/util.py | MIT |
def get_pid(name):
"""Check if process is running by name."""
if not shutil.which("pidof"):
return False
try:
if platform.system() != 'Darwin':
subprocess.check_output(["pidof", "-s", name])
else:
subprocess.check_output(["pidof", name])
except subproces... | Check if process is running by name. | get_pid | python | dylanaraps/pywal | pywal/util.py | https://github.com/dylanaraps/pywal/blob/master/pywal/util.py | MIT |
def get_desktop_env():
"""Identify the current running desktop environment."""
desktop = os.environ.get("XDG_CURRENT_DESKTOP")
if desktop:
return desktop
desktop = os.environ.get("DESKTOP_SESSION")
if desktop:
return desktop
desktop = os.environ.get("GNOME_DESKTOP_SESSION_ID")
... | Identify the current running desktop environment. | get_desktop_env | python | dylanaraps/pywal | pywal/wallpaper.py | https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py | MIT |
def xfconf(img):
"""Call xfconf to set the wallpaper on XFCE."""
xfconf_re = re.compile(
r"^/backdrop/screen\d/monitor(?:0|\w*)/"
r"(?:(?:image-path|last-image)|workspace\d/last-image)$",
flags=re.M
)
xfconf_data = subprocess.check_output(
["xfconf-query", "--channel", "x... | Call xfconf to set the wallpaper on XFCE. | xfconf | python | dylanaraps/pywal | pywal/wallpaper.py | https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py | MIT |
def set_wm_wallpaper(img):
"""Set the wallpaper for non desktop environments."""
if shutil.which("feh"):
util.disown(["feh", "--bg-fill", img])
elif shutil.which("xwallpaper"):
util.disown(["xwallpaper", "--zoom", img])
elif shutil.which("hsetroot"):
util.disown(["hsetroot", "-... | Set the wallpaper for non desktop environments. | set_wm_wallpaper | python | dylanaraps/pywal | pywal/wallpaper.py | https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py | MIT |
def set_desktop_wallpaper(desktop, img):
"""Set the wallpaper for the desktop environment."""
desktop = str(desktop).lower()
if "xfce" in desktop or "xubuntu" in desktop:
xfconf(img)
elif "muffin" in desktop or "cinnamon" in desktop:
util.disown(["gsettings", "set",
... | Set the wallpaper for the desktop environment. | set_desktop_wallpaper | python | dylanaraps/pywal | pywal/wallpaper.py | https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py | MIT |
def has_im():
"""Check to see if the user has im installed."""
if shutil.which("magick"):
return ["magick", "convert"]
if shutil.which("convert"):
return ["convert"]
logging.error("Imagemagick wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
... | Check to see if the user has im installed. | has_im | python | dylanaraps/pywal | pywal/backends/wal.py | https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py | MIT |
def gen_colors(img):
"""Format the output from imagemagick into a list
of hex colors."""
magick_command = has_im()
for i in range(0, 20, 1):
raw_colors = imagemagick(16 + i, img, magick_command)
if len(raw_colors) > 16:
break
if i == 19:
logging.erro... | Format the output from imagemagick into a list
of hex colors. | gen_colors | python | dylanaraps/pywal | pywal/backends/wal.py | https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py | MIT |
def adjust(colors, light):
"""Adjust the generated colors and store them in a dict that
we will later save in json format."""
raw_colors = colors[:1] + colors[8:16] + colors[8:-1]
# Manually adjust colors.
if light:
for color in raw_colors:
color = util.saturate_color(color, ... | Adjust the generated colors and store them in a dict that
we will later save in json format. | adjust | python | dylanaraps/pywal | pywal/backends/wal.py | https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py | MIT |
def test_css_template(self):
"""> Test substitutions in template file (css)."""
tmp_file = os.path.join(TMP_DIR, "test.css")
export.color(COLORS, "css", tmp_file)
self.is_file(tmp_file)
self.is_file_contents(tmp_file, " --background: #1F211E;") | > Test substitutions in template file (css). | test_css_template | python | dylanaraps/pywal | tests/test_export.py | https://github.com/dylanaraps/pywal/blob/master/tests/test_export.py | MIT |
def test_set_special_alpha(self):
"""> Create special escape sequence with alpha."""
alpha = "99"
result = sequences.set_special(11,
COLORS["special"]["background"],
"h", alpha)
if platform.uname()[0] == "Darw... | > Create special escape sequence with alpha. | test_set_special_alpha | python | dylanaraps/pywal | tests/test_sequences.py | https://github.com/dylanaraps/pywal/blob/master/tests/test_sequences.py | MIT |
def verify_checksum(self, subtests, dbc_file: str, msg_name: str, msg_addr: int, test_messages: list[bytes],
checksum_field: str = 'CHECKSUM', counter_field = 'COUNTER'):
"""
Verify that opendbc calculates payload CRCs/checksums matching those received in known-good sample messages
Dep... |
Verify that opendbc calculates payload CRCs/checksums matching those received in known-good sample messages
Depends on all non-zero bits in the sample message having a corresponding DBC signal, add UNKNOWN signals if needed
| verify_checksum | python | commaai/opendbc | opendbc/can/tests/test_checksums.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py | MIT |
def verify_fca_giorgio_crc(self, subtests, msg_name: str, msg_addr: int, test_messages: list[bytes]):
"""Test modified SAE J1850 CRCs, with special final XOR cases for EPS messages"""
assert len(test_messages) == 3
self.verify_checksum(subtests, "fca_giorgio", msg_name, msg_addr, test_messages) | Test modified SAE J1850 CRCs, with special final XOR cases for EPS messages | verify_fca_giorgio_crc | python | commaai/opendbc | opendbc/can/tests/test_checksums.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py | MIT |
def test_honda_checksum(self):
"""Test checksums for Honda standard and extended CAN ids"""
# TODO: refactor to use self.verify_checksum()
dbc_file = "honda_accord_2018_can_generated"
msgs = [("LKAS_HUD", 0), ("LKAS_HUD_A", 0)]
parser = CANParser(dbc_file, msgs, 0)
packer = CANPacker(dbc_file)
... | Test checksums for Honda standard and extended CAN ids | test_honda_checksum | python | commaai/opendbc | opendbc/can/tests/test_checksums.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py | MIT |
def test_parse_all_dbcs(self, subtests):
"""
Dynamic DBC parser checks:
- Checksum and counter length, start bit, endianness
- Duplicate message addresses and names
- Signal out of bounds
- All BO_, SG_, VAL_ lines for syntax errors
"""
for dbc in ALL_DBCS:
with ... |
Dynamic DBC parser checks:
- Checksum and counter length, start bit, endianness
- Duplicate message addresses and names
- Signal out of bounds
- All BO_, SG_, VAL_ lines for syntax errors
| test_parse_all_dbcs | python | commaai/opendbc | opendbc/can/tests/test_dbc_parser.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_dbc_parser.py | MIT |
def test_parser_counter_can_valid(self):
"""
Tests number of allowed bad counters + ensures CAN stays invalid
while receiving invalid messages + that we can recover
"""
msgs = [
("STEERING_CONTROL", 0),
]
packer = CANPacker("honda_civic_touring_2016_can_generated")
parser = CANPars... |
Tests number of allowed bad counters + ensures CAN stays invalid
while receiving invalid messages + that we can recover
| test_parser_counter_can_valid | python | commaai/opendbc | opendbc/can/tests/test_packer_parser.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py | MIT |
def test_parser_no_partial_update(self):
"""
Ensure that the CANParser doesn't partially update messages with invalid signals (COUNTER/CHECKSUM).
Previously, the signal update loop would only break once it got to one of these invalid signals,
after already updating most/all of the signals.
"""
m... |
Ensure that the CANParser doesn't partially update messages with invalid signals (COUNTER/CHECKSUM).
Previously, the signal update loop would only break once it got to one of these invalid signals,
after already updating most/all of the signals.
| test_parser_no_partial_update | python | commaai/opendbc | opendbc/can/tests/test_packer_parser.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py | MIT |
def test_scale_offset(self):
"""Test that both scale and offset are correctly preserved"""
dbc_file = "honda_civic_touring_2016_can_generated"
msgs = [("VSA_STATUS", 50)]
parser = CANParser(dbc_file, msgs, 0)
packer = CANPacker(dbc_file)
for brake in range(100):
values = {"USER_BRAKE": br... | Test that both scale and offset are correctly preserved | test_scale_offset | python | commaai/opendbc | opendbc/can/tests/test_packer_parser.py | https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py | MIT |
def disable_ecu(can_recv, can_send, bus=0, addr=0x7d0, sub_addr=None, com_cont_req=b'\x28\x83\x01', timeout=0.1, retry=10):
"""Silence an ECU by disabling sending and receiving messages using UDS 0x28.
The ECU will stay silent as long as openpilot keeps sending Tester Present.
This is used to disable the radar i... | Silence an ECU by disabling sending and receiving messages using UDS 0x28.
The ECU will stay silent as long as openpilot keeps sending Tester Present.
This is used to disable the radar in some cars. Openpilot will emulate the radar.
WARNING: THIS DISABLES AEB! | disable_ecu | python | commaai/opendbc | opendbc/car/disable_ecu.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/disable_ecu.py | MIT |
def eliminate_incompatible_cars(msg, candidate_cars):
"""Removes cars that could not have sent msg.
Inputs:
msg: A cereal/log CanData message from the car.
candidate_cars: A list of cars to consider.
Returns:
A list containing the subset of candidate_cars that could have sent msg.
"""
... | Removes cars that could not have sent msg.
Inputs:
msg: A cereal/log CanData message from the car.
candidate_cars: A list of cars to consider.
Returns:
A list containing the subset of candidate_cars that could have sent msg.
| eliminate_incompatible_cars | python | commaai/opendbc | opendbc/car/fingerprints.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/fingerprints.py | MIT |
def match_fw_to_car_fuzzy(live_fw_versions: LiveFwVersions, match_brand: str = None, log: bool = True, exclude: str = None) -> set[str]:
"""Do a fuzzy FW match. This function will return a match, and the number of firmware version
that were matched uniquely to that specific car. If multiple ECUs uniquely match to d... | Do a fuzzy FW match. This function will return a match, and the number of firmware version
that were matched uniquely to that specific car. If multiple ECUs uniquely match to different cars
the match is rejected. | match_fw_to_car_fuzzy | python | commaai/opendbc | opendbc/car/fw_versions.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py | MIT |
def match_fw_to_car_exact(live_fw_versions: LiveFwVersions, match_brand: str = None, log: bool = True, extra_fw_versions: dict = None) -> set[str]:
"""Do an exact FW match. Returns all cars that match the given
FW versions for a list of "essential" ECUs. If an ECU is not considered
essential the FW version can be... | Do an exact FW match. Returns all cars that match the given
FW versions for a list of "essential" ECUs. If an ECU is not considered
essential the FW version can be missing to get a fingerprint, but if it's present it
needs to match the database. | match_fw_to_car_exact | python | commaai/opendbc | opendbc/car/fw_versions.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py | MIT |
def get_brand_ecu_matches(ecu_rx_addrs: set[EcuAddrBusType]) -> dict[str, list[bool]]:
"""Returns dictionary of brands and matches with ECUs in their FW versions"""
brand_rx_addrs = {brand: set() for brand in FW_QUERY_CONFIGS}
brand_matches = {brand: [] for brand, _, _ in REQUESTS}
# Since we can't know what ... | Returns dictionary of brands and matches with ECUs in their FW versions | get_brand_ecu_matches | python | commaai/opendbc | opendbc/car/fw_versions.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py | MIT |
def get_fw_versions_ordered(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback, vin: str,
ecu_rx_addrs: set[EcuAddrBusType], timeout: float = 0.1, num_pandas: int = 1, progress: bool = False) -> list[CarParams.CarFw]:
"""Queries for FW versions ordering... | Queries for FW versions ordering brands by likelihood, breaks when exact match is found | get_fw_versions_ordered | python | commaai/opendbc | opendbc/car/fw_versions.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py | MIT |
def update_blinker_from_lamp(self, blinker_time: int, left_blinker_lamp: bool, right_blinker_lamp: bool):
"""Update blinkers from lights. Enable output when light was seen within the last `blinker_time`
iterations"""
# TODO: Handle case when switching direction. Now both blinkers can be on at the same time
... | Update blinkers from lights. Enable output when light was seen within the last `blinker_time`
iterations | update_blinker_from_lamp | python | commaai/opendbc | opendbc/car/interfaces.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py | MIT |
def update_steering_pressed(self, steering_pressed, steering_pressed_min_count):
"""Applies filtering on steering pressed for noisy driver torque signals."""
self.steering_pressed_cnt += 1 if steering_pressed else -1
self.steering_pressed_cnt = int(np.clip(self.steering_pressed_cnt, 0, steering_pressed_min_... | Applies filtering on steering pressed for noisy driver torque signals. | update_steering_pressed | python | commaai/opendbc | opendbc/car/interfaces.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py | MIT |
def update_blinker_from_stalk(self, blinker_time: int, left_blinker_stalk: bool, right_blinker_stalk: bool):
"""Update blinkers from stalk position. When stalk is seen the blinker will be on for at least blinker_time,
or until the stalk is turned off, whichever is longer. If the opposite stalk direction is seen... | Update blinkers from stalk position. When stalk is seen the blinker will be on for at least blinker_time,
or until the stalk is turned off, whichever is longer. If the opposite stalk direction is seen the blinker
is forced to the other side. On a rising edge of the stalk the timeout is reset. | update_blinker_from_stalk | python | commaai/opendbc | opendbc/car/interfaces.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py | MIT |
def rx(self) -> None:
"""Drain can socket and sort messages into buffers based on address"""
can_packets = self.can_recv(wait_for_one=True)
for packet in can_packets:
for msg in packet:
if msg.src == self.bus and msg.address in self.msg_addrs.values():
self.msg_buffer[msg.address].a... | Drain can socket and sort messages into buffers based on address | rx | python | commaai/opendbc | opendbc/car/isotp_parallel_query.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/isotp_parallel_query.py | MIT |
def _can_rx(self, addr, sub_addr=None):
"""Helper function to retrieve message with specified address and subaddress from buffer"""
keep_msgs = []
if sub_addr is None:
msgs = self.msg_buffer[addr]
else:
# Filter based on subaddress
msgs = []
for m in self.msg_buffer[addr]:
... | Helper function to retrieve message with specified address and subaddress from buffer | _can_rx | python | commaai/opendbc | opendbc/car/isotp_parallel_query.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/isotp_parallel_query.py | MIT |
def update_params(self, stiffness_factor: float, steer_ratio: float) -> None:
"""Update the vehicle model with a new stiffness factor and steer ratio"""
self.cF: float = stiffness_factor * self.cF_orig
self.cR: float = stiffness_factor * self.cR_orig
self.sR: float = steer_ratio | Update the vehicle model with a new stiffness factor and steer ratio | update_params | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def steady_state_sol(self, sa: float, u: float, roll: float) -> np.ndarray:
"""Returns the steady state solution.
If the speed is too low we can't use the dynamic model (tire slip is undefined),
we then have to use the kinematic model
Args:
sa: Steering wheel angle [rad]
u: Speed [m/s]
... | Returns the steady state solution.
If the speed is too low we can't use the dynamic model (tire slip is undefined),
we then have to use the kinematic model
Args:
sa: Steering wheel angle [rad]
u: Speed [m/s]
roll: Road Roll [rad]
Returns:
2x1 matrix with steady state solution ... | steady_state_sol | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def curvature_factor(self, u: float) -> float:
"""Returns the curvature factor.
Multiplied by wheel angle (not steering wheel angle) this will give the curvature.
Args:
u: Speed [m/s]
Returns:
Curvature factor [1/m]
"""
sf = calc_slip_factor(self)
return (1. - self.chi) / (1. -... | Returns the curvature factor.
Multiplied by wheel angle (not steering wheel angle) this will give the curvature.
Args:
u: Speed [m/s]
Returns:
Curvature factor [1/m]
| curvature_factor | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def roll_compensation(self, roll: float, u: float) -> float:
"""Calculates the roll-compensation to curvature
Args:
roll: Road Roll [rad]
u: Speed [m/s]
Returns:
Roll compensation curvature [rad]
"""
sf = calc_slip_factor(self)
if abs(sf) < 1e-6:
return 0
else:
... | Calculates the roll-compensation to curvature
Args:
roll: Road Roll [rad]
u: Speed [m/s]
Returns:
Roll compensation curvature [rad]
| roll_compensation | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def get_steer_from_yaw_rate(self, yaw_rate: float, u: float, roll: float) -> float:
"""Calculates the required steering wheel angle for a given yaw_rate
Args:
yaw_rate: Desired yaw rate [rad/s]
u: Speed [m/s]
roll: Road Roll [rad]
Returns:
Steering wheel angle [rad]
"""
cur... | Calculates the required steering wheel angle for a given yaw_rate
Args:
yaw_rate: Desired yaw rate [rad/s]
u: Speed [m/s]
roll: Road Roll [rad]
Returns:
Steering wheel angle [rad]
| get_steer_from_yaw_rate | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def kin_ss_sol(sa: float, u: float, VM: VehicleModel) -> np.ndarray:
"""Calculate the steady state solution at low speeds
At low speeds the tire slip is undefined, so a kinematic
model is used.
Args:
sa: Steering angle [rad]
u: Speed [m/s]
VM: Vehicle model
Returns:
2x1 matrix with steady st... | Calculate the steady state solution at low speeds
At low speeds the tire slip is undefined, so a kinematic
model is used.
Args:
sa: Steering angle [rad]
u: Speed [m/s]
VM: Vehicle model
Returns:
2x1 matrix with steady state solution
| kin_ss_sol | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def create_dyn_state_matrices(u: float, VM: VehicleModel) -> tuple[np.ndarray, np.ndarray]:
"""Returns the A and B matrix for the dynamics system
Args:
u: Vehicle speed [m/s]
VM: Vehicle model
Returns:
A tuple with the 2x2 A matrix, and 2x2 B matrix
Parameters in the vehicle model:
cF: Tire s... | Returns the A and B matrix for the dynamics system
Args:
u: Vehicle speed [m/s]
VM: Vehicle model
Returns:
A tuple with the 2x2 A matrix, and 2x2 B matrix
Parameters in the vehicle model:
cF: Tire stiffness Front [N/rad]
cR: Tire stiffness Rear [N/rad]
aF: Distance from CG to front whee... | create_dyn_state_matrices | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def dyn_ss_sol(sa: float, u: float, roll: float, VM: VehicleModel) -> np.ndarray:
"""Calculate the steady state solution when x_dot = 0,
Ax + Bu = 0 => x = -A^{-1} B u
Args:
sa: Steering angle [rad]
u: Speed [m/s]
roll: Road Roll [rad]
VM: Vehicle model
Returns:
2x1 matrix with steady stat... | Calculate the steady state solution when x_dot = 0,
Ax + Bu = 0 => x = -A^{-1} B u
Args:
sa: Steering angle [rad]
u: Speed [m/s]
roll: Road Roll [rad]
VM: Vehicle model
Returns:
2x1 matrix with steady state solution
| dyn_ss_sol | python | commaai/opendbc | opendbc/car/vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py | MIT |
def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, path_offset: float, path_angle: float, curvature: float,
curvature_rate: float):
"""
Creates a CAN message for the Ford TJA/LCA Command.
This command can apply "Lane Centering" maneuvers: continuous lane centering for traffic ja... |
Creates a CAN message for the Ford TJA/LCA Command.
This command can apply "Lane Centering" maneuvers: continuous lane centering for traffic jam assist and highway
driving. It is not subject to the PSCM lockout.
Ford lane centering command uses a third order polynomial to describe the road centerline. The po... | create_lat_ctl_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def create_lat_ctl2_msg(packer, CAN: CanBus, mode: int, path_offset: float, path_angle: float, curvature: float,
curvature_rate: float, counter: int):
"""
Create a CAN message for the new Ford Lane Centering command.
This message is used on the CAN FD platform and replaces the old Lateral... |
Create a CAN message for the new Ford Lane Centering command.
This message is used on the CAN FD platform and replaces the old LateralMotionControl message. It is similar but has
additional signals for a counter and checksum.
Frequency is 20Hz.
| create_lat_ctl2_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def create_acc_msg(packer, CAN: CanBus, long_active: bool, gas: float, accel: float, stopping: bool, brake_request, v_ego_kph: float):
"""
Creates a CAN message for the Ford ACC Command.
This command can be used to enable ACC, to set the ACC gas/brake/decel values
and to disable ACC.
Frequency is 50Hz.
""... |
Creates a CAN message for the Ford ACC Command.
This command can be used to enable ACC, to set the ACC gas/brake/decel values
and to disable ACC.
Frequency is 50Hz.
| create_acc_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def create_acc_ui_msg(packer, CAN: CanBus, CP, main_on: bool, enabled: bool, fcw_alert: bool, standstill: bool,
show_distance_bars: bool, hud_control, stock_values: dict):
"""
Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam
assist status.
... |
Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam
assist status.
Stock functionality is maintained by passing through unmodified signals.
Frequency is 5Hz.
| create_acc_ui_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def create_lkas_ui_msg(packer, CAN: CanBus, main_on: bool, enabled: bool, steer_alert: bool, hud_control,
stock_values: dict):
"""
Creates a CAN message for the Ford IPC IPMA/LKAS status.
Show the LKAS status with the "driver assist" lines in the IPC.
Stock functionality is maintained b... |
Creates a CAN message for the Ford IPC IPMA/LKAS status.
Show the LKAS status with the "driver assist" lines in the IPC.
Stock functionality is maintained by passing through unmodified signals.
Frequency is 1Hz.
| create_lkas_ui_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def create_button_msg(packer, bus: int, stock_values: dict, cancel=False, resume=False, tja_toggle=False):
"""
Creates a CAN message for the Ford SCCM buttons/switches.
Includes cruise control buttons, turn lights and more.
Frequency is 10Hz.
"""
values = {s: stock_values[s] for s in [
"HeadLghtHiFla... |
Creates a CAN message for the Ford SCCM buttons/switches.
Includes cruise control buttons, turn lights and more.
Frequency is 10Hz.
| create_button_msg | python | commaai/opendbc | opendbc/car/ford/fordcan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py | MIT |
def cluster_points(pts_l: list[list[float]], pts2_l: list[list[float]], max_dist: float) -> list[int]:
"""
Clusters a collection of points based on another collection of points. This is useful for correlating clusters through time.
Points in pts2 not close enough to any point in pts are assigned -1.
Args:
p... |
Clusters a collection of points based on another collection of points. This is useful for correlating clusters through time.
Points in pts2 not close enough to any point in pts are assigned -1.
Args:
pts_l: List of points to base the new clusters on
pts2_l: List of points to cluster using pts
max_dis... | cluster_points | python | commaai/opendbc | opendbc/car/ford/radar_interface.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/radar_interface.py | MIT |
def test_platform_codes_fuzzy_fw(self, data):
"""Ensure function doesn't raise an exception"""
fw_strategy = st.lists(st.binary())
fws = data.draw(fw_strategy)
get_platform_codes(fws) | Ensure function doesn't raise an exception | test_platform_codes_fuzzy_fw | python | commaai/opendbc | opendbc/car/ford/tests/test_ford.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/tests/test_ford.py | MIT |
def test_correct_ecu_response_database(self, subtests):
"""
Assert standard responses for certain ECUs, since they can
respond to multiple queries with different data
"""
expected_fw_prefix = HYUNDAI_VERSION_REQUEST_LONG[1:]
for car_model, ecus in FW_VERSIONS.items():
with subtests.test(ca... |
Assert standard responses for certain ECUs, since they can
respond to multiple queries with different data
| test_correct_ecu_response_database | python | commaai/opendbc | opendbc/car/hyundai/tests/test_hyundai.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/hyundai/tests/test_hyundai.py | MIT |
def test_platform_codes_fuzzy_fw(self, data):
"""Ensure function doesn't raise an exception"""
fw_strategy = st.lists(st.binary())
fws = data.draw(fw_strategy)
get_platform_codes(fws) | Ensure function doesn't raise an exception | test_platform_codes_fuzzy_fw | python | commaai/opendbc | opendbc/car/hyundai/tests/test_hyundai.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/hyundai/tests/test_hyundai.py | MIT |
def test_can_fingerprint(self, car_model, fingerprints):
"""Tests online fingerprinting function on offline fingerprints"""
for fingerprint in fingerprints: # can have multiple fingerprints for each platform
can = [CanData(address=address, dat=b'\x00' * length, src=src)
for address, length ... | Tests online fingerprinting function on offline fingerprints | test_can_fingerprint | python | commaai/opendbc | opendbc/car/tests/test_can_fingerprint.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_can_fingerprint.py | MIT |
def test_interface_attrs(self):
"""Asserts basic behavior of interface attribute getter"""
num_brands = len(get_interface_attr('CAR'))
assert num_brands >= 12
# Should return value for all brands when not combining, even if attribute doesn't exist
ret = get_interface_attr('FAKE_ATTR')
assert le... | Asserts basic behavior of interface attribute getter | test_interface_attrs | python | commaai/opendbc | opendbc/car/tests/test_car_interfaces.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_car_interfaces.py | MIT |
def fake_set_obd_multiplexing(self, obd_multiplexing):
"""The 10Hz blocking params loop adds on average 50ms to the query time for each OBD multiplexing change"""
if obd_multiplexing != self.current_obd_multiplexing:
self.current_obd_multiplexing = obd_multiplexing
self.total_time += 0.1 / 2 | The 10Hz blocking params loop adds on average 50ms to the query time for each OBD multiplexing change | fake_set_obd_multiplexing | python | commaai/opendbc | opendbc/car/tests/test_fw_fingerprint.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_fw_fingerprint.py | MIT |
def test_dyn_ss_sol_against_yaw_rate(self):
"""Verify that the yaw_rate helper function matches the results
from the state space model."""
for roll in np.linspace(math.radians(-20), math.radians(20), num=11):
for u in np.linspace(1, 30, num=10):
for sa in np.linspace(math.radians(-20), math.r... | Verify that the yaw_rate helper function matches the results
from the state space model. | test_dyn_ss_sol_against_yaw_rate | python | commaai/opendbc | opendbc/car/tests/test_vehicle_model.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_vehicle_model.py | MIT |
def create_steer_command(packer, steer, steer_req):
"""Creates a CAN message for the Toyota Steer Command."""
values = {
"STEER_REQUEST": steer_req,
"STEER_TORQUE_CMD": steer,
"SET_ME_1": 1,
}
return packer.make_can_msg("STEERING_LKA", 0, values) | Creates a CAN message for the Toyota Steer Command. | create_steer_command | python | commaai/opendbc | opendbc/car/toyota/toyotacan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/toyota/toyotacan.py | MIT |
def create_lta_steer_command(packer, steer_control_type, steer_angle, steer_req, frame, torque_wind_down):
"""Creates a CAN message for the Toyota LTA Steer Command."""
values = {
"COUNTER": frame + 128,
"SETME_X1": 1, # suspected LTA feature availability
# 1 for TSS 2.5 cars, 3 for TSS 2.0. Send base... | Creates a CAN message for the Toyota LTA Steer Command. | create_lta_steer_command | python | commaai/opendbc | opendbc/car/toyota/toyotacan.py | https://github.com/commaai/opendbc/blob/master/opendbc/car/toyota/toyotacan.py | MIT |
def add_regen_tests(cls):
"""Dynamically adds regen tests for all user brake tests."""
# only rx/user brake tests, not brake command
found_tests = [func for func in dir(cls) if func.startswith("test_") and "user_brake" in func]
assert len(found_tests) >= 3, "Failed to detect known brake tests"
for test in f... | Dynamically adds regen tests for all user brake tests. | add_regen_tests | python | commaai/opendbc | opendbc/safety/tests/common.py | https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py | MIT |
def _common_measurement_test(self, msg_func: Callable, min_value: float, max_value: float, factor: float,
meas_min_func: Callable[[], int], meas_max_func: Callable[[], int]):
"""Tests accurate measurement parsing, and that the struct is reset on safety mode init"""
for val in np.a... | Tests accurate measurement parsing, and that the struct is reset on safety mode init | _common_measurement_test | python | commaai/opendbc | opendbc/safety/tests/common.py | https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py | MIT |
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 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.