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
Handle the slice object case in TransformGenerator.__getitem__
diff --git a/pathod/language/generators.py b/pathod/language/generators.py index 01f709e2b0..9fff3082f0 100644 --- a/pathod/language/generators.py +++ b/pathod/language/generators.py @@ -37,6 +37,8 @@ def __len__(self): def __getitem__(self, x): d = self.gen.__getitem__(x) + if isinstance(x, slice): + return self.transform(x.start, d) return self.transform(x, d) def __repr__(self):
should fix https://travis-ci.org/mitmproxy/mitmproxy/jobs/134827120#L501 test failures: ``` self = <netlib.websockets.protocol.Masker object at 0x7fe8ebdfc110> offset = slice(0, 3, None), data = 'foo' def mask(self, offset, data): result = bytearray(data) if six.PY2: for i in range(len(data)): > result[i] ^= ord(self.key[offset % 4]) E TypeError: unsupported operand type(s) for %: 'slice' and 'int' netlib/websockets/protocol.py:47: TypeError ```
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/1199
2016-06-02T20:32:20Z
2016-06-02T20:45:56Z
2016-06-02T20:45:56Z
2016-06-02T20:48:44Z
131
mitmproxy/mitmproxy
27,472
更新 PPOCRLabel 导出 JSON 文件的错误,更新了配置文件 SLANet_ch.yml 中 Eval - datadir 前多余的空格。
diff --git a/PPOCRLabel/PPOCRLabel.py b/PPOCRLabel/PPOCRLabel.py index c17db91a5b..d0d2bb721b 100644 --- a/PPOCRLabel/PPOCRLabel.py +++ b/PPOCRLabel/PPOCRLabel.py @@ -2531,7 +2531,7 @@ def exportJSON(self): split = 'test' # save dict - html = {'structure': {'tokens': token_list}, 'cell': cells} + html = {'structure': {'tokens': token_list}, 'cells': cells} json_results.append({'filename': os.path.basename(image_path), 'split': split, 'imgid': imgid, 'html': html}) imgid += 1 diff --git a/configs/table/SLANet_ch.yml b/configs/table/SLANet_ch.yml index 997ff0a77b..a3fc1c68dd 100644 --- a/configs/table/SLANet_ch.yml +++ b/configs/table/SLANet_ch.yml @@ -107,7 +107,7 @@ Train: Eval: dataset: name: PubTabDataSet - data_dir: train_data/table/val/ + data_dir: train_data/table/val/ label_file_list: [train_data/table/val.txt] transforms: - DecodeImage:
解决了导出 JSON 文件时,L2534 将 "cells" 写成 "cell" 的问题。因如下代码取的是cells,否则在训练载入数据时会报 keyerror 的错误。 https://github.com/PaddlePaddle/PaddleOCR/blob/282eebbd660886c38d4ae91bcbcd70b5cdc03f75/ppocr/data/pubtab_dataset.py#L102
https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/7445
2022-09-01T00:46:36Z
2022-09-01T08:01:16Z
2022-09-01T08:01:16Z
2022-09-01T08:01:16Z
307
PaddlePaddle/PaddleOCR
41,836
hwp
diff --git a/CHANGELOG.md b/CHANGELOG.md index 450071ad4ca8d..3b49b4ed0ac1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### New Features +- Added `HWPReader` (#7672) - Simplified portkey LLM interface (#7669) - Added async operation support to `ElasticsearchStore` vector store (#7613) diff --git a/llama_index/readers/file/base.py b/llama_index/readers/file/base.py index 6fe9eb53bd268..b21c6d450c71b 100644 --- a/llama_index/readers/file/base.py +++ b/llama_index/readers/file/base.py @@ -5,7 +5,7 @@ from typing import Callable, Dict, Generator, List, Optional, Type from llama_index.readers.base import BaseReader -from llama_index.readers.file.docs_reader import DocxReader, PDFReader +from llama_index.readers.file.docs_reader import DocxReader, PDFReader, HWPReader from llama_index.readers.file.epub_reader import EpubReader from llama_index.readers.file.image_reader import ImageReader from llama_index.readers.file.ipynb_reader import IPYNBReader @@ -17,6 +17,7 @@ from llama_index.schema import Document DEFAULT_FILE_READER_CLS: Dict[str, Type[BaseReader]] = { + ".hwp": HWPReader, ".pdf": PDFReader, ".docx": DocxReader, ".pptx": PptxReader, diff --git a/llama_index/readers/file/docs_reader.py b/llama_index/readers/file/docs_reader.py index 05ab0246f6c5f..57954d7c7e781 100644 --- a/llama_index/readers/file/docs_reader.py +++ b/llama_index/readers/file/docs_reader.py @@ -3,8 +3,11 @@ Contains parsers for docx, pdf files. """ +import zlib +import struct + from pathlib import Path -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional from llama_index.readers.base import BaseReader from llama_index.schema import Document @@ -66,3 +69,102 @@ def load_data( metadata.update(extra_info) return [Document(text=text, metadata=metadata or {})] + + +class HWPReader(BaseReader): + """Hwp Parser""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.FILE_HEADER_SECTION = "FileHeader" + self.HWP_SUMMARY_SECTION = "\x05HwpSummaryInformation" + self.SECTION_NAME_LENGTH = len("Section") + self.BODYTEXT_SECTION = "BodyText" + self.HWP_TEXT_TAGS = [67] + self.text = "" + + def load_data( + self, file: Path, extra_info: Optional[Dict] = None + ) -> List[Document]: + """Load data and extract table from Hwp file. + Args: + file (Path): Path for the Hwp file. + Returns: + List[Document] + """ + import olefile + + load_file = olefile.OleFileIO(file) + file_dir = load_file.listdir() + if self.is_valid(file_dir) is False: + raise Exception("Not Valid HwpFile") + + result_text = self._get_text(load_file, file_dir) + result = self._text_to_document(text=result_text, extra_info=extra_info) + return [result] + + def is_valid(self, dirs: List[str]) -> bool: + if [self.FILE_HEADER_SECTION] not in dirs: + return False + + return [self.HWP_SUMMARY_SECTION] in dirs + + def get_body_sections(self, dirs: List[str]) -> List[str]: + m = [] + for d in dirs: + if d[0] == self.BODYTEXT_SECTION: + m.append(int(d[1][self.SECTION_NAME_LENGTH :])) + + return ["BodyText/Section" + str(x) for x in sorted(m)] + + def _text_to_document( + self, text: str, extra_info: Optional[Dict] = None + ) -> Document: + return Document(text=text, extra_info=extra_info or {}) + + def get_text(self) -> str: + return self.text + + # 전체 text 추출 + + def _get_text(self, load_file: Any, file_dirs: List[str]) -> str: + sections = self.get_body_sections(file_dirs) + text = "" + for section in sections: + text += self.get_text_from_section(load_file, section) + text += "\n" + + self.text = text + return self.text + + def is_compressed(self, load_file: Any) -> bool: + header = load_file.openstream("FileHeader") + header_data = header.read() + return (header_data[36] & 1) == 1 + + def get_text_from_section(self, load_file: Any, section: str) -> str: + bodytext = load_file.openstream(section) + data = bodytext.read() + + unpacked_data = ( + zlib.decompress(data, -15) if self.is_compressed(load_file) else data + ) + size = len(unpacked_data) + + i = 0 + + text = "" + while i < size: + header = struct.unpack_from("<I", unpacked_data, i)[0] + rec_type = header & 0x3FF + (header >> 10) & 0x3FF + rec_len = (header >> 20) & 0xFFF + + if rec_type in self.HWP_TEXT_TAGS: + rec_data = unpacked_data[i + 4 : i + 4 + rec_len] + text += rec_data.decode("utf-16") + text += "\n" + + i += 4 + rec_len + + return text
Added hwp reader module.
https://api.github.com/repos/run-llama/llama_index/pulls/7672
2023-09-14T06:57:51Z
2023-09-15T15:24:33Z
2023-09-15T15:24:33Z
2023-09-15T15:24:33Z
1,411
run-llama/llama_index
6,141
Update readme.md
diff --git a/readme.md b/readme.md index 102854c54..88b887cad 100644 --- a/readme.md +++ b/readme.md @@ -167,7 +167,7 @@ Same with the above instructions. You need to change torch to AMD version pip uninstall torch torchvision torchaudio torchtext functorch xformers pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm5.6 -AMD is not intensively tested, however. +AMD is not intensively tested, however. The AMD support is in beta. ### Windows(AMD GPUs) @@ -180,9 +180,22 @@ Same with Windows. Download the software, edit the content of `run.bat` as: Then run the `run.bat`. +AMD is not intensively tested, however. The AMD support is in beta. + ### Mac -Coming soon ... +Mac is not intensively tested. Below is an unofficial guideline for using Mac. You can discuss problems [here](https://github.com/lllyasviel/Fooocus/pull/129). + +You can install Fooocus on Apple Mac silicon (M1 or M2) with macOS 'Catalina' or a newer version. Fooocus runs on Apple silicon computers via [PyTorch](https://pytorch.org/get-started/locally/) MPS device acceleration. + +> :point_up: Mac Silicon computers don't come with a dedicated graphics card, resulting in significantly longer image processing times compared to computers with dedicated graphics cards. +1. Install the conda package manager and pytorch nightly. Read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide for instructions. Make sure pytorch recognizes your MPS device. +1. Open the macOS Terminal app and clone this repository with `git clone https://github.com/lllyasviel/Fooocus.git`. +1. Change to the new Fooocus directory, `cd Fooocus`. +1. Create a new conda environment, `conda env create -f environment.yaml`. +1. Activate your new conda environment, `conda activate fooocus`. +1. Install the packages required by Fooocus, `pip install -r requirements_versions.txt`. +1. Launch Fooocus by running `python launch.py`. The first time you run Fooocus, it will automatically download the Stable Diffusion SDXL models and will take a significant time, depending on your internet connection. ## List of "Hidden" Tricks <a name="tech_list"></a>
https://api.github.com/repos/lllyasviel/Fooocus/pulls/608
2023-10-09T22:53:40Z
2023-10-09T22:53:55Z
2023-10-09T22:53:55Z
2023-10-09T22:55:05Z
556
lllyasviel/Fooocus
6,981
typo fix: flask -> flag
diff --git a/flask/app.py b/flask/app.py index 48369ee441..47254bedf3 100644 --- a/flask/app.py +++ b/flask/app.py @@ -112,7 +112,7 @@ class Flask(_PackageBoundObject): #: configuration key. Defaults to `False`. debug = ConfigAttribute('DEBUG') - #: The testing flask. Set this to `True` to enable the test mode of + #: The testing flag. Set this to `True` to enable the test mode of #: Flask extensions (and in the future probably also Flask itself). #: For example this might activate unittest helpers that have an #: additional runtime cost which should not be enabled by default.
https://api.github.com/repos/pallets/flask/pulls/275
2011-07-11T22:25:56Z
2011-07-12T00:41:17Z
2011-07-12T00:41:16Z
2020-11-14T07:18:45Z
164
pallets/flask
20,207
Add layer - neural network inference from the command line
diff --git a/README.md b/README.md index b012d00f..d84dc70c 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,8 @@ Further resources: - [Natural Language Processing](#scala-nlp) - [Data Analysis / Data Visualization](#scala-data-analysis) - [General-Purpose Machine Learning](#scala-general-purpose) +- [Scheme](#scheme) + - [Neural Networks](#scheme-neural-networks) - [Swift](#swift) - [General-Purpose Machine Learning](#swift-general-purpose) - [TensorFlow](#tensor) @@ -133,6 +135,7 @@ Further resources: ### Tools +- [Neural Networks](#tools-neural-networks) - [Misc](#tools-misc) @@ -1406,6 +1409,14 @@ be * [Smile](http://haifengl.github.io/smile/) - Statistical Machine Intelligence and Learning Engine. * [doddle-model](https://github.com/picnicml/doddle-model) - An in-memory machine learning library built on top of Breeze. It provides immutable objects and exposes its functionality through a scikit-learn-like API. +<a name="scheme"></a> +## Scheme + +<a name="scheme-neural-networks"></a> +#### Neural Networks + +* [layer](https://github.com/cloudkj/layer) - Neural network inference from the command line, implemented in [CHICKEN Scheme](https://www.call-cc.org/). + <a name="swift"></a> ## Swift @@ -1438,6 +1449,10 @@ be <a name="tools"></a> ## Tools +<a name="tools-neural-networks"></a> +#### Neural Networks +* [layer](https://github.com/cloudkj/layer) - Neural network inference from the command line + <a name="tools-misc"></a> #### Misc * [Notebooks](https://github.com/rlan/notebooks) - A starter kit for Jupyter notebooks and machine learning. Companion docker images consist of all combinations of python versions, machine learning frameworks (Keras, PyTorch and Tensorflow) and CPU/CUDA versions.
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/582
2019-01-21T18:08:03Z
2019-01-21T18:24:31Z
2019-01-21T18:24:31Z
2019-01-21T18:24:31Z
498
josephmisiti/awesome-machine-learning
51,963
Update Hugging Face Hub instructions
diff --git a/README.md b/README.md index 960d5a2e..d962390a 100755 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Keep in mind that the links expire after 24 hours and a certain amount of downlo ### Access to Hugging Face -We are also providing downloads on [Hugging Face](https://huggingface.co/meta-llama). You must first request a download from the Meta website using the same email address as your Hugging Face account. After doing so, you can request access to any of the models on Hugging Face and within 1-2 days your account will be granted access to all versions. +We are also providing downloads on [Hugging Face](https://huggingface.co/meta-llama). You can request access to the models by acknowledging the license and filling the form in the model card of a repo. After doing so, you should get access to all the Llama models of a version (Code Llama, Llama 2, or Llama Guard) within 1 hour. ## Quick Start
https://api.github.com/repos/meta-llama/llama/pulls/1091
2024-04-08T14:13:07Z
2024-04-09T16:16:49Z
2024-04-09T16:16:48Z
2024-04-09T16:16:49Z
245
meta-llama/llama
31,971
merge google/flan based adapters: T5Adapter, CodeT5pAdapter, FlanAdapter
diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 296b53c8f3..0a660d9e9c 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -23,7 +23,6 @@ AutoTokenizer, LlamaTokenizer, LlamaForCausalLM, - T5Tokenizer, ) from fastchat.constants import CPU_ISA @@ -31,9 +30,7 @@ from fastchat.modules.awq import AWQConfig, load_awq_quantized from fastchat.conversation import Conversation, get_conv_template from fastchat.model.compression import load_compress_model -from fastchat.model.llama_condense_monkey_patch import ( - replace_llama_with_condense, -) +from fastchat.model.llama_condense_monkey_patch import replace_llama_with_condense from fastchat.model.model_chatglm import generate_stream_chatglm from fastchat.model.model_codet5p import generate_stream_codet5p from fastchat.model.model_falcon import generate_stream_falcon @@ -616,11 +613,14 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("vicuna_v1.1") -class CodeT5pAdapter(BaseModelAdapter): - """The model adapter for Salesforce/codet5p-6b""" +class GoogleFlanAdapter(BaseModelAdapter): + """The model adapter for google/Flan based models, such as Salesforce/codet5p-6b, lmsys/fastchat-t5-3b-v1.0, flan-t5-*, flan-ul2""" def match(self, model_path: str): - return "codet5p" in model_path.lower() + return any( + model_str in model_path.lower() + for model_str in ["flan-", "fastchat-t5", "codet5p"] + ) def load_model(self, model_path: str, from_pretrained_kwargs: dict): revision = from_pretrained_kwargs.get("revision", "main") @@ -634,28 +634,6 @@ def load_model(self, model_path: str, from_pretrained_kwargs: dict): return model, tokenizer -class T5Adapter(BaseModelAdapter): - """The model adapter for lmsys/fastchat-t5-3b-v1.0""" - - def match(self, model_path: str): - return "t5" in model_path.lower() - - def load_model(self, model_path: str, from_pretrained_kwargs: dict): - revision = from_pretrained_kwargs.get("revision", "main") - tokenizer = T5Tokenizer.from_pretrained(model_path, revision=revision) - model = AutoModelForSeq2SeqLM.from_pretrained( - model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs - ) - return model, tokenizer - - -class FlanAdapter(T5Adapter): - """The model adapter for flan-t5-*, flan-ul2""" - - def match(self, model_path: str): - return "flan" in model_path.lower() - - class KoalaAdapter(BaseModelAdapter): """The model adapter for koala""" @@ -1599,9 +1577,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(VicunaAdapter) register_model_adapter(AiroborosAdapter) register_model_adapter(LongChatAdapter) -register_model_adapter(CodeT5pAdapter) -register_model_adapter(T5Adapter) -register_model_adapter(FlanAdapter) +register_model_adapter(GoogleFlanAdapter) register_model_adapter(KoalaAdapter) register_model_adapter(AlpacaAdapter) register_model_adapter(ChatGLMAdapter)
## Why are these changes needed? merge multiple google/flan based adapters (T5Adapter, CodeT5pAdapter, FlanAdapter) together. ## Related issue number (if applicable) <!-- For example: "Closes #1234" --> ## Checks - [x] 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/2411
2023-09-13T04:58:58Z
2023-09-18T20:18:39Z
2023-09-18T20:18:39Z
2023-09-18T20:18:39Z
828
lm-sys/FastChat
41,550
version bump 13.5.0
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c3c2dcb3..61d5cc8d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ 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). -## Unreleased +## [13.5.0] - 2023-07-29 ### Fixed diff --git a/pyproject.toml b/pyproject.toml index 531c8d168..8c62eacb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "rich" homepage = "https://github.com/Textualize/rich" documentation = "https://rich.readthedocs.io/en/latest/" -version = "13.4.2" +version = "13.5.0" description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" authors = ["Will McGugan <willmcgugan@gmail.com>"] license = "MIT"
https://api.github.com/repos/Textualize/rich/pulls/3066
2023-07-29T16:10:04Z
2023-07-29T16:16:47Z
2023-07-29T16:16:47Z
2023-07-29T16:16:48Z
290
Textualize/rich
48,008
consistently opening braces for multiline function def on new line
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 832fd9cc2..4e079d12f 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -2548,13 +2548,15 @@ And yes, C++ does have multiple return values, by convention of using a `tuple`, ##### Example - int f(const string& input, /*output only*/ string& output_data) { // BAD: output-only parameter documented in a comment + int f(const string& input, /*output only*/ string& output_data) // BAD: output-only parameter documented in a comment + { // ... output_data = something(); return status; } - tuple<int, string> f(const string& input) { // GOOD: self-documenting + tuple<int, string> f(const string& input) // GOOD: self-documenting + { // ... return make_tuple(something(), status); } @@ -2768,7 +2770,8 @@ For passthrough functions that pass in parameters (by ordinary reference or by p If `F` returns by value, this function returns a reference to a temporary. template<class F> - auto&& wrapper(F f) { + auto&& wrapper(F f) + { log_call(typeid(f)); // or whatever instrumentation return f(); } @@ -2778,7 +2781,8 @@ If `F` returns by value, this function returns a reference to a temporary. Better: template<class F> - auto wrapper(F f) { + auto wrapper(F f) + { log_call(typeid(f)); // or whatever instrumentation return f(); } @@ -2861,7 +2865,8 @@ Flag all uses of default arguments in virtual functions. This is a simple three-stage parallel pipeline. Each `stage` object encapsulates a worker thread and a queue, has a `process` function to enqueue work, and in its destructor automatically blocks waiting for the queue to empty before ending the thread. - void send_packets(buffers& bufs) { + void send_packets(buffers& bufs) + { stage encryptor ([] (buffer& b){ encrypt(b); }); stage compressor ([&](buffer& b){ compress(b); encryptor.process(b); }); stage decorator ([&](buffer& b){ decorate(b); compressor.process(b); }); @@ -4351,8 +4356,7 @@ But what if you can get significant better performance by not making a temporary Vector& Vector::operator=(const Vector& a) { - if (a.sz>sz) - { + if (a.sz>sz) { // ... use the swap technique, it can't be bettered ... return *this } @@ -6016,7 +6020,8 @@ Whenever you deal with a resource that needs paired acquire/release function cal Consider: - void send(X* x, cstring_view destination) { + void send(X* x, cstring_view destination) + { auto port = OpenPort(destination); my_mutex.lock(); // ... @@ -6034,7 +6039,8 @@ Further, if any of the code marked `...` throws an exception, then `x` is leaked Consider: - void send(unique_ptr<X> x, cstring_view destination) { // x owns the X + void send(unique_ptr<X> x, cstring_view destination) // x owns the X + { Port port{destination}; // port owns the PortHandle lock_guard<mutex> guard{my_mutex}; // guard owns the lock // ... @@ -6564,7 +6570,8 @@ A function that does not manipulate lifetime should take raw pointers or referen ##### Example, bad // callee - void f(shared_ptr<widget>& w) { + void f(shared_ptr<widget>& w) + { // ... use(*w); // only use of w -- the lifetime is not used at all // ... @@ -6580,7 +6587,8 @@ A function that does not manipulate lifetime should take raw pointers or referen ##### Example, good // callee - void f(widget& w) { + void f(widget& w) + { // ... use(w); // ... @@ -6614,13 +6622,15 @@ Any type (including primary template or specialization) that overloads unary `*` // use Boost's intrusive_ptr #include <boost/intrusive_ptr.hpp> - void f(boost::intrusive_ptr<widget> p) { // error under rule 'sharedptrparam' + void f(boost::intrusive_ptr<widget> p) // error under rule 'sharedptrparam' + { p->foo(); } // use Microsoft's CComPtr #include <atlbase.h> - void f(CComPtr<widget> p) { // error under rule 'sharedptrparam' + void f(CComPtr<widget> p) // error under rule 'sharedptrparam' + { p->foo(); } @@ -6759,18 +6769,21 @@ Consider this code: // global (static or heap), or aliased local... shared_ptr<widget> g_p = ...; - void f(widget& w) { + void f(widget& w) + { g(); use(w); // A } - void g() { + void g() + { g_p = ... ; // oops, if this was the last shared_ptr to that widget, destroys the widget } The following should not pass code review: - void my_code() { + void my_code() + { f(*g_p); // BAD: passing pointer or reference obtained from a nonlocal smart pointer // that could be inadvertently reset somewhere inside f or it callees g_p->func(); // BAD: same reason, just passing it as a "this" pointer @@ -6778,7 +6791,8 @@ The following should not pass code review: The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree: - void my_code() { + void my_code() + { auto pin = g_p; // cheap: 1 increment covers this entire function and all the call trees below us f(*pin); // GOOD: passing pointer or reference obtained from a local unaliased smart pointer pin->func(); // GOOD: same reason @@ -10528,21 +10542,24 @@ There are three major ways to let calling code customize a template. * Call a member function. Callers can provide any type with such a named member function. template<class T> - void test(T t) { + void test(T t) + { t.f(); // require T to provide f() } * Call a nonmember function without qualification. Callers can provide any type for which there is such a function available in the caller's context or in the namespace of the type. template<class T> - void test(T t) { + void test(T t) + { f(t); // require f(/*T*/) be available in caller's cope or in T's namespace } * Invoke a "trait" -- usually a type alias to compute a type, or a `constexpr` function to compute a value, or in rarer cases a traditional traits template to be specialized on the user's type. template<class T> - void test(T t) { + void test(T t) + { test_traits<T>::f(t); // require customizing test_traits<> to get non-default functions/types test_traits<T>::value_type x; } @@ -11031,12 +11048,14 @@ Use the least-derived class that has the functionality you need. void j(); }; - void myfunc(derived& param) { // bad, unless there is a specific reason for limiting to derived1 objects only + void myfunc(derived& param) // bad, unless there is a specific reason for limiting to derived1 objects only + { use(param.f()); use(param.g()); } - void myfunc(base& param) { // good, uses only base interface so only commit to that + void myfunc(base& param) // good, uses only base interface so only commit to that + { use(param.f()); use(param.g()); } @@ -11749,7 +11768,8 @@ Casting away `const` is a lie. If the variable is actually declared `const`, it' ##### Example, bad - void f(const int& i) { + void f(const int& i) + { const_cast<int&>(i) = 42; // BAD } @@ -12808,7 +12828,8 @@ Here is an example of the last option: virtual void f() = 0; template<class T> - static shared_ptr<T> Create() { // interface for creating objects + static shared_ptr<T> Create() // interface for creating objects + { auto p = make_shared<T>(); p->PostInitialize(); return p; @@ -12922,7 +12943,8 @@ Never allow an error to be reported from a destructor, a resource deallocation f 1. `nefarious` objects are hard to use safely even as local variables: - void test(string& s) { + void test(string& s) + { nefarious n; // trouble brewing string copy = s; // copy the string } // destroy copy and then n @@ -12937,7 +12959,8 @@ Here, copying `s` could throw, and if that throws and if `n`'s destructor then a // ... }; - void test(string& s) { + void test(string& s) + { innocent_bystander i; // more trouble brewing string copy = s; // copy the string } // destroy copy and then i @@ -12952,7 +12975,8 @@ Here, if constructing `copy2` throws, we have the same problem because `i`'s des 4. You can't reliably create arrays of `nefarious`: - void test() { + void test() + { std::array<nefarious, 10> arr; // this line can std::terminate(!) }
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/276
2015-10-03T11:39:07Z
2015-10-05T10:59:06Z
2015-10-05T10:59:06Z
2015-10-05T11:12:21Z
2,379
isocpp/CppCoreGuidelines
15,928
Add Lemur model
diff --git a/docs/model_support.md b/docs/model_support.md index 24f3bc9cc5..9d1aedddc9 100644 --- a/docs/model_support.md +++ b/docs/model_support.md @@ -48,6 +48,7 @@ - [HuggingFaceH4/starchat-beta](https://huggingface.co/HuggingFaceH4/starchat-beta) - [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) - 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 b1c66ee796..a8bdb1cb6a 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -639,6 +639,21 @@ def get_conv_template(name: str) -> Conversation: ) ) +# Lemur-70b-chat default template +# reference: https://huggingface.co/OpenLemur/lemur-70b-chat-v1#generation +register_conv_template( + Conversation( + name="lemur-70b-chat", + system_template="""<|im_start|>system +{system_message}""", + system_message="""You are a helpful, respectful, and honest assistant.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32002, 0], + ) +) + # MPT-30b-instruct default template # reference: https://huggingface.co/mosaicml/mpt-30b-instruct#formatting register_conv_template( diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 7c1ed844f9..cf7bc4d3ee 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -1681,6 +1681,18 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("vicuna_v1.1") +class LemurAdapter(BaseModelAdapter): + """The model adapter for OpenLemur/lemur-70b-chat-v1""" + + use_fast_tokenizer = False + + def match(self, model_path: str): + return "lemur-70b-chat" in model_path.lower() + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("lemur-70b-chat") + + # Note: the registration order matters. # The one registered earlier has a higher matching priority. register_model_adapter(PeftModelAdapter) @@ -1742,6 +1754,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(Llama2ChangAdapter) register_model_adapter(ZephyrAdapter) register_model_adapter(XwinLMAdapter) +register_model_adapter(LemurAdapter) # 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 d692e41142..3ade406b59 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -339,6 +339,13 @@ def get_model_info(name: str) -> ModelInfo: "Chat models developed by Xwin-LM team", ) +register_model_info( + ["lemur-70b-chat"], + "Lemur-Chat", + "https://huggingface.co/OpenLemur/lemur-70b-chat-v1", + "an openly accessible language model optimized for both natural language and coding capabilities ", +) + register_model_info( ["Mistral-7B-OpenOrca"], "Open-Orca",
<!-- 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? Support the model https://huggingface.co/OpenLemur/lemur-70b-chat-v1 which uses the ChatML template. ## Related issue number (if applicable) <!-- For example: "Closes #1234" --> ## Checks - [x] 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/2584
2023-10-19T14:36:14Z
2023-10-24T01:23:52Z
2023-10-24T01:23:52Z
2023-10-24T01:23:53Z
1,049
lm-sys/FastChat
41,514
Filter the None labels
diff --git a/utils/datasets.py b/utils/datasets.py index 7ed8f5a1d80..338400e6340 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -375,7 +375,7 @@ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, r pbar = tqdm(self.label_files) for i, file in enumerate(pbar): l = self.labels[i] # label - if l.shape[0]: + if l is not None and l.shape[0]: assert l.shape[1] == 5, '> 5 label columns: %s' % file assert (l >= 0).all(), 'negative labels: %s' % file assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Improved label loading robustness in dataset processing. ### 📊 Key Changes - Added an additional check to verify that labels are not `None` before processing them. ### 🎯 Purpose & Impact - **Purpose:** Prevent errors that could occur when a label file is empty or corrupted. - **Impact:** Enhances the stability of dataset loading, reducing the likelihood of crashes during model training and evaluation due to problematic label data. This makes the YOLOv5 user experience more reliable for developers working on object detection tasks.
https://api.github.com/repos/ultralytics/yolov5/pulls/705
2020-08-11T03:04:06Z
2020-08-11T18:15:49Z
2020-08-11T18:15:49Z
2024-01-19T21:08:14Z
211
ultralytics/yolov5
25,592
add Line to Social
diff --git a/README.md b/README.md index 0d59bc8ab7..f1ef4b3a86 100644 --- a/README.md +++ b/README.md @@ -1048,6 +1048,7 @@ API | Description | Auth | HTTPS | CORS | | [HackerNews](https://github.com/HackerNews/API) | Social news for CS and entrepreneurship | No | Yes | Unknown | | [Instagram](https://www.instagram.com/developer/) | Instagram Login, Share on Instagram, Social Plugins and more | `OAuth` | Yes | Unknown | | [Kakao](https://developers.kakao.com/) | Kakao Login, Share on KakaoTalk, Social Plugins and more | `OAuth` | Yes | Unknown | +| [Line](https://developers.line.biz/) | Line Login, Share on Line, Social Plugins and more | `OAuth` | Yes | Unknown | | [LinkedIn](https://docs.microsoft.com/en-us/linkedin/?context=linkedin/context) | The foundation of all digital integrations with LinkedIn | `OAuth` | Yes | Unknown | | [Meetup.com](https://www.meetup.com/meetup_api/) | Data about Meetups from Meetup.com | `apiKey` | Yes | Unknown | | [MySocialApp](https://mysocialapp.io) | Seamless Social Networking features, API, SDK to any app | `apiKey` | Yes | Unknown |
<!-- 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: --> - [x] My submission is formatted according to the guidelines in the [contributing guide](/CONTRIBUTING.md) - [x] My addition is ordered alphabetically - [x] My submission has a useful description - [x] The description does not end with punctuation - [x] Each table column is padded with one space on either side - [x] I have searched the repository for any relevant issues or pull requests - [x] Any category I am creating has the minimum requirement of 3 items - [x] All changes have been [squashed][squash-link] into a single commit [squash-link]: <https://github.com/todotxt/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit> Add Line to Social #2148
https://api.github.com/repos/public-apis/public-apis/pulls/2149
2021-10-03T02:13:37Z
2021-10-06T06:54:39Z
2021-10-06T06:54:39Z
2021-10-06T06:54:39Z
309
public-apis/public-apis
35,682
Lambda: add function properties to LambdaContext for invocations
diff --git a/localstack/services/awslambda/lambda_api.py b/localstack/services/awslambda/lambda_api.py index c5156db076fde..c129b101430e9 100644 --- a/localstack/services/awslambda/lambda_api.py +++ b/localstack/services/awslambda/lambda_api.py @@ -10,6 +10,7 @@ import base64 import threading import imp +import re from io import BytesIO from datetime import datetime from six import iteritems @@ -72,6 +73,15 @@ class LambdaContext(object): + + def __init__(self, func_details, qualifier=None): + self.function_name = func_details.name() + self.function_version = func_details.get_qualifier_version(qualifier) + + self.invoked_function_arn = func_details.arn() + if qualifier: + self.invoked_function_arn += ':' + qualifier + def get_remaining_time_in_millis(self): # TODO implement! return 1000 * 60 @@ -254,7 +264,7 @@ def run_lambda(event, context, func_arn, version=None, suppress_output=False, as try: func_details = arn_to_lambda.get(func_arn) if not context: - context = LambdaContext() + context = LambdaContext(func_details, version) result, log_output = LAMBDA_EXECUTOR.execute(func_arn, func_details, event, context=context, version=version, async=async) except Exception as e: @@ -531,6 +541,8 @@ def create_function(): 'TracingConfig': {}, 'VpcConfig': {'SecurityGroupIds': [None], 'SubnetIds': [None], 'VpcId': None} }) + if data.get('Publish', False): + result['Version'] = publish_new_function_version(arn)['Version'] return jsonify(result or {}) except Exception as e: del arn_to_lambda[arn] @@ -693,11 +705,20 @@ def invoke_function(function): - name: 'request' in: body """ + # function here can either be an arn or a function name arn = func_arn(function) + + # arn can also contain a qualifier, extract it from there if so + m = re.match('(arn:aws:lambda:.*:.*:function:[a-zA-Z0-9-_]+)(:.*)?', arn) + if m and m.group(2): + qualifier = m.group(2)[1:] + arn = m.group(1) + else: + qualifier = request.args.get('Qualifier') + if arn not in arn_to_lambda: return error_response('Function does not exist: %s' % arn, 404, error_type='ResourceNotFoundException') - qualifier = request.args['Qualifier'] if 'Qualifier' in request.args else '$LATEST' - if not arn_to_lambda.get(arn).qualifier_exists(qualifier): + if qualifier and not arn_to_lambda.get(arn).qualifier_exists(qualifier): return error_response('Function does not exist: {0}:{1}'.format(arn, qualifier), 404, error_type='ResourceNotFoundException') data = None diff --git a/localstack/services/awslambda/lambda_executors.py b/localstack/services/awslambda/lambda_executors.py index 9e2015f8d03ef..d319327b1167d 100644 --- a/localstack/services/awslambda/lambda_executors.py +++ b/localstack/services/awslambda/lambda_executors.py @@ -110,6 +110,10 @@ def execute(self, func_arn, func_details, event, context=None, version=None, asy environment['AWS_LAMBDA_EVENT_BODY'] = event_body_escaped environment['HOSTNAME'] = docker_host environment['LOCALSTACK_HOSTNAME'] = docker_host + if context: + environment['AWS_LAMBDA_FUNCTION_NAME'] = context.function_name + environment['AWS_LAMBDA_FUNCTION_VERSION'] = context.function_version + environment['AWS_LAMBDA_FUNCTION_INVOKED_ARN'] = context.invoked_function_arn # custom command to execute in the container command = '' diff --git a/localstack/utils/aws/aws_models.py b/localstack/utils/aws/aws_models.py index dc59fef5daa24..d4b6a1b852e30 100644 --- a/localstack/utils/aws/aws_models.py +++ b/localstack/utils/aws/aws_models.py @@ -181,11 +181,13 @@ def arn(self): return self.id def function(self, qualifier=None): + return self.versions.get(self.get_qualifier_version(qualifier)).get('Function') + + def get_qualifier_version(self, qualifier=None): if not qualifier: qualifier = '$LATEST' - version = qualifier if qualifier in self.versions else \ + return qualifier if qualifier in self.versions else \ self.aliases.get(qualifier).get('FunctionVersion') - return self.versions.get(version).get('Function') def qualifier_exists(self, qualifier): return qualifier in self.aliases or qualifier in self.versions diff --git a/tests/integration/lambdas/lambda_integration.py b/tests/integration/lambdas/lambda_integration.py index 363ffd0d74c6e..3d84a5124e209 100644 --- a/tests/integration/lambdas/lambda_integration.py +++ b/tests/integration/lambdas/lambda_integration.py @@ -35,7 +35,14 @@ def handler(event, context): } if 'Records' not in event: - return event + return { + 'event': event, + 'context': { + 'invoked_function_arn': context.invoked_function_arn, + 'function_version': context.function_version, + 'function_name': context.function_name + } + } raw_event_messages = [] for record in event['Records']: diff --git a/tests/integration/test_lambda.py b/tests/integration/test_lambda.py index 4fbe0848c25ed..01346db42b6c5 100644 --- a/tests/integration/test_lambda.py +++ b/tests/integration/test_lambda.py @@ -61,8 +61,52 @@ def test_upload_lambda_from_s3(): # invoke lambda function data_before = b'{"foo": "bar"}' result = lambda_client.invoke(FunctionName=lambda_name, Payload=data_before) - data_after = result['Payload'].read() - assert json.loads(to_str(data_before)) == json.loads(to_str(data_after)) + data_after = json.loads(result['Payload'].read()) + assert json.loads(to_str(data_before)) == data_after['event'] + + context = data_after['context'] + assert '$LATEST' == context['function_version'] + assert lambda_name == context['function_name'] + + +def test_function_invocation_with_qualifier(): + + s3_client = aws_stack.connect_to_service('s3') + lambda_client = aws_stack.connect_to_service('lambda') + + lambda_name = 'test_lambda_%s' % short_uid() + bucket_name = 'test_bucket_lambda2' + bucket_key = 'test_lambda.zip' + + # upload zip file to S3 + zip_file = testutil.create_lambda_archive(load_file(TEST_LAMBDA_PYTHON), get_content=True, + libs=TEST_LAMBDA_LIBS, runtime=LAMBDA_RUNTIME_PYTHON27) + s3_client.create_bucket(Bucket=bucket_name) + s3_client.upload_fileobj(BytesIO(zip_file), bucket_name, bucket_key) + + # create lambda function + response = lambda_client.create_function( + FunctionName=lambda_name, Handler='handler.handler', + Runtime=lambda_api.LAMBDA_RUNTIME_PYTHON27, Role='r1', + Code={ + 'S3Bucket': bucket_name, + 'S3Key': bucket_key + }, + Publish=True + ) + + assert 'Version' in response + + # invoke lambda function + data_before = b'{"foo": "bar"}' + result = lambda_client.invoke(FunctionName=lambda_name, Payload=data_before, + Qualifier=response['Version']) + data_after = json.loads(result['Payload'].read()) + assert json.loads(to_str(data_before)) == data_after['event'] + + context = data_after['context'] + assert response['Version'] == context['function_version'] + assert lambda_name == context['function_name'] def test_lambda_runtimes(): @@ -76,8 +120,8 @@ def test_lambda_runtimes(): zip_file=zip_file, runtime=LAMBDA_RUNTIME_PYTHON27) result = lambda_client.invoke(FunctionName=TEST_LAMBDA_NAME_PY, Payload=b'{}') assert result['StatusCode'] == 200 - result_data = result['Payload'].read() - assert to_str(result_data).strip() == '{}' + result_data = json.loads(result['Payload'].read()) + assert result_data['event'] == json.loads('{}') if use_docker(): # deploy and invoke lambda - Python 3.6
This adds some common properties to the LambdaContext, which is passed to functions during invocations. In particular, the following properties are added: function_name, function_version, invoked_function_arn. The above properties are passed to lambda functions running inside docker. Support for publishing during function creation has also been added, which was a missing functionality, and was helpful in testing. Note that this has a slight dependency on https://github.com/lambci/docker-lambda/pull/98, but shouldn't break anything if this was merged first. Contributed by @quantcast **Please refer to the contribution guidelines in the README when submitting PRs.**
https://api.github.com/repos/localstack/localstack/pulls/810
2018-06-20T20:27:40Z
2018-07-03T16:11:44Z
2018-07-03T16:11:44Z
2018-07-03T16:11:44Z
2,056
localstack/localstack
28,938
Add new model to the arena
diff --git a/docs/model_support.md b/docs/model_support.md index 654dda47e7..ddbeb92fdd 100644 --- a/docs/model_support.md +++ b/docs/model_support.md @@ -1,21 +1,23 @@ # Model Support ## Supported models + - [meta-llama/Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf) - - example: `python3 -m fastchat.serve.cli --model-path meta-llama/Llama-2-7b-chat-hf` + - example: `python3 -m fastchat.serve.cli --model-path meta-llama/Llama-2-7b-chat-hf` - Vicuna, Alpaca, LLaMA, Koala - - example: `python3 -m fastchat.serve.cli --model-path lmsys/vicuna-7b-v1.3` + - example: `python3 -m fastchat.serve.cli --model-path lmsys/vicuna-7b-v1.3` - [BAAI/AquilaChat-7B](https://huggingface.co/BAAI/AquilaChat-7B) - [BAAI/bge-large-en](https://huggingface.co/BAAI/bge-large-en#using-huggingface-transformers) - [baichuan-inc/baichuan-7B](https://huggingface.co/baichuan-inc/baichuan-7B) - [BlinkDL/RWKV-4-Raven](https://huggingface.co/BlinkDL/rwkv-4-raven) - - example: `python3 -m fastchat.serve.cli --model-path ~/model_weights/RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth` + - example: `python3 -m fastchat.serve.cli --model-path ~/model_weights/RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth` - [bofenghuang/vigogne-2-7b-instruct](https://huggingface.co/bofenghuang/vigogne-2-7b-instruct) - [bofenghuang/vigogne-2-7b-chat](https://huggingface.co/bofenghuang/vigogne-2-7b-chat) - [camel-ai/CAMEL-13B-Combined-Data](https://huggingface.co/camel-ai/CAMEL-13B-Combined-Data) - [databricks/dolly-v2-12b](https://huggingface.co/databricks/dolly-v2-12b) - [FlagAlpha/Llama2-Chinese-13b-Chat](https://huggingface.co/FlagAlpha/Llama2-Chinese-13b-Chat) - [FreedomIntelligence/phoenix-inst-chat-7b](https://huggingface.co/FreedomIntelligence/phoenix-inst-chat-7b) +- [FreedomIntelligence/ReaLM-7b-v1](https://huggingface.co/FreedomIntelligence/Realm-7b) - [h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-7b](https://huggingface.co/h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-7b) - [internlm/internlm-chat-7b](https://huggingface.co/internlm/internlm-chat-7b) - [lcw99/polyglot-ko-12.8b-chang-instruct-chat](https://huggingface.co/lcw99/polyglot-ko-12.8b-chang-instruct-chat) @@ -51,11 +53,13 @@ To support a new model in FastChat, you need to correctly handle its prompt template and model loading. The goal is to make the following command run with the correct prompts. + ``` python3 -m fastchat.serve.cli --model [YOUR_MODEL_PATH] ``` You can run this example command to learn the code logic. + ``` python3 -m fastchat.serve.cli --model lmsys/vicuna-7b-v1.3 ``` @@ -63,6 +67,7 @@ python3 -m fastchat.serve.cli --model lmsys/vicuna-7b-v1.3 You can add `--debug` to see the actual prompt sent to the model. ### Steps + FastChat uses the `Conversation` class to handle prompt templates and `BaseModelAdapter` class to handle model loading. 1. Implement a conversation template for the new model at [fastchat/conversation.py](https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py). You can follow existing examples and use `register_conv_template` to add a new one. diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 853aa8f30d..9354203895 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -555,6 +555,19 @@ def get_conv_template(name: str) -> Conversation: ) ) +# ReaLM default template +register_conv_template( + Conversation( + name="ReaLM-7b-v1", + system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n", + roles=("Human", "Assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.PHOENIX, + sep="</s>", + ) +) + # ChatGPT default template register_conv_template( Conversation( diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 0b35640867..e3ee0ef03f 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -863,6 +863,23 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("phoenix") +class ReaLMAdapter(BaseModelAdapter): + """The model adapter for FreedomIntelligence/ReaLM-7b""" + + def match(self, model_path: str): + return "ReaLM" in model_path + + def load_model(self, model_path: str, from_pretrained_kwargs: dict): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = AutoModelForCausalLM.from_pretrained( + model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs + ) + return model, tokenizer + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("ReaLM-7b-v1") + + class ChatGPTAdapter(BaseModelAdapter): """The model adapter for ChatGPT""" @@ -1600,6 +1617,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(VigogneInstructAdapter) register_model_adapter(VigogneChatAdapter) register_model_adapter(OpenLLaMaOpenInstructAdapter) +register_model_adapter(ReaLMAdapter) # 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 6cb6f1081d..234da8adb4 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -182,6 +182,12 @@ def get_model_info(name: str) -> ModelInfo: "https://huggingface.co/FreedomIntelligence/phoenix-inst-chat-7b", "a multilingual chat assistant fine-tuned from Bloomz to democratize ChatGPT across languages by CUHK(SZ)", ) +register_model_info( + ["realm-7b-v1"], + "ReaLM", + "https://github.com/FreedomIntelligence/ReaLM", + "A chatbot fine-tuned from LLaMA2 with data generated via iterative calls to UserGPT and ChatGPT by CUHK(SZ) and SRIBD.", +) register_model_info( ["billa-7b-sft"], "BiLLa-7B-SFT",
hi, thanks for your brilliant job!! we want to support our model `ReaLM` in mt-bench. we have added the related information to `conversation.py`, `model_adapter.py`, `model_registry.py`, `model_support.md`. all the information is coded under our previous model `phoenix`. the following links are the repos for the code and model. https://github.com/FreedomIntelligence/ReaLM https://huggingface.co/FreedomIntelligence/ReaLM-7b thanks in advance!
https://api.github.com/repos/lm-sys/FastChat/pulls/2296
2023-08-23T12:27:51Z
2023-08-24T07:05:34Z
2023-08-24T07:05:34Z
2023-10-08T02:57:47Z
1,889
lm-sys/FastChat
41,534
update xx_net.sh
diff --git a/code/default/xx_net.sh b/code/default/xx_net.sh index 321284ea6d..874e6c5441 100755 --- a/code/default/xx_net.sh +++ b/code/default/xx_net.sh @@ -26,18 +26,20 @@ else PYTHON="python" fi +PACKAGE_PATH=$("${PYTHON}" -c "import os; print os.path.dirname(os.path.realpath('$0'))") + start() { echo -n "Starting ${PACKAGE_DESC}: " if hash python2 2>/dev/null; then #nohup "${PYTHON}" launcher/start.py 2>&1 | /usr/bin/logger -t ${PACKAGE_NAME} & - nohup "${PYTHON}" launcher/start.py >/dev/null 2>&1 & + nohup "${PYTHON}" ${PACKAGE_PATH}/launcher/start.py >/dev/null 2>&1 & fi echo "${PACKAGE_NAME}." } stop() { echo -n "Stopping ${PACKAGE_DESC}: " - kill -9 `ps aux | grep "${PYTHON} launcher/start.py" | grep -v grep | awk '{print $2}'` || true + kill -9 `ps aux | grep "${PYTHON} ${PACKAGE_PATH}/launcher/start.py" | grep -v grep | awk '{print $2}'` || true echo "${PACKAGE_NAME}." } @@ -58,8 +60,6 @@ if [ "$(id -u)" != "0" ]; then exit 0 fi -# `readlink -f` won't work on Mac, this hack should work on all systems. -cd $("${PYTHON}" -c "import os; print os.path.dirname(os.path.realpath('$0'))") case "$1" in # If no arg is given, start the goagent.
如果直接在linux 的/etc/init.d 中创建xx_net.sh 的软链接,然后注册为服务,xx_net 不会启动。 因此修改cd 到xx_net 实际所在目录的方式为直接调用xx_net 的绝对路径。
https://api.github.com/repos/XX-net/XX-Net/pulls/3844
2016-07-12T13:31:16Z
2016-07-12T14:10:34Z
2016-07-12T14:10:34Z
2016-07-12T15:01:43Z
394
XX-net/XX-Net
17,190
Create pythagoreanTriplets.py
diff --git a/pythagoreanTriplets.py b/pythagoreanTriplets.py new file mode 100644 index 0000000000..55b146ea78 --- /dev/null +++ b/pythagoreanTriplets.py @@ -0,0 +1,14 @@ +limit=int(input("Enter upper limit:")) +c=0 +m=2 +while(c<limit): + for n in range(1,m+1): + a=m*m-n*n + b=2*m*n + c=m*m+n*n + if(c>limit): + break + if(a==0 or b==0 or c==0): + break + print(a,b,c) + m=m+1
https://api.github.com/repos/geekcomputers/Python/pulls/1454
2022-01-04T03:29:45Z
2022-01-04T07:50:55Z
2022-01-04T07:50:55Z
2022-01-04T07:50:55Z
167
geekcomputers/Python
31,703
Bipedal fix bounds and type hints
diff --git a/gym/envs/box2d/bipedal_walker.py b/gym/envs/box2d/bipedal_walker.py index 8fc2dc8f643..ee072cf5311 100644 --- a/gym/envs/box2d/bipedal_walker.py +++ b/gym/envs/box2d/bipedal_walker.py @@ -181,12 +181,71 @@ def __init__(self, hardcore: bool = False): categoryBits=0x0001, ) - high = np.array([np.inf] * 24).astype(np.float32) + # we use 5.0 to represent the joints moving at maximum + # 5 x the rated speed due to impulses from ground contact etc. + low = np.array( + [ + -math.pi, + -5.0, + -5.0, + -5.0, + -math.pi, + -5.0, + -math.pi, + -5.0, + -0.0, + -math.pi, + -5.0, + -math.pi, + -5.0, + -0.0, + ] + + [-1.0] * 10 + ).astype(np.float32) + high = np.array( + [ + math.pi, + 5.0, + 5.0, + 5.0, + math.pi, + 5.0, + math.pi, + 5.0, + 5.0, + math.pi, + 5.0, + math.pi, + 5.0, + 5.0, + ] + + [1.0] * 10 + ).astype(np.float32) self.action_space = spaces.Box( np.array([-1, -1, -1, -1]).astype(np.float32), np.array([1, 1, 1, 1]).astype(np.float32), ) - self.observation_space = spaces.Box(-high, high) + self.observation_space = spaces.Box(low, high) + + # state = [ + # self.hull.angle, # Normal angles up to 0.5 here, but sure more is possible. + # 2.0 * self.hull.angularVelocity / FPS, + # 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range + # 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS, + # self.joints[ + # 0 + # ].angle, # This will give 1.1 on high up, but it's still OK (and there should be spikes on hiting the ground, that's normal too) + # self.joints[0].speed / SPEED_HIP, + # self.joints[1].angle + 1.0, + # self.joints[1].speed / SPEED_KNEE, + # 1.0 if self.legs[1].ground_contact else 0.0, + # self.joints[2].angle, + # self.joints[2].speed / SPEED_HIP, + # self.joints[3].angle + 1.0, + # self.joints[3].speed / SPEED_KNEE, + # 1.0 if self.legs[3].ground_contact else 0.0, + # ] + # state += [l.fraction for l in self.lidar] def _destroy(self): if not self.terrain: @@ -444,7 +503,7 @@ def ReportFixture(self, fixture, point, normal, fraction): else: return self.step(np.array([0, 0, 0, 0]))[0], {} - def step(self, action): + def step(self, action: np.ndarray): # self.hull.ApplyForceToCenter((0, 20), True) -- Uncomment this to receive a bit of stability help control_speed = False # Should be easier as well if control_speed: @@ -489,9 +548,8 @@ def step(self, action): 2.0 * self.hull.angularVelocity / FPS, 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS, - self.joints[ - 0 - ].angle, # This will give 1.1 on high up, but it's still OK (and there should be spikes on hiting the ground, that's normal too) + self.joints[0].angle, + # This will give 1.1 on high up, but it's still OK (and there should be spikes on hiting the ground, that's normal too) self.joints[0].speed / SPEED_HIP, self.joints[1].angle + 1.0, self.joints[1].speed / SPEED_KNEE, @@ -531,7 +589,7 @@ def step(self, action): done = True return np.array(state, dtype=np.float32), reward, done, {} - def render(self, mode="human"): + def render(self, mode: str = "human"): import pygame from pygame import gfxdraw diff --git a/gym/envs/box2d/lunar_lander.py b/gym/envs/box2d/lunar_lander.py index 543dad66c48..0d9c6c0484b 100644 --- a/gym/envs/box2d/lunar_lander.py +++ b/gym/envs/box2d/lunar_lander.py @@ -165,10 +165,41 @@ def __init__(self, continuous: bool = False): self.continuous = continuous + low = np.array( + [ + # these are bounds for position + # realistically the environment should have ended + # long before we reach more than 50% outside + -1.5, + -1.5, + # velocity bounds is 5x rated speed + -5.0, + -5.0, + -math.pi, + -5.0, + -0.0, + -0.0, + ] + ).astype(np.float32) + high = np.array( + [ + # these are bounds for position + # realistically the environment should have ended + # long before we reach more than 50% outside + 1.5, + 1.5, + # velocity bounds is 5x rated speed + 5.0, + 5.0, + math.pi, + 5.0, + 1.0, + 1.0, + ] + ).astype(np.float32) + # useful range is -1 .. +1, but spikes can be higher - self.observation_space = spaces.Box( - -np.inf, np.inf, shape=(8,), dtype=np.float32 - ) + self.observation_space = spaces.Box(low, high) if self.continuous: # Action is two floats [main engine, left-right engines].
# Description This fixes the box infinite bounds on bipedal walker, as well as puts in place some missing type hints. ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) # 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 - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes
https://api.github.com/repos/openai/gym/pulls/2750
2022-04-13T23:26:37Z
2022-04-14T00:23:08Z
2022-04-14T00:23:08Z
2022-04-15T21:21:40Z
1,700
openai/gym
5,060
Capture and re-raise urllib3 ProtocolError
diff --git a/requests/adapters.py b/requests/adapters.py index 3c1e979f14..bf94bbe7bd 100644 --- a/requests/adapters.py +++ b/requests/adapters.py @@ -23,6 +23,7 @@ from .packages.urllib3.exceptions import HTTPError as _HTTPError from .packages.urllib3.exceptions import MaxRetryError from .packages.urllib3.exceptions import ProxyError as _ProxyError +from .packages.urllib3.exceptions import ProtocolError from .packages.urllib3.exceptions import ReadTimeoutError from .packages.urllib3.exceptions import SSLError as _SSLError from .cookies import extract_cookies_to_jar @@ -400,8 +401,8 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox # All is well, return the connection to the pool. conn._put_conn(low_conn) - except socket.error as sockerr: - raise ConnectionError(sockerr, request=request) + except (ProtocolError, socket.error) as err: + raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): diff --git a/test_requests.py b/test_requests.py index 716c0dcff6..2ff61248b5 100755 --- a/test_requests.py +++ b/test_requests.py @@ -286,6 +286,14 @@ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self): r = s.get(url) assert r.status_code == 200 + def test_connection_error(self): + """Connecting to an unknown domain should raise a ConnectionError""" + with pytest.raises(ConnectionError): + requests.get("http://fooobarbangbazbing.httpbin.org") + + with pytest.raises(ConnectionError): + requests.get("http://httpbin.org:1") + def test_basicauth_with_netrc(self): auth = ('user', 'pass') wrong_auth = ('wronguser', 'wrongpass')
Fixes #2192
https://api.github.com/repos/psf/requests/pulls/2193
2014-08-29T20:16:54Z
2014-09-04T18:39:41Z
2014-09-04T18:39:41Z
2021-09-08T10:01:21Z
451
psf/requests
32,388
Migrate Tradfri to has entity name
diff --git a/homeassistant/components/tradfri/base_class.py b/homeassistant/components/tradfri/base_class.py index 5a84ad5719c7e5..c7154c19f158c4 100644 --- a/homeassistant/components/tradfri/base_class.py +++ b/homeassistant/components/tradfri/base_class.py @@ -37,6 +37,8 @@ async def wrapper(command: Command | list[Command]) -> None: class TradfriBaseEntity(CoordinatorEntity[TradfriDeviceDataUpdateCoordinator]): """Base Tradfri device.""" + _attr_has_entity_name = True + def __init__( self, device_coordinator: TradfriDeviceDataUpdateCoordinator, @@ -52,7 +54,6 @@ def __init__( self._device_id = self._device.id self._api = handle_error(api) - self._attr_name = self._device.name self._attr_unique_id = f"{self._gateway_id}-{self._device.id}" diff --git a/homeassistant/components/tradfri/cover.py b/homeassistant/components/tradfri/cover.py index 976a48906fc3b5..c51918b4a4f320 100644 --- a/homeassistant/components/tradfri/cover.py +++ b/homeassistant/components/tradfri/cover.py @@ -40,6 +40,8 @@ async def async_setup_entry( class TradfriCover(TradfriBaseEntity, CoverEntity): """The platform class required by Home Assistant.""" + _attr_name = None + def __init__( self, device_coordinator: TradfriDeviceDataUpdateCoordinator, diff --git a/homeassistant/components/tradfri/fan.py b/homeassistant/components/tradfri/fan.py index d6bb91a49791cc..a26dfa1d9a099c 100644 --- a/homeassistant/components/tradfri/fan.py +++ b/homeassistant/components/tradfri/fan.py @@ -54,6 +54,7 @@ async def async_setup_entry( class TradfriAirPurifierFan(TradfriBaseEntity, FanEntity): """The platform class required by Home Assistant.""" + _attr_name = None _attr_supported_features = FanEntityFeature.PRESET_MODE | FanEntityFeature.SET_SPEED def __init__( diff --git a/homeassistant/components/tradfri/light.py b/homeassistant/components/tradfri/light.py index 32160c6a130a96..df35301b3736c0 100644 --- a/homeassistant/components/tradfri/light.py +++ b/homeassistant/components/tradfri/light.py @@ -49,6 +49,7 @@ async def async_setup_entry( class TradfriLight(TradfriBaseEntity, LightEntity): """The platform class required by Home Assistant.""" + _attr_name = None _attr_supported_features = LightEntityFeature.TRANSITION def __init__( diff --git a/homeassistant/components/tradfri/sensor.py b/homeassistant/components/tradfri/sensor.py index 1b3839ce2d7d56..b2751083315c0a 100644 --- a/homeassistant/components/tradfri/sensor.py +++ b/homeassistant/components/tradfri/sensor.py @@ -24,7 +24,6 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.helpers.typing import UNDEFINED from .base_class import TradfriBaseEntity from .const import ( @@ -89,7 +88,7 @@ def _get_filter_time_left(device: Device) -> int: SENSOR_DESCRIPTIONS_FAN: tuple[TradfriSensorEntityDescription, ...] = ( TradfriSensorEntityDescription( key="aqi", - name="air quality", + translation_key="aqi", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, icon="mdi:air-filter", @@ -97,7 +96,7 @@ def _get_filter_time_left(device: Device) -> int: ), TradfriSensorEntityDescription( key="filter_life_remaining", - name="filter time left", + translation_key="filter_life_remaining", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTime.HOURS, icon="mdi:clock-outline", @@ -203,9 +202,6 @@ def __init__( self._attr_unique_id = f"{self._attr_unique_id}-{description.key}" - if description.name is not UNDEFINED: - self._attr_name = f"{self._attr_name}: {description.name}" - self._refresh() # Set initial state def _refresh(self) -> None: diff --git a/homeassistant/components/tradfri/strings.json b/homeassistant/components/tradfri/strings.json index 34d7e89929af8b..0a9a86bd23a209 100644 --- a/homeassistant/components/tradfri/strings.json +++ b/homeassistant/components/tradfri/strings.json @@ -20,5 +20,15 @@ "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", "already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]" } + }, + "entity": { + "sensor": { + "aqi": { + "name": "Air quality" + }, + "filter_life_remaining": { + "name": "Filter time left" + } + } } } diff --git a/homeassistant/components/tradfri/switch.py b/homeassistant/components/tradfri/switch.py index e0e2467ca4bf37..2f6f19961579a4 100644 --- a/homeassistant/components/tradfri/switch.py +++ b/homeassistant/components/tradfri/switch.py @@ -40,6 +40,8 @@ async def async_setup_entry( class TradfriSwitch(TradfriBaseEntity, SwitchEntity): """The platform class required by Home Assistant.""" + _attr_name = None + def __init__( self, device_coordinator: TradfriDeviceDataUpdateCoordinator, diff --git a/tests/components/tradfri/test_sensor.py b/tests/components/tradfri/test_sensor.py index 23391c8e875868..d301638ec5dc37 100644 --- a/tests/components/tradfri/test_sensor.py +++ b/tests/components/tradfri/test_sensor.py @@ -61,7 +61,7 @@ async def test_battery_sensor( remote_control: Device, ) -> None: """Test that a battery sensor is correctly added.""" - entity_id = "sensor.test" + entity_id = "sensor.test_battery" device = remote_control mock_gateway.mock_devices.append(device) await setup_integration(hass) @@ -92,7 +92,7 @@ async def test_cover_battery_sensor( blind: Blind, ) -> None: """Test that a battery sensor is correctly added for a cover (blind).""" - entity_id = "sensor.test" + entity_id = "sensor.test_battery" device = blind.device mock_gateway.mock_devices.append(device) await setup_integration(hass)
<!-- You are amazing! Thanks for contributing to our project! Please, DO NOT DELETE ANY TEXT from this template! (unless instructed). --> ## Proposed change <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue in the additional information section. --> Migrate Tradfri to has entity name ## Type of change <!-- What type of change does your PR introduce to Home Assistant? NOTE: Please, check only 1! box! If your PR requires multiple boxes to be checked, you'll most likely need to split it into multiple PRs. This makes things easier and faster to code review. --> - [ ] Dependency upgrade - [ ] Bugfix (non-breaking change which fixes an issue) - [ ] New integration (thank you!) - [x] New feature (which adds functionality to an existing integration) - [ ] Deprecation (breaking change to happen in the future) - [ ] Breaking change (fix/feature causing existing functionality to break) - [ ] Code quality improvements to existing code or addition of tests ## Additional information <!-- Details are important, and help maintainers processing your PR. Please be sure to fill out additional details, if applicable. --> - This PR fixes or closes issue: fixes # - This PR is related to issue: - Link to documentation pull request: ## Checklist <!-- Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. --> - [ ] The code change is tested and works locally. - [x] Local tests pass. **Your PR cannot be merged unless tests pass** - [x] There is no commented out code in this PR. - [x] I have followed the [development checklist][dev-checklist] - [x] I have followed the [perfect PR recommendations][perfect-pr] - [x] The code has been formatted using Black (`black --fast homeassistant tests`) - [x] Tests have been added to verify that the new code works. If user exposed functionality or configuration variables are added/changed: - [ ] Documentation added/updated for [www.home-assistant.io][docs-repository] If the code communicates with devices, web services, or third-party tools: - [ ] The [manifest file][manifest-docs] has all fields filled out correctly. Updated and included derived files by running: `python3 -m script.hassfest`. - [ ] New or updated dependencies have been added to `requirements_all.txt`. Updated by running `python3 -m script.gen_requirements_all`. - [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description. - [ ] Untested files have been added to `.coveragerc`. <!-- This project is very active and we have a high turnover of pull requests. Unfortunately, the number of incoming pull requests is higher than what our reviewers can review and merge so there is a long backlog of pull requests waiting for review. You can help here! By reviewing another pull request, you will help raise the code quality of that pull request and the final review will be faster. This way the general pace of pull request reviews will go up and your wait time will go down. When picking a pull request to review, try to choose one that hasn't yet been reviewed. Thanks for helping out! --> To help with the load of incoming pull requests: - [ ] I have reviewed two other [open pull requests][prs] in this repository. [prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure <!-- Thank you for contributing <3 Below, some useful links you could explore: --> [dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/ [manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/ [quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/ [docs-repository]: https://github.com/home-assistant/home-assistant.io [perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr
https://api.github.com/repos/home-assistant/core/pulls/96248
2023-07-10T10:27:03Z
2023-07-18T18:56:50Z
2023-07-18T18:56:50Z
2023-07-19T19:01:36Z
1,635
home-assistant/core
39,282
Fix the OFT/BOFT bugs when using new LyCORIS implementation
diff --git a/extensions-builtin/Lora/network_oft.py b/extensions-builtin/Lora/network_oft.py index d658ad10930..7821a8a7dbf 100644 --- a/extensions-builtin/Lora/network_oft.py +++ b/extensions-builtin/Lora/network_oft.py @@ -1,6 +1,5 @@ import torch import network -from lyco_helpers import factorization from einops import rearrange @@ -22,24 +21,24 @@ def __init__(self, net: network.Network, weights: network.NetworkWeights): self.org_module: list[torch.Module] = [self.sd_module] self.scale = 1.0 - self.is_kohya = False + self.is_R = False self.is_boft = False - # kohya-ss + # kohya-ss/New LyCORIS OFT/BOFT if "oft_blocks" in weights.w.keys(): - self.is_kohya = True self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size) - self.alpha = weights.w["alpha"] # alpha is constraint + self.alpha = weights.w.get("alpha", None) # alpha is constraint self.dim = self.oft_blocks.shape[0] # lora dim - # LyCORIS OFT + # Old LyCORIS OFT elif "oft_diag" in weights.w.keys(): + self.is_R = True self.oft_blocks = weights.w["oft_diag"] # self.alpha is unused self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size) - # LyCORIS BOFT - if weights.w["oft_diag"].dim() == 4: - self.is_boft = True + # LyCORIS BOFT + if self.oft_blocks.dim() == 4: + self.is_boft = True self.rescale = weights.w.get('rescale', None) if self.rescale is not None: self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1)) @@ -55,30 +54,29 @@ def __init__(self, net: network.Network, weights: network.NetworkWeights): elif is_other_linear: self.out_dim = self.sd_module.embed_dim - if self.is_kohya: - self.constraint = self.alpha * self.out_dim - self.num_blocks = self.dim - self.block_size = self.out_dim // self.dim - elif self.is_boft: + self.num_blocks = self.dim + self.block_size = self.out_dim // self.dim + self.constraint = (0 if self.alpha is None else self.alpha) * self.out_dim + if self.is_R: self.constraint = None - self.boft_m = weights.w["oft_diag"].shape[0] - self.block_num = weights.w["oft_diag"].shape[1] - self.block_size = weights.w["oft_diag"].shape[2] + self.block_size = self.dim + self.num_blocks = self.out_dim // self.dim + elif self.is_boft: + self.boft_m = self.oft_blocks.shape[0] + self.num_blocks = self.oft_blocks.shape[1] + self.block_size = self.oft_blocks.shape[2] self.boft_b = self.block_size - #self.block_size, self.block_num = butterfly_factor(self.out_dim, self.dim) - else: - self.constraint = None - self.block_size, self.num_blocks = factorization(self.out_dim, self.dim) def calc_updown(self, orig_weight): oft_blocks = self.oft_blocks.to(orig_weight.device) eye = torch.eye(self.block_size, device=oft_blocks.device) - if self.is_kohya: - block_Q = oft_blocks - oft_blocks.transpose(1, 2) # ensure skew-symmetric orthogonal matrix - norm_Q = torch.norm(block_Q.flatten()) - new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device)) - block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8)) + if not self.is_R: + block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix + if self.constraint != 0: + norm_Q = torch.norm(block_Q.flatten()) + new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device)) + block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8)) oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse()) R = oft_blocks.to(orig_weight.device)
## Checklist: - [x] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) - [x] I have performed a self-review of my own code - [x] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style) - [x] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/14973
2024-02-20T09:21:16Z
2024-02-26T04:12:12Z
2024-02-26T04:12:12Z
2024-02-29T01:11:21Z
1,104
AUTOMATIC1111/stable-diffusion-webui
40,032
ES.46 Issue 1797 - narrowing to bool
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 14618a0fd..844648e6e 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -11704,17 +11704,24 @@ A key example is basic narrowing: The guidelines support library offers a `narrow_cast` operation for specifying that narrowing is acceptable and a `narrow` ("narrow if") that throws an exception if a narrowing would throw away legal values: - i = narrow_cast<int>(d); // OK (you asked for it): narrowing: i becomes 7 - i = narrow<int>(d); // OK: throws narrowing_error + i = gsl::narrow_cast<int>(d); // OK (you asked for it): narrowing: i becomes 7 + i = gsl::narrow<int>(d); // OK: throws narrowing_error We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type: double d = -7.9; unsigned u = 0; - u = d; // BAD - u = narrow_cast<unsigned>(d); // OK (you asked for it): u becomes 4294967289 - u = narrow<unsigned>(d); // OK: throws narrowing_error + u = d; // bad: narrowing + u = gsl::narrow_cast<unsigned>(d); // OK (you asked for it): u becomes 4294967289 + u = gsl::narrow<unsigned>(d); // OK: throws narrowing_error + +##### Note + +This rule does not apply to [contextual conversions to bool](https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions): + + if (ptr) do_something(*ptr); // OK: ptr is used as a condition + bool b = ptr; // bad: narrowing ##### Enforcement
Added note for narrowing to bool. See #1797. Also qualified gsl::narrow
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1824
2021-08-30T04:50:32Z
2021-09-30T18:05:15Z
2021-09-30T18:05:15Z
2021-09-30T18:05:25Z
443
isocpp/CppCoreGuidelines
15,434
Bump sphinx from 3.0.4 to 3.1.0
diff --git a/requirements/dev.txt b/requirements/dev.txt index f9ca816b7b..6df3ed0d42 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -40,7 +40,7 @@ requests==2.23.0 # via sphinx six==1.15.0 # via packaging, pip-tools, tox, virtualenv snowballstemmer==2.0.0 # via sphinx sphinx-issues==1.2.0 # via -r requirements/docs.in -sphinx==3.0.4 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet +sphinx==3.1.0 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet sphinxcontrib-applehelp==1.0.2 # via sphinx sphinxcontrib-devhelp==1.0.2 # via sphinx sphinxcontrib-htmlhelp==1.0.3 # via sphinx diff --git a/requirements/docs.txt b/requirements/docs.txt index 2c405a0e17..8d2e718ab2 100644 --- a/requirements/docs.txt +++ b/requirements/docs.txt @@ -22,7 +22,7 @@ requests==2.23.0 # via sphinx six==1.15.0 # via packaging snowballstemmer==2.0.0 # via sphinx sphinx-issues==1.2.0 # via -r requirements/docs.in -sphinx==3.0.4 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet +sphinx==3.1.0 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet sphinxcontrib-applehelp==1.0.2 # via sphinx sphinxcontrib-devhelp==1.0.2 # via sphinx sphinxcontrib-htmlhelp==1.0.3 # via sphinx
Bumps [sphinx](https://github.com/sphinx-doc/sphinx) from 3.0.4 to 3.1.0. <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/sphinx-doc/sphinx/blob/3.x/CHANGES">sphinx's changelog</a>.</em></p> <blockquote> <h1>Release 3.1.0 (released Jun 08, 2020)</h1> <h2>Dependencies</h2> <ul> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7746">#7746</a>: mathjax: Update to 2.7.5</li> </ul> <h2>Incompatible changes</h2> <ul> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7477">#7477</a>: imgconverter: Invoke &quot;magick convert&quot; command by default on Windows</li> </ul> <h2>Deprecated</h2> <ul> <li>The first argument for sphinx.ext.autosummary.generate.AutosummaryRenderer has been changed to Sphinx object</li> <li><code>sphinx.ext.autosummary.generate.AutosummaryRenderer</code> takes an object type as an argument</li> <li>The <code>ignore</code> argument of <code>sphinx.ext.autodoc.Documenter.get_doc()</code></li> <li>The <code>template_dir</code> argument of <code>sphinx.ext.autosummary.generate. AutosummaryRenderer</code></li> <li>The <code>module</code> argument of <code>sphinx.ext.autosummary.generate. find_autosummary_in_docstring()</code></li> <li>The <code>builder</code> argument of <code>sphinx.ext.autosummary.generate. generate_autosummary_docs()</code></li> <li>The <code>template_dir</code> argument of <code>sphinx.ext.autosummary.generate. generate_autosummary_docs()</code></li> <li>The <code>ignore</code> argument of <code>sphinx.util.docstring.prepare_docstring()</code></li> <li><code>sphinx.ext.autosummary.generate.AutosummaryRenderer.exists()</code></li> <li><code>sphinx.util.rpartition()</code></li> </ul> <h2>Features added</h2> <ul> <li>LaTeX: Make the <code>toplevel_sectioning</code> setting optional in LaTeX theme</li> <li>LaTeX: Allow to override papersize and pointsize from LaTeX themes</li> <li>LaTeX: Add :confval:<code>latex_theme_options</code> to override theme options</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7410">#7410</a>: Allow to suppress &quot;circular toctree references detected&quot; warnings using :confval:<code>suppress_warnings</code></li> <li>C, added scope control directives, :rst:dir:<code>c:namespace</code>, :rst:dir:<code>c:namespace-push</code>, and :rst:dir:<code>c:namespace-pop</code>.</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/2044">#2044</a>: autodoc: Suppress default value for instance attributes</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7473">#7473</a>: autodoc: consider a member public if docstring contains <code>:meta public:</code> in info-field-list</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7487">#7487</a>: autodoc: Allow to generate docs for singledispatch functions by py:autofunction</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7143">#7143</a>: autodoc: Support final classes and methods</li> <li><a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7384">#7384</a>: autodoc: Support signatures defined by <code>__new__()</code>, metaclasses and</li> </ul> </tr></table> ... (truncated) </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/sphinx-doc/sphinx/commit/62a9b324a2230d0c8dbfde579abd7ce4ec42d4fb"><code>62a9b32</code></a> Bump to 3.1.0 final</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/23a51a3a33f0003854e08424f8bf6dce2bcaf6b7"><code>23a51a3</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7797">#7797</a> from tk0miya/7791_TypeError_for_singledispatchfunction</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/d0cdf073bd36aaa050858df510455b145bc2c4bd"><code>d0cdf07</code></a> Update CHANGES for PR <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7657">#7657</a></li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/2ed20853ed6ab3783aeb1ac4d874e0e9a1357108"><code>2ed2085</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7657">#7657</a> from mgeier/css-margins</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/7fa47e4b1b184ddab8827651548cedd62415fbcb"><code>7fa47e4</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7788">#7788</a> from tk0miya/7722_support_typevar</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/bf89b1d101fd51fb5c7b76a9af016ddbd68ce2d6"><code>bf89b1d</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7794">#7794</a> from tk0miya/7792_setuptools_verbosity</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/588e5bd08c8ccf6c7cf496e93a18c01a704db5a8"><code>588e5bd</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7778">#7778</a> from tk0miya/7723_pdflatex_URL_having_singlequote</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/f98987b24ecff3c5d30ecb34ce0c8515132cde87"><code>f98987b</code></a> Fix <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7791">#7791</a>: autodoc: TypeError is raised on documenting singledispatch function</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/8bd5f8b214b25242487948931f8e9b9d1bcf9f98"><code>8bd5f8b</code></a> autodoc: Support TypeVar (refs: <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7722">#7722</a>)</li> <li><a href="https://github.com/sphinx-doc/sphinx/commit/6ccab6c1504cbc8fb29d31bf1900b8bbe9413589"><code>6ccab6c</code></a> Close <a href="https://github-redirect.dependabot.com/sphinx-doc/sphinx/issues/7792">#7792</a>: setuptools: Support <code>--verbosity</code> option</li> <li>Additional commits viewable in <a href="https://github.com/sphinx-doc/sphinx/compare/v3.0.4...v3.1.0">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://api.dependabot.com/badges/compatibility_score?dependency-name=sphinx&package-manager=pip&previous-version=3.0.4&new-version=3.1.0)](https://dependabot.com/compatibility-score/?dependency-name=sphinx&package-manager=pip&previous-version=3.0.4&new-version=3.1.0) 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) If all status checks pass Dependabot will automatically merge this pull request. [//]: # (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 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) - `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language - `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language - `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language - `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language - `@dependabot badge me` will comment on this PR with code to add a "Dependabot enabled" badge to your readme Additionally, you can set the following in your Dependabot [dashboard](https://app.dependabot.com): - Update frequency (including time of day and day of week) - Pull request limits (per update run and/or open at any time) - Automerge options (never/patch/minor, and dev/runtime dependencies) - Out-of-range updates (receive only lockfile updates, if desired) - Security updates (receive only security updates, if desired) </details>
https://api.github.com/repos/pallets/flask/pulls/3645
2020-06-08T14:16:14Z
2020-06-08T14:18:55Z
2020-06-08T14:18:55Z
2020-11-14T01:33:38Z
494
pallets/flask
20,698
Fixed mispelling
diff --git a/README.md b/README.md index d1db60c..5874fa4 100644 --- a/README.md +++ b/README.md @@ -3161,7 +3161,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ <!-- Example ID: edafe923-0c20-4315-b6e1-0c31abfc38f5 ---> ```py -# `pip install nump` first. +# `pip install numpy` first. import numpy as np def energy_send(x):
https://api.github.com/repos/satwikkansal/wtfpython/pulls/167
2020-01-05T00:50:06Z
2020-01-06T14:08:50Z
2020-01-06T14:08:50Z
2020-01-07T19:11:40Z
132
satwikkansal/wtfpython
25,883
add check for submodules in release builds
diff --git a/release/build_release2.sh b/release/build_release2.sh index ee3c3f4656c94c..c607aa820636bc 100755 --- a/release/build_release2.sh +++ b/release/build_release2.sh @@ -55,6 +55,14 @@ scons -j3 python selfdrive/manager/test/test_manager.py selfdrive/car/tests/test_car_interfaces.py +# Ensure no submodules in release +if test "$(git submodule--helper list | wc -l)" -gt "0"; then + echo "submodules found:" + git submodule--helper list + exit 1 +fi +git submodule status + # Cleanup find . -name '*.a' -delete find . -name '*.o' -delete
https://api.github.com/repos/commaai/openpilot/pulls/21643
2021-07-18T21:39:08Z
2021-07-19T17:09:16Z
2021-07-19T17:09:16Z
2021-07-19T17:09:17Z
173
commaai/openpilot
9,199
Revert "Fix "global" max_attempt bug (#1719)"
diff --git a/acme/acme/client.py b/acme/acme/client.py index 478536ecc36..49c6bcb21c0 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -1,5 +1,4 @@ """ACME client API.""" -import collections import datetime import heapq import logging @@ -335,9 +334,8 @@ def poll_and_request_issuance( :param authzrs: `list` of `.AuthorizationResource` :param int mintime: Minimum time before next attempt, used if ``Retry-After`` is not present in the response. - :param int max_attempts: Maximum number of attempts (per - authorization) before `PollError` with non-empty ``waiting`` - is raised. + :param int max_attempts: Maximum number of attempts before + `PollError` with non-empty ``waiting`` is raised. :returns: ``(cert, updated_authzrs)`` `tuple` where ``cert`` is the issued certificate (`.messages.CertificateResource`), @@ -351,11 +349,6 @@ def poll_and_request_issuance( was marked by the CA as invalid """ - # pylint: disable=too-many-locals - assert max_attempts > 0 - attempts = collections.defaultdict(int) - exhausted = set() - # priority queue with datetime (based on Retry-After) as key, # and original Authorization Resource as value waiting = [(datetime.datetime.now(), authzr) for authzr in authzrs] @@ -363,7 +356,8 @@ def poll_and_request_issuance( # recently updated one updated = dict((authzr, authzr) for authzr in authzrs) - while waiting: + while waiting and max_attempts: + max_attempts -= 1 # find the smallest Retry-After, and sleep if necessary when, authzr = heapq.heappop(waiting) now = datetime.datetime.now() @@ -377,20 +371,16 @@ def poll_and_request_issuance( updated_authzr, response = self.poll(updated[authzr]) updated[authzr] = updated_authzr - attempts[authzr] += 1 # pylint: disable=no-member if updated_authzr.body.status not in ( messages.STATUS_VALID, messages.STATUS_INVALID): - if attempts[authzr] < max_attempts: - # push back to the priority queue, with updated retry_after - heapq.heappush(waiting, (self.retry_after( - response, default=mintime), authzr)) - else: - exhausted.add(authzr) - - if exhausted or any(authzr.body.status == messages.STATUS_INVALID - for authzr in six.itervalues(updated)): - raise errors.PollError(exhausted, updated) + # push back to the priority queue, with updated retry_after + heapq.heappush(waiting, (self.retry_after( + response, default=mintime), authzr)) + + if not max_attempts or any(authzr.body.status == messages.STATUS_INVALID + for authzr in six.itervalues(updated)): + raise errors.PollError(waiting, updated) updated_authzrs = tuple(updated[authzr] for authzr in authzrs) return self.request_issuance(csr, updated_authzrs), updated_authzrs diff --git a/acme/acme/client_test.py b/acme/acme/client_test.py index 9abc69c7c4c..449bd695ec3 100644 --- a/acme/acme/client_test.py +++ b/acme/acme/client_test.py @@ -319,10 +319,7 @@ def request_issuance(csr, authzrs): # pylint: disable=missing-docstring ) cert, updated_authzrs = self.client.poll_and_request_issuance( - csr, authzrs, mintime=mintime, - # make sure that max_attempts is per-authorization, rather - # than global - max_attempts=max(len(authzrs[0].retries), len(authzrs[1].retries))) + csr, authzrs, mintime=mintime) self.assertTrue(cert[0] is csr) self.assertTrue(cert[1] is updated_authzrs) self.assertEqual(updated_authzrs[0].uri, 'a...') diff --git a/acme/acme/errors.py b/acme/acme/errors.py index 77d47c52260..0385667c74e 100644 --- a/acme/acme/errors.py +++ b/acme/acme/errors.py @@ -56,25 +56,26 @@ def __str__(self): class PollError(ClientError): """Generic error when polling for authorization fails. - This might be caused by either timeout (`exhausted` will be non-empty) + This might be caused by either timeout (`waiting` will be non-empty) or by some authorization being invalid. - :ivar exhausted: Set of `.AuthorizationResource` that didn't finish - within max allowed attempts. + :ivar waiting: Priority queue with `datetime.datatime` (based on + ``Retry-After``) as key, and original `.AuthorizationResource` + as value. :ivar updated: Mapping from original `.AuthorizationResource` to the most recently updated one """ - def __init__(self, exhausted, updated): - self.exhausted = exhausted + def __init__(self, waiting, updated): + self.waiting = waiting self.updated = updated super(PollError, self).__init__() @property def timeout(self): """Was the error caused by timeout?""" - return bool(self.exhausted) + return bool(self.waiting) def __repr__(self): - return '{0}(exhausted={1!r}, updated={2!r})'.format( - self.__class__.__name__, self.exhausted, self.updated) + return '{0}(waiting={1!r}, updated={2!r})'.format( + self.__class__.__name__, self.waiting, self.updated) diff --git a/acme/acme/errors_test.py b/acme/acme/errors_test.py index 966be8f1ea5..45b269a0bcc 100644 --- a/acme/acme/errors_test.py +++ b/acme/acme/errors_test.py @@ -1,4 +1,5 @@ """Tests for acme.errors.""" +import datetime import unittest import mock @@ -35,9 +36,9 @@ class PollErrorTest(unittest.TestCase): def setUp(self): from acme.errors import PollError self.timeout = PollError( - exhausted=set([mock.sentinel.AR]), + waiting=[(datetime.datetime(2015, 11, 29), mock.sentinel.AR)], updated={}) - self.invalid = PollError(exhausted=set(), updated={ + self.invalid = PollError(waiting=[], updated={ mock.sentinel.AR: mock.sentinel.AR2}) def test_timeout(self): @@ -45,7 +46,7 @@ def test_timeout(self): self.assertFalse(self.invalid.timeout) def test_repr(self): - self.assertEqual('PollError(exhausted=set([]), updated={sentinel.AR: ' + self.assertEqual('PollError(waiting=[], updated={sentinel.AR: ' 'sentinel.AR2})', repr(self.invalid))
Reverts letsencrypt/letsencrypt#2111 since it seems that may have broken travis tests when merged.
https://api.github.com/repos/certbot/certbot/pulls/2220
2016-01-18T20:14:09Z
2016-01-18T20:14:16Z
2016-01-18T20:14:16Z
2016-05-06T19:21:56Z
1,698
certbot/certbot
2,595
Fix typo in comment
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py index 8e972709355..038db7b47e0 100644 --- a/scrapy/core/downloader/handlers/http11.py +++ b/scrapy/core/downloader/handlers/http11.py @@ -379,7 +379,7 @@ def _cb_bodyready(self, txresponse, request): {'size': expected_size, 'warnsize': warnsize, 'request': request}) def _cancel(_): - # Abort connection inmediately. + # Abort connection immediately. txresponse._transport._producer.abortConnection() d = defer.Deferred(_cancel)
https://api.github.com/repos/scrapy/scrapy/pulls/3059
2018-01-01T16:05:10Z
2018-01-10T20:34:12Z
2018-01-10T20:34:12Z
2018-07-11T20:45:56Z
159
scrapy/scrapy
34,770
Fixes comfy list not being styled
diff --git a/web/extensions/core/colorPalette.js b/web/extensions/core/colorPalette.js index 94bea9ab3e..41541a8d8f 100644 --- a/web/extensions/core/colorPalette.js +++ b/web/extensions/core/colorPalette.js @@ -107,7 +107,7 @@ const colorPalettes = { "descrip-text": "#444", "drag-text": "#555", "error-text": "#F44336", - "border-color": "#CCC" + "border-color": "#888" } }, }, diff --git a/web/style.css b/web/style.css index 34e31726c4..312fc046a5 100644 --- a/web/style.css +++ b/web/style.css @@ -160,9 +160,9 @@ body { .comfy-list { color: var(--descrip-text); - background-color: #333; + background-color: var(--comfy-menu-bg); margin-bottom: 10px; - border-color: #4e4e4e; + border-color: var(--border-color); border-style: solid; }
Missed this in #481, comfy-list was not styled so history and queue were not. Also, Light theme has a bad border color as seen in the history image below since it blends with background. Previous: ![image](https://user-images.githubusercontent.com/23466035/231731631-dadf79ef-f49e-438c-a183-dec2502f1574.png) ![image](https://user-images.githubusercontent.com/23466035/231733996-a6e1cc3d-a9ca-4d55-a9f0-83054f14601f.png) Now: ![image](https://user-images.githubusercontent.com/23466035/231733124-b64fc98e-a025-473b-aab9-af52e1ff5b75.png) ![image](https://user-images.githubusercontent.com/23466035/231733527-602d0878-1d52-40fc-a623-28207d204c58.png)
https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/498
2023-04-13T10:39:13Z
2023-04-13T17:51:38Z
2023-04-13T17:51:38Z
2023-04-13T18:54:35Z
259
comfyanonymous/ComfyUI
17,768
🌐 Add French translation for `docs/fr/docs/advanced/additional-status-code.md`
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md new file mode 100644 index 0000000000000..35b57594d5975 --- /dev/null +++ b/docs/fr/docs/advanced/additional-responses.md @@ -0,0 +1,240 @@ +# Réponses supplémentaires dans OpenAPI + +!!! Attention + Ceci concerne un sujet plutôt avancé. + + Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. + +Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc. + +Ces réponses supplémentaires seront incluses dans le schéma OpenAPI, elles apparaîtront donc également dans la documentation de l'API. + +Mais pour ces réponses supplémentaires, vous devez vous assurer de renvoyer directement une `Response` comme `JSONResponse`, avec votre code HTTP et votre contenu. + +## Réponse supplémentaire avec `model` + +Vous pouvez ajouter à votre décorateur de *paramètre de chemin* un paramètre `responses`. + +Il prend comme valeur un `dict` dont les clés sont des codes HTTP pour chaque réponse, comme `200`, et la valeur de ces clés sont d'autres `dict` avec des informations pour chacun d'eux. + +Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modèle Pydantic, tout comme `response_model`. + +**FastAPI** prendra ce modèle, générera son schéma JSON et l'inclura au bon endroit dans OpenAPI. + +Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire : + +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + +!!! Remarque + Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. + +!!! Info + La clé `model` ne fait pas partie d'OpenAPI. + + **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. + + Le bon endroit est : + + * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : + * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : + * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. + * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. + +Les réponses générées au format OpenAPI pour cette *opération de chemin* seront : + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Les schémas sont référencés à un autre endroit du modèle OpenAPI : + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Types de médias supplémentaires pour la réponse principale + +Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents types de médias pour la même réponse principale. + +Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG : + +```Python hl_lines="19-24 28" +{!../../../docs_src/additional_responses/tutorial002.py!} +``` + +!!! Remarque + Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. + +!!! Info + À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). + + Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. + +## Combinaison d'informations + +Vous pouvez également combiner des informations de réponse provenant de plusieurs endroits, y compris les paramètres `response_model`, `status_code` et `responses`. + +Vous pouvez déclarer un `response_model`, en utilisant le code HTTP par défaut `200` (ou un code personnalisé si vous en avez besoin), puis déclarer des informations supplémentaires pour cette même réponse dans `responses`, directement dans le schéma OpenAPI. + +**FastAPI** conservera les informations supplémentaires des `responses` et les combinera avec le schéma JSON de votre modèle. + +Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui utilise un modèle Pydantic et a une `description` personnalisée. + +Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé : + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API : + +<img src="/img/tutorial/additional-responses/image01.png"> + +## Combinez les réponses prédéfinies et les réponses personnalisées + +Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de nombreux *paramètre de chemin*, mais vous souhaitez les combiner avec des réponses personnalisées nécessaires à chaque *opération de chemin*. + +Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` : + +``` Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur : + +``` Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Vous pouvez utiliser cette technique pour réutiliser certaines réponses prédéfinies dans vos *paramètres de chemin* et les combiner avec des réponses personnalisées supplémentaires. + +Par exemple: + +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` + +## Plus d'informations sur les réponses OpenAPI + +Pour voir exactement ce que vous pouvez inclure dans les réponses, vous pouvez consulter ces sections dans la spécification OpenAPI : + +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responsesObject" class="external-link" target="_blank">Objet Responses de OpenAPI </a>, il inclut le `Response Object`. +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject" class="external-link" target="_blank">Objet Response de OpenAPI </a>, vous pouvez inclure n'importe quoi directement dans chaque réponse à l'intérieur de votre paramètre `responses`. Y compris `description`, `headers`, `content` (à l'intérieur de cela, vous déclarez différents types de médias et schémas JSON) et `links`. diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md new file mode 100644 index 0000000000000..e7b003707bf84 --- /dev/null +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -0,0 +1,37 @@ +# Codes HTTP supplémentaires + +Par défaut, **FastAPI** renverra les réponses à l'aide d'une structure de données `JSONResponse`, en plaçant la réponse de votre *chemin d'accès* à l'intérieur de cette `JSONResponse`. + +Il utilisera le code HTTP par défaut ou celui que vous avez défini dans votre *chemin d'accès*. + +## Codes HTTP supplémentaires + +Si vous souhaitez renvoyer des codes HTTP supplémentaires en plus du code principal, vous pouvez le faire en renvoyant directement une `Response`, comme une `JSONResponse`, et en définissant directement le code HTTP supplémentaire. + +Par exemple, disons que vous voulez avoir un *chemin d'accès* qui permet de mettre à jour les éléments et renvoie les codes HTTP 200 "OK" en cas de succès. + +Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les éléments n'existaient pas auparavant, il les crée et renvoie un code HTTP de 201 "Créé". + +Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez : + +```Python hl_lines="4 25" +{!../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +!!! Attention + Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. + + Elle ne sera pas sérialisée avec un modèle. + + Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). + +!!! note "Détails techniques" + Vous pouvez également utiliser `from starlette.responses import JSONResponse`. + + Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. + +## Documents OpenAPI et API + +Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (la documentation de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer. + +Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml index 1c4f45682f00c..7dce4b1276c69 100644 --- a/docs/fr/mkdocs.yml +++ b/docs/fr/mkdocs.yml @@ -67,6 +67,9 @@ nav: - tutorial/query-params.md - tutorial/body.md - tutorial/background-tasks.md +- Guide utilisateur avancé: + - advanced/additional-status-codes.md + - advanced/additional-responses.md - async.md - Déploiement: - deployment/index.md
Here is the PR to translate the `advanced/additional-status-code.md` See the french translation tracking issue https://github.com/tiangolo/fastapi/issues/1972. Thanks for the reviews
https://api.github.com/repos/tiangolo/fastapi/pulls/5477
2022-10-09T08:46:16Z
2022-11-13T14:03:48Z
2022-11-13T14:03:48Z
2022-11-13T14:03:49Z
3,324
tiangolo/fastapi
22,755
Added uWSGI and example usage to stand-alone WSGI containers documentation
diff --git a/docs/deploying/wsgi-standalone.rst b/docs/deploying/wsgi-standalone.rst index ad43c1441f..bf680976cd 100644 --- a/docs/deploying/wsgi-standalone.rst +++ b/docs/deploying/wsgi-standalone.rst @@ -27,6 +27,22 @@ For example, to run a Flask application with 4 worker processes (``-w .. _eventlet: http://eventlet.net/ .. _greenlet: https://greenlet.readthedocs.io/en/latest/ +uWSGI +-------- + +`uWSGI`_ is a fast application server written in C. It is very configurable +which makes it more complicated to setup than gunicorn. + +Running `uWSGI HTTP Router`_:: + + uwsgi --http 127.0.0.1:5000 --module myproject:app + +For a more optimized setup, see `configuring uWSGI and NGINX`_. + +.. _uWSGI: http://uwsgi-docs.readthedocs.io/en/latest/ +.. _uWSGI HTTP Router: http://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router +.. _configuring uWSGI and NGINX: uwsgi.html#starting-your-app-with-uwsgi + Gevent -------
Talked with @davidism and decided to add section for uWSGI HTTP router / server via embedded mode.
https://api.github.com/repos/pallets/flask/pulls/2302
2017-05-22T23:20:00Z
2017-05-23T01:08:41Z
2017-05-23T01:08:41Z
2020-11-14T04:09:25Z
315
pallets/flask
20,481
Minecraft bug fix: just obtain event instead of execute_event
diff --git a/metagpt/roles/minecraft/critic_agent.py b/metagpt/roles/minecraft/critic_agent.py index 9bc34cbcc..afce29ea2 100644 --- a/metagpt/roles/minecraft/critic_agent.py +++ b/metagpt/roles/minecraft/critic_agent.py @@ -156,7 +156,7 @@ async def _act(self) -> Message: self.maintain_actions(todo) # 获取最新的游戏周边信息 - events = await self._execute_events() + events = await self._obtain_events() self.perform_game_info_callback(events, self.game_memory.update_chest_memory) # logger.info(f"Execute return event is {self.game_memory.event}") context = self.game_memory.context
https://api.github.com/repos/geekan/MetaGPT/pulls/424
2023-10-12T11:31:35Z
2023-10-12T11:32:00Z
2023-10-12T11:32:00Z
2023-10-19T07:41:44Z
173
geekan/MetaGPT
16,742
Deprecate ESP and move the functionality under --preview
diff --git a/CHANGES.md b/CHANGES.md index 4b9ceae81dc..c3e2a3350d3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -30,6 +30,8 @@ - Fix handling of standalone `match()` or `case()` when there is a trailing newline or a comment inside of the parentheses. (#2760) - Black now normalizes string prefix order (#2297) +- Deprecate `--experimental-string-processing` and move the functionality under + `--preview` (#2789) ### Packaging @@ -38,7 +40,8 @@ ### Preview style -- Introduce the `--preview` flag with no style changes (#2752) +- Introduce the `--preview` flag (#2752) +- Add `--experimental-string-processing` to the preview style (#2789) ### Integrations diff --git a/docs/faq.md b/docs/faq.md index c7d5ec33ad9..94a978d826f 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -33,7 +33,7 @@ still proposed on the issue tracker. See Starting in 2022, the formatting output will be stable for the releases made in the same year (other than unintentional bugs). It is possible to opt-in to the latest formatting -styles, using the `--future` flag. +styles, using the `--preview` flag. ## Why is my file not formatted? diff --git a/docs/the_black_code_style/current_style.md b/docs/the_black_code_style/current_style.md index 11fe2c8cceb..1d1e42e75c8 100644 --- a/docs/the_black_code_style/current_style.md +++ b/docs/the_black_code_style/current_style.md @@ -10,6 +10,10 @@ with `# fmt: off` and end with `# fmt: on`, or lines that ends with `# fmt: skip [YAPF](https://github.com/google/yapf)'s block comments to the same effect, as a courtesy for straddling code. +The rest of this document describes the current formatting style. If you're interested +in trying out where the style is heading, see [future style](./future_style.md) and try +running `black --preview`. + ### How _Black_ wraps lines _Black_ ignores previous formatting and applies uniform horizontal and vertical @@ -260,16 +264,6 @@ If you are adopting _Black_ in a large project with pre-existing string conventi you can pass `--skip-string-normalization` on the command line. This is meant as an adoption helper, avoid using this for new projects. -(labels/experimental-string)= - -As an experimental option (can be enabled by `--experimental-string-processing`), -_Black_ splits long strings (using parentheses where appropriate) and merges short ones. -When split, parts of f-strings that don't need formatting are converted to plain -strings. User-made splits are respected when they do not exceed the line length limit. -Line continuation backslashes are converted into parenthesized strings. Unnecessary -parentheses are stripped. Because the functionality is experimental, feedback and issue -reports are highly encouraged! - _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected for both quotations and the text within, although relative indentation in the text is preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the diff --git a/docs/the_black_code_style/future_style.md b/docs/the_black_code_style/future_style.md index 70ffeefc76a..2ec2c0333a5 100644 --- a/docs/the_black_code_style/future_style.md +++ b/docs/the_black_code_style/future_style.md @@ -34,15 +34,18 @@ with \ Although when the target version is Python 3.9 or higher, _Black_ will use parentheses instead since they're allowed in Python 3.9 and higher. -## Improved string processing - -Currently, _Black_ does not split long strings to fit the line length limit. Currently, -there is [an experimental option](labels/experimental-string) to enable splitting -strings. We plan to enable this option by default once it is fully stable. This is -tracked in [this issue](https://github.com/psf/black/issues/2188). - ## Preview style Experimental, potentially disruptive style changes are gathered under the `--preview` CLI flag. At the end of each year, these changes may be adopted into the default style, -as described in [The Black Code Style](./index.rst). +as described in [The Black Code Style](./index.rst). Because the functionality is +experimental, feedback and issue reports are highly encouraged! + +### Improved string processing + +_Black_ will split long string literals and merge short ones. Parentheses are used where +appropriate. When split, parts of f-strings that don't need formatting are converted to +plain strings. User-made splits are respected when they do not exceed the line length +limit. Line continuation backslashes are converted into parenthesized strings. +Unnecessary parentheses are stripped. The stability and status of this feature is +tracked in [this issue](https://github.com/psf/black/issues/2188). diff --git a/src/black/__init__.py b/src/black/__init__.py index 405a01082e7..67c272e3cc9 100644 --- a/src/black/__init__.py +++ b/src/black/__init__.py @@ -241,10 +241,7 @@ def validate_regex( "--experimental-string-processing", is_flag=True, hidden=True, - help=( - "Experimental option that performs more normalization on string literals." - " Currently disabled because it leads to some crashes." - ), + help="(DEPRECATED and now included in --preview) Normalize string literals.", ) @click.option( "--preview", diff --git a/src/black/linegen.py b/src/black/linegen.py index 6008c773f94..9ee42aaaf72 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -23,8 +23,7 @@ from black.strings import normalize_string_prefix, normalize_string_quotes from black.trans import Transformer, CannotTransform, StringMerger from black.trans import StringSplitter, StringParenWrapper, StringParenStripper -from black.mode import Mode -from black.mode import Feature +from black.mode import Mode, Feature, Preview from blib2to3.pytree import Node, Leaf from blib2to3.pgen2 import token @@ -338,7 +337,7 @@ def transform_line( and not (line.inside_brackets and line.contains_standalone_comments()) ): # Only apply basic string preprocessing, since lines shouldn't be split here. - if mode.experimental_string_processing: + if Preview.string_processing in mode: transformers = [string_merge, string_paren_strip] else: transformers = [] @@ -381,7 +380,7 @@ def _rhs( # via type ... https://github.com/mypyc/mypyc/issues/884 rhs = type("rhs", (), {"__call__": _rhs})() - if mode.experimental_string_processing: + if Preview.string_processing in mode: if line.inside_brackets: transformers = [ string_merge, diff --git a/src/black/mode.py b/src/black/mode.py index c8c2bd4eb26..b6d1a1fbbef 100644 --- a/src/black/mode.py +++ b/src/black/mode.py @@ -7,9 +7,10 @@ import sys from dataclasses import dataclass, field -from enum import Enum +from enum import Enum, auto from operator import attrgetter from typing import Dict, Set +from warnings import warn if sys.version_info < (3, 8): from typing_extensions import Final @@ -124,6 +125,13 @@ def supports_feature(target_versions: Set[TargetVersion], feature: Feature) -> b class Preview(Enum): """Individual preview style features.""" + string_processing = auto() + hug_simple_powers = auto() + + +class Deprecated(UserWarning): + """Visible deprecation warning.""" + @dataclass class Mode: @@ -136,6 +144,14 @@ class Mode: experimental_string_processing: bool = False preview: bool = False + def __post_init__(self) -> None: + if self.experimental_string_processing: + warn( + "`experimental string processing` has been included in `preview`" + " and deprecated. Use `preview` instead.", + Deprecated, + ) + def __contains__(self, feature: Preview) -> bool: """ Provide `Preview.FEATURE in Mode` syntax that mirrors the ``preview`` flag. @@ -143,6 +159,8 @@ def __contains__(self, feature: Preview) -> bool: The argument is not checked and features are not differentiated. They only exist to make development easier by clarifying intent. """ + if feature is Preview.string_processing: + return self.preview or self.experimental_string_processing return self.preview def get_cache_key(self) -> str: diff --git a/tests/test_black.py b/tests/test_black.py index 202fe23ddcd..19cff23cb89 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -150,6 +150,11 @@ def test_empty_ff(self) -> None: os.unlink(tmp_file) self.assertFormatEqual(expected, actual) + def test_experimental_string_processing_warns(self) -> None: + self.assertWarns( + black.mode.Deprecated, black.Mode, experimental_string_processing=True + ) + def test_piping(self) -> None: source, expected = read_data("src/black/__init__", data=False) result = BlackRunner().invoke( @@ -342,7 +347,7 @@ def test_detect_pos_only_arguments(self) -> None: @patch("black.dump_to_file", dump_to_stderr) def test_string_quotes(self) -> None: source, expected = read_data("string_quotes") - mode = black.Mode(experimental_string_processing=True) + mode = black.Mode(preview=True) assert_format(source, expected, mode) mode = replace(mode, string_normalization=False) not_normalized = fs(source, mode=mode) diff --git a/tests/test_format.py b/tests/test_format.py index 00cd07f36f7..40f225c9554 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -55,15 +55,6 @@ "tupleassign", ] -EXPERIMENTAL_STRING_PROCESSING_CASES: List[str] = [ - "cantfit", - "comments7", - "long_strings", - "long_strings__edge_case", - "long_strings__regression", - "percent_precedence", -] - PY310_CASES: List[str] = [ "pattern_matching_simple", "pattern_matching_complex", @@ -73,7 +64,15 @@ "parenthesized_context_managers", ] -PREVIEW_CASES: List[str] = [] +PREVIEW_CASES: List[str] = [ + # string processing + "cantfit", + "comments7", + "long_strings", + "long_strings__edge_case", + "long_strings__regression", + "percent_precedence", +] SOURCES: List[str] = [ "src/black/__init__.py", @@ -136,11 +135,6 @@ def test_simple_format(filename: str) -> None: check_file(filename, DEFAULT_MODE) -@pytest.mark.parametrize("filename", EXPERIMENTAL_STRING_PROCESSING_CASES) -def test_experimental_format(filename: str) -> None: - check_file(filename, black.Mode(experimental_string_processing=True)) - - @pytest.mark.parametrize("filename", PREVIEW_CASES) def test_preview_format(filename: str) -> None: check_file(filename, black.Mode(preview=True))
### Description This PR deprecates `--experimental-string-processing` and moves the functionality under `--preview` machinery. ### Checklist - did you ... - [x] Add a CHANGELOG entry if necessary? - [x] Add / update tests if necessary? - [x] Add new / update outdated documentation? I'll review myself for some points of contention. Closes #2756.
https://api.github.com/repos/psf/black/pulls/2789
2022-01-20T22:32:34Z
2022-01-20T23:42:08Z
2022-01-20T23:42:07Z
2022-01-21T07:56:09Z
2,686
psf/black
24,018
Update pretrained_word_embeddings.py
diff --git a/examples/pretrained_word_embeddings.py b/examples/pretrained_word_embeddings.py index 4fea37a69bb..069024c3fdb 100644 --- a/examples/pretrained_word_embeddings.py +++ b/examples/pretrained_word_embeddings.py @@ -101,10 +101,10 @@ print('Preparing embedding matrix.') # prepare embedding matrix -num_words = min(MAX_NUM_WORDS, len(word_index)) + 1 +num_words = min(MAX_NUM_WORDS, len(word_index) + 1) embedding_matrix = np.zeros((num_words, EMBEDDING_DIM)) for word, i in word_index.items(): - if i > MAX_NUM_WORDS: + if i >= MAX_NUM_WORDS: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None:
<!-- Please make sure you've read and understood our contributing guidelines; https://github.com/keras-team/keras/blob/master/CONTRIBUTING.md --> ### Summary Hello, Here's a small example why I think there's a small mistake in the code. ![Example Code](https://i.imgur.com/jZVO97d.png) Now if you check we've specified > MAX_NUM_WORDS = 3 but tokenizer return **n-1** words i.e **2**. So we only have two words in our integer coded corpus. ``` num_words = min(MAX_NUM_WORDS, len(tokenizer.word_index) + 1) # i.e min(3, 8 + 1) embedding_matrix = np.zeros((num_words, 10)) print(embedding_matrix.shape) (3, 10) ``` Then this should be how we create embedding matrix. ``` for word, i in word_index.items(): if i >= MAX_NUM_WORDS: # i. e i >= 3 We also don't want word three to be included. continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector ``` ### Related Issues None. ### PR Overview - [n] This PR requires new unit tests [y/n] (make sure tests are included) - [n] This PR requires to update the documentation [y/n] (make sure the docs are up-to-date) - [n] This PR is backwards compatible [y/n] - [n] This PR changes the current API [y/n] (all API changes need to be approved by fchollet)
https://api.github.com/repos/keras-team/keras/pulls/13073
2019-07-06T13:20:20Z
2019-07-09T21:31:18Z
2019-07-09T21:31:18Z
2019-09-12T07:00:28Z
172
keras-team/keras
47,696
Add FPv2: 2022 Subaru Outback Wilderness
diff --git a/selfdrive/car/subaru/values.py b/selfdrive/car/subaru/values.py index 7a1e9a8a3dc3f5..9975e495ddf5ec 100644 --- a/selfdrive/car/subaru/values.py +++ b/selfdrive/car/subaru/values.py @@ -461,6 +461,7 @@ class SubaruCarInfo(CarInfo): b'\xa1 \x08\x02', b'\xa1 \x06\x02', b'\xa1 \x08\x00', + b'\xa1 "\t\x00', ], (Ecu.eps, 0x746, None): [ b'\x9b\xc0\x10\x00', @@ -482,6 +483,7 @@ class SubaruCarInfo(CarInfo): b'\xe2"`p\x07', b'\xf1\x82\xe2,\xa0@\x07', b'\xbc"`q\x07', + b'\xe3,\xa0@\x07', ], (Ecu.transmission, 0x7e1, None): [ b'\xa5\xfe\xf7@\x00',
**Description** Add missing fw values for 2022 Subaru Outback Wilderness **Route** Route: 7e051e2bb863d0b6|2022-11-17--17-45-50--49
https://api.github.com/repos/commaai/openpilot/pulls/26540
2022-11-18T17:05:01Z
2022-11-21T23:34:21Z
2022-11-21T23:34:21Z
2022-11-21T23:34:48Z
259
commaai/openpilot
9,659
Augmented Generic IE
diff --git a/youtube_dl/extractor/generic.py b/youtube_dl/extractor/generic.py index 7a877b3bcb4..759fd60a739 100644 --- a/youtube_dl/extractor/generic.py +++ b/youtube_dl/extractor/generic.py @@ -102,7 +102,7 @@ def _real_extract(self, url): mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage) if mobj is None: # Broaden the search a little bit: JWPlayer JS loader - mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage) + mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage) if mobj is None: # Try to find twitter cards info mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage) @@ -135,7 +135,7 @@ def _real_extract(self, url): # Video Title - Tagline | Site Name # and so on and so forth; it's just not practical video_title = self._html_search_regex(r'<title>(.*)</title>', - webpage, u'video title') + webpage, u'video title', default=u'video') # video uploader is domain name video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
I changed one of regexes for the generic IE to handle the case in which file is a key inside a dictionary. This occurs sometimes and can be used to handle cases like: http://www.mp4upload.com/embed-rt2yx5n01ydl-650x372.html in which: I also made 'video' the default title for the generic IE. I would argue that the generic IE needs to be a little more forgiving about not being able to find a correct title (the previous link is an example of youtube-dl not finding the correct title). Youtube-dl should not refuse to download a video because a title was not provided by the site.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/954
2013-06-27T18:30:04Z
2013-06-27T18:44:46Z
2013-06-27T18:44:46Z
2014-06-26T01:14:45Z
373
ytdl-org/youtube-dl
49,901
Manual Alignments: Resize bounding box scaling bugfix
diff --git a/tools/lib_alignments/jobs_manual.py b/tools/lib_alignments/jobs_manual.py index 81f4bb3c61..afdb5e2eda 100644 --- a/tools/lib_alignments/jobs_manual.py +++ b/tools/lib_alignments/jobs_manual.py @@ -781,6 +781,8 @@ def move_bounding_box(self, pt_x, pt_y): def resize_bounding_box(self, pt_x, pt_y): """ Resize the bounding box """ + scale = self.interface.get_frame_scaling() + if not self.last_move: self.last_move = (pt_x, pt_y) self.media["bounding_box_orig"] = self.media["bounding_box"] @@ -791,10 +793,12 @@ def resize_bounding_box(self, pt_x, pt_y): original = self.media["bounding_box_orig"] updated = self.media["bounding_box"] - updated[0] = min(self.center[0] - 10, original[0] - move_x) - updated[1] = min(self.center[1] - 10, original[1] - move_y) - updated[2] = max(self.center[0] + 10, original[2] + move_x) - updated[3] = max(self.center[1] + 10, original[3] + move_y) + minsize = int(10 / scale) + center = (int(self.center[0] / scale), int(self.center[1] / scale)) + updated[0] = min(center[0] - minsize, original[0] - move_x) + updated[1] = min(center[1] - minsize, original[1] - move_y) + updated[2] = max(center[0] + minsize, original[2] + move_x) + updated[3] = max(center[1] + minsize, original[3] + move_y) self.update_landmarks() self.last_move = (pt_x, pt_y)
Fix a bug that led to incorrect bounding box on scaled images.
https://api.github.com/repos/deepfakes/faceswap/pulls/511
2018-09-28T08:47:29Z
2018-09-28T08:47:54Z
2018-09-28T08:47:54Z
2018-09-28T08:47:54Z
447
deepfakes/faceswap
18,924
[AIRFLOW-5709] Fix regression in setting custom operator resources.
diff --git a/airflow/models/baseoperator.py b/airflow/models/baseoperator.py index d848c2743227c..5d61e1e77a777 100644 --- a/airflow/models/baseoperator.py +++ b/airflow/models/baseoperator.py @@ -372,7 +372,7 @@ def __init__( d=dag.dag_id if dag else "", t=task_id, tr=weight_rule)) self.weight_rule = weight_rule - self.resources = Resources(*resources) if resources is not None else None + self.resources = Resources(**resources) if resources is not None else None self.run_as_user = run_as_user self.task_concurrency = task_concurrency self.executor_config = executor_config or {} diff --git a/tests/models/test_baseoperator.py b/tests/models/test_baseoperator.py index 2716422edc422..9d2b99b33b370 100644 --- a/tests/models/test_baseoperator.py +++ b/tests/models/test_baseoperator.py @@ -256,3 +256,12 @@ def test_override_jinja_env_option(self): result = task.render_template("{{ foo }}", {"foo": "bar"}) self.assertEqual(result, "bar") + + def test_default_resources(self): + task = DummyOperator(task_id="default-resources") + self.assertIsNone(task.resources) + + def test_custom_resources(self): + task = DummyOperator(task_id="custom-resources", resources={"cpus": 1, "ram": 1024}) + self.assertEqual(task.resources.cpus.qty, 1) + self.assertEqual(task.resources.ram.qty, 1024)
Make sure you have checked _all_ steps below. ### Jira - [x] 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-5709 - 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 - [x] Here are some details about my PR, including screenshots of any UI changes: Fix a regression in custom operator resources introduced in #5259, and add basic unit tests of operator resources. ### Tests - [x] My PR adds the following unit tests __OR__ does not need testing for this extremely good reason: ### Commits - [x] 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 - [x] 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
https://api.github.com/repos/apache/airflow/pulls/6331
2019-10-14T14:53:32Z
2019-11-05T20:23:25Z
2019-11-05T20:23:25Z
2019-11-05T20:23:26Z
364
apache/airflow
14,819
Add a binary coefficient function
diff --git a/binary coefficients b/binary coefficients new file mode 100644 index 0000000000..1d6f9fb410 --- /dev/null +++ b/binary coefficients @@ -0,0 +1,21 @@ +def pascal_triangle( lineNumber ) : + list1 = list() + list1.append([1]) + i=1 + while(i<=lineNumber): + j=1 + l=[] + l.append(1) + while(j<i): + + l.append(list1[i-1][j]+list1[i-1][j-1]) + j=j+1 + l.append(1) + list1.append(l) + i=i+1 + return list1 + +def binomial_coef(n,k): + pascalTriangle=pascal_triangle(n) + return(pascalTriangle[n][k-1]) +
Add a binary coefficient function that generate pascal's triangle and calculate the coefficient (n, k)
https://api.github.com/repos/geekcomputers/Python/pulls/435
2018-11-27T21:10:53Z
2018-12-10T18:48:05Z
2018-12-10T18:48:05Z
2018-12-10T18:48:05Z
208
geekcomputers/Python
31,707
downloaderMW doc typo (spiderMW doc copy remnant)
diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rst index 38d19fb00ed..30075fa7b43 100644 --- a/docs/topics/downloader-middleware.rst +++ b/docs/topics/downloader-middleware.rst @@ -38,7 +38,7 @@ previous (or subsequent) middleware being applied. If you want to disable a built-in middleware (the ones defined in :setting:`DOWNLOADER_MIDDLEWARES_BASE` and enabled by default) you must define it in your project's :setting:`DOWNLOADER_MIDDLEWARES` setting and assign `None` -as its value. For example, if you want to disable the off-site middleware:: +as its value. For example, if you want to disable the user-agent middleware:: DOWNLOADER_MIDDLEWARES = { 'myproject.middlewares.CustomDownloaderMiddleware': 543,
Downloader middleware documentation typo(?). Probably a forgotten word while coping docs from spider middleware.
https://api.github.com/repos/scrapy/scrapy/pulls/590
2014-02-11T20:55:46Z
2014-02-11T21:49:30Z
2014-02-11T21:49:30Z
2014-06-23T22:42:11Z
199
scrapy/scrapy
34,426
Separate tests for single and action_space
diff --git a/gym/vector/tests/test_async_vector_env.py b/gym/vector/tests/test_async_vector_env.py index 497fdc09be0..d835ea0c903 100644 --- a/gym/vector/tests/test_async_vector_env.py +++ b/gym/vector/tests/test_async_vector_env.py @@ -37,12 +37,16 @@ def test_reset_async_vector_env(shared_memory): @pytest.mark.parametrize('shared_memory', [True, False]) -def test_step_async_vector_env(shared_memory): +@pytest.mark.parametrize('use_single_action_space', [True, False]) +def test_step_async_vector_env(shared_memory, use_single_action_space): env_fns = [make_env('CubeCrash-v0', i) for i in range(8)] try: env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) observations = env.reset() - actions = [env.single_action_space.sample() for _ in range(8)] + if use_single_action_space: + actions = [env.single_action_space.sample() for _ in range(8)] + else: + actions = env.action_space.sample() observations, rewards, dones, _ = env.step(actions) finally: env.close() diff --git a/gym/vector/tests/test_sync_vector_env.py b/gym/vector/tests/test_sync_vector_env.py index 800ed10d20b..bdf74b60e48 100644 --- a/gym/vector/tests/test_sync_vector_env.py +++ b/gym/vector/tests/test_sync_vector_env.py @@ -31,12 +31,16 @@ def test_reset_sync_vector_env(): assert observations.shape == env.observation_space.shape -def test_step_sync_vector_env(): +@pytest.mark.parametrize('use_single_action_space', [True, False]) +def test_step_sync_vector_env(use_single_action_space): env_fns = [make_env('CubeCrash-v0', i) for i in range(8)] try: env = SyncVectorEnv(env_fns) observations = env.reset() - actions = [env.single_action_space.sample() for _ in range(8)] + if use_single_action_space: + actions = [env.single_action_space.sample() for _ in range(8)] + else: + actions = env.action_space.sample() observations, rewards, dones, _ = env.step(actions) finally: env.close()
Separate `test_step_...` into two tests, depending on how the actions are created (either from a list of `env.single_action_space.sample()`, or with `env.action_space.sample()`).
https://api.github.com/repos/openai/gym/pulls/1552
2019-06-22T03:13:04Z
2019-06-28T23:32:40Z
2019-06-28T23:32:40Z
2019-06-28T23:33:48Z
520
openai/gym
5,118
added support for Google Images search
diff --git a/langchain/utilities/serpapi.py b/langchain/utilities/serpapi.py index db6ddf79cc13f9..98f4214ce0614b 100644 --- a/langchain/utilities/serpapi.py +++ b/langchain/utilities/serpapi.py @@ -159,7 +159,12 @@ def _process_response(res: dict) -> str: toret = res["organic_results"][0]["snippet"] elif "link" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["link"] - + elif ( + "images_results" in res.keys() + and "thumbnail" in res["images_results"][0].keys() + ): + thumbnails = [item["thumbnail"] for item in res["images_results"][:10]] + toret = thumbnails else: toret = "No good search result found" return toret
- Description: Added Google Image Search support for SerpAPIWrapper - Issue: NA - Dependencies: None - Tag maintainer: @hinthornw - Twitter handle: @sausheong
https://api.github.com/repos/langchain-ai/langchain/pulls/7751
2023-07-15T10:31:54Z
2023-07-15T14:04:18Z
2023-07-15T14:04:18Z
2023-07-15T14:04:18Z
213
langchain-ai/langchain
43,310
Add support for http://www.spankwire.com
diff --git a/youtube_dl/extractor/__init__.py b/youtube_dl/extractor/__init__.py index db69af36192..7a60e09377d 100644 --- a/youtube_dl/extractor/__init__.py +++ b/youtube_dl/extractor/__init__.py @@ -109,6 +109,7 @@ from .sohu import SohuIE from .soundcloud import SoundcloudIE, SoundcloudSetIE, SoundcloudUserIE from .southparkstudios import SouthParkStudiosIE +from .spankwire import SpankwireIE from .spiegel import SpiegelIE from .stanfordoc import StanfordOpenClassroomIE from .statigram import StatigramIE diff --git a/youtube_dl/extractor/spankwire.py b/youtube_dl/extractor/spankwire.py new file mode 100644 index 00000000000..f0d5009c717 --- /dev/null +++ b/youtube_dl/extractor/spankwire.py @@ -0,0 +1,70 @@ +import os +import re + +from .common import InfoExtractor +from ..utils import ( + compat_urllib_parse_urlparse, + compat_urllib_request, + compat_urllib_parse, + unescapeHTML, +) +from ..aes import ( + aes_decrypt_text +) + +class SpankwireIE(InfoExtractor): + _VALID_URL = r'^(?:https?://)?(?:www\.)?(?P<url>spankwire\.com/[^/]*/video(?P<videoid>[0-9]+)/?)' + _TEST = { + u'url': u'http://www.spankwire.com/Buckcherry-s-X-Rated-Music-Video-Crazy-Bitch/video103545/', + u'file': u'103545.mp4', + u'md5': u'1b3f55e345500552dbc252a3e9c1af43', + u'info_dict': { + u"uploader": u"oreusz", + u"title": u"Buckcherry`s X Rated Music Video Crazy Bitch", + u"description": u"Crazy Bitch X rated music video.", + } + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + video_id = mobj.group('videoid') + url = 'http://www.' + mobj.group('url') + + req = compat_urllib_request.Request(url) + req.add_header('Cookie', 'age_verified=1') + webpage = self._download_webpage(req, video_id) + + video_title = self._html_search_regex(r'<h1>([^<]+)', webpage, u'title') + video_uploader = self._html_search_regex(r'by:\s*<a [^>]*>(.+?)</a>', webpage, u'uploader', fatal=False) + thumbnail = self._html_search_regex(r'flashvars\.image_url = "([^"]+)', webpage, u'thumbnail', fatal=False) + description = self._html_search_regex(r'>\s*Description:</div>\s*<[^>]*>([^<]+)', webpage, u'description', fatal=False) + if len(description) == 0: + description = None + + video_urls = list(map(compat_urllib_parse.unquote , re.findall(r'flashvars\.quality_[0-9]{3}p = "([^"]+)', webpage))) + if webpage.find('flashvars\.encrypted = "true"') != -1: + password = self._html_search_regex(r'flashvars\.video_title = "([^"]+)', webpage, u'password').replace('+', ' ') + video_urls = list(map(lambda s: aes_decrypt_text(s, password, 32).decode('utf-8'), video_urls)) + + formats = [] + for video_url in video_urls: + path = compat_urllib_parse_urlparse( video_url ).path + extension = os.path.splitext( path )[1][1:] + format = path.split('/')[4].split('_')[:2] + format = "-".join( format ) + formats.append({ + 'url': video_url, + 'ext': extension, + 'format': format, + 'format_id': format, + }) + formats.sort(key=lambda format: list(map(lambda s: s.zfill(6), format['format'].split('-')))) + + return { + 'id': video_id, + 'uploader': video_uploader, + 'title': video_title, + 'thumbnail': thumbnail, + 'description': description, + 'formats': formats, + }
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/1663
2013-10-27T00:32:08Z
2013-10-28T05:51:41Z
2013-10-28T05:51:41Z
2014-06-23T02:03:46Z
1,059
ytdl-org/youtube-dl
50,307
nit: add kg graph nb to docs
diff --git a/docs/core_modules/data_modules/index/modules.md b/docs/core_modules/data_modules/index/modules.md index eef15d1749641..e55884f0fd344 100644 --- a/docs/core_modules/data_modules/index/modules.md +++ b/docs/core_modules/data_modules/index/modules.md @@ -10,6 +10,8 @@ Tree Index <./index_guide.md> Keyword Table Index <./index_guide.md> /examples/index_structs/knowledge_graph/KnowledgeGraphDemo.ipynb /examples/index_structs/knowledge_graph/KnowledgeGraphIndex_vs_VectorStoreIndex_vs_CustomIndex_combined.ipynb +/examples/query_engine/knowledge_graph_query_engine.ipynb +/examples/query_engine/knowledge_graph_rag_query_engine.ipynb REBEL + Knowledge Graph Index <https://colab.research.google.com/drive/1G6pcR0pXvSkdMQlAK_P-IrYgo-_staxd?usp=sharing> SQL Index </examples/index_structs/struct_indices/SQLIndexDemo.ipynb> /examples/index_structs/struct_indices/duckdb_sql_query.ipynb diff --git a/docs/core_modules/query_modules/query_engine/modules.md b/docs/core_modules/query_modules/query_engine/modules.md index 85685ca88392a..533eeabd853e4 100644 --- a/docs/core_modules/query_modules/query_engine/modules.md +++ b/docs/core_modules/query_modules/query_engine/modules.md @@ -17,6 +17,7 @@ maxdepth: 1 /examples/query_engine/json_query_engine.ipynb /examples/query_engine/pandas_query_engine.ipynb /examples/query_engine/knowledge_graph_query_engine.ipynb +/examples/query_engine/knowledge_graph_rag_query_engine.ipynb ``` ## Advanced diff --git a/llama_index/graph_stores/nebulagraph.py b/llama_index/graph_stores/nebulagraph.py index bcc74373240e6..e972964a668e0 100644 --- a/llama_index/graph_stores/nebulagraph.py +++ b/llama_index/graph_stores/nebulagraph.py @@ -428,7 +428,7 @@ def get_flat_rel_map( f" subj," f" REDUCE(acc = collect(NULL), l in rels | acc + l) AS " f" flattened_rels" - f"RETURN" + f" RETURN" f" subj," f" REDUCE(acc = subj, l in flattened_rels | acc + ', ' + l ) AS " f" flattened_rels"
https://api.github.com/repos/run-llama/llama_index/pulls/7398
2023-08-25T03:02:12Z
2023-08-25T03:06:23Z
2023-08-25T03:06:23Z
2023-08-28T17:10:56Z
559
run-llama/llama_index
6,866
Add word embedding in Go
diff --git a/README.md b/README.md index 53b68363..6bb15507 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,7 @@ For a list of free-to-attend meetups and local events, go [here](https://github. * [paicehusk](https://github.com/Rookii/paicehusk) - Golang implementation of the Paice/Husk Stemming Algorithm. * [snowball](https://github.com/tebeka/snowball) - Snowball Stemmer for Go. * [go-ngram](https://github.com/Lazin/go-ngram) - In-memory n-gram index with compression. +* [word-embedding](github.com/ynqa/word-embedding) - Word Embeddings: the full implementation of word2vec, GloVe in Go. <a name="go-general-purpose"></a> #### General-Purpose Machine Learning
This repo is the models to embed words to vector space, so-called word embedding, or word representation. These models are written in Golang from scratch :) So, you're able to build word vector and estimate similarity list between words with CLI, please see usage! Now it's supported word2vec only, but will be dealt with GloVe, SPPMI from on now.
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/381
2017-05-22T10:15:28Z
2017-05-22T12:04:15Z
2017-05-22T12:04:15Z
2017-05-22T12:04:15Z
211
josephmisiti/awesome-machine-learning
51,856
Proposal: Add Scraper.AI
diff --git a/README.md b/README.md index 515b763873..f378b10c3d 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,7 @@ API | Description | Auth | HTTPS | CORS | | [QR code](http://goqr.me/api/) | Generate and decode / read QR code graphics | No | Yes | Unknown | | [QuickChart](https://quickchart.io/) | Generate chart and graph images | No | Yes | Yes | | [ReqRes](https://reqres.in/ ) | A hosted REST-API ready to respond to your AJAX requests | No | Yes | Unknown | +| [Scraper.AI](https://docs.scraper.ai/#/) | Extract and monitor data from any website | `apiKey` | Yes | Unknown | | [ScraperApi](https://www.scraperapi.com) | Easily build scalable web scrapers | `apiKey` | Yes | Unknown | | [ScreenshotAPI.net](https://screenshotapi.net/) | Create pixel-perfect website screenshots | `apiKey` | Yes | Yes | | [SHOUTCLOUD](http://shoutcloud.io/) | ALL-CAPS AS A SERVICE | No | No | Unknown |
Add Scraper.AI to the list <!-- 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: --> - [x] My submission is formatted according to the guidelines in the [contributing guide](CONTRIBUTING.md) - [x] My addition is ordered alphabetically - [x] My submission has a useful description - [x] The description does not end with punctuation - [x] Each table column is padded with one space on either side - [x] I have searched the repository for any relevant issues or pull requests - [ ] Any category I am creating has the minimum requirement of 3 items - [x] All changes have been [squashed][squash-link] into a single commit [squash-link]: <https://github.com/todotxt/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit>
https://api.github.com/repos/public-apis/public-apis/pulls/1436
2020-10-28T09:25:06Z
2020-11-02T20:01:17Z
2020-11-02T20:01:17Z
2020-11-02T20:01:41Z
265
public-apis/public-apis
35,383
added Bookcrossing, GDProfiles, Bazar.cz, Chatujme.cz and Avízo.cz
diff --git a/data.json b/data.json index 0ea979c76..968d68b48 100644 --- a/data.json +++ b/data.json @@ -1588,5 +1588,47 @@ "urlMain": "https://segmentfault.com/", "username_claimed": "bule", "username_unclaimed": "noonewouldeverusethis7" + }, + "Bookcrossing": { + "errorType": "status_code", + "rank": 52161, + "url": "https://www.bookcrossing.com/mybookshelf/{}/", + "urlMain": "https://www.bookcrossing.com/", + "username_claimed": "blue", + "username_unclaimed": "noonewouldeverusethis" + }, + "GDProfiles": { + "errorType": "status_code", + "rank": 6211812, + "url": "https://gdprofiles.com/{}", + "urlMain": "https://gdprofiles.com/", + "username_claimed": "blue", + "username_unclaimed": "noonewouldeverusethis" + }, + "Bazar.cz": { + "errorType": "response_url", + "errorUrl": "https://www.bazar.cz/error404.aspx", + "rank": 597773, + "url": "https://www.bazar.cz/{}/", + "urlMain": "https://www.bazar.cz/", + "username_claimed": "pianina", + "username_unclaimed": "noonewouldeverusethis" + }, + "Chatujme.cz": { + "errorType": "message", + "errorMsg": "Neexistujicí profil", + "url": "https://profil.chatujme.cz/{}", + "urlMain": "https://chatujme.cz/", + "username_claimed": "david", + "username_unclaimed": "noonewouldeverusethis" + }, + "Avízo.cz": { + "errorType": "response_url", + "errorUrl": "https://www.avizo.cz/", + "rank": 183652, + "url": "https://www.avizo.cz/{}/", + "urlMain": "https://www.avizo.cz/", + "username_claimed": "blue", + "username_unclaimed": "noonewouldeverusethis" } } \ No newline at end of file
https://api.github.com/repos/sherlock-project/sherlock/pulls/367
2019-11-26T14:42:11Z
2019-11-26T15:06:41Z
2019-11-26T15:06:41Z
2019-11-29T22:01:29Z
576
sherlock-project/sherlock
36,572
MSI installer
diff --git a/Methodology and Resources/Windows - Privilege Escalation.md b/Methodology and Resources/Windows - Privilege Escalation.md index 9677f30691..afb3a31166 100644 --- a/Methodology and Resources/Windows - Privilege Escalation.md +++ b/Methodology and Resources/Windows - Privilege Escalation.md @@ -30,7 +30,9 @@ * [EoP - $PATH Interception](#eop---path-interception) * [EoP - Named Pipes](#eop---named-pipes) * [EoP - Kernel Exploitation](#eop---kernel-exploitation) -* [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated) +* [EoP - Microsoft Windows Installer](#eop---microsoft-windows-installer) + * [AlwaysInstallElevated](#alwaysinstallelevated) + * [CustomActions](#customactions) * [EoP - Insecure GUI apps](#eop---insecure-gui-apps) * [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers) * [EoP - Printers](#eop---printers) @@ -837,17 +839,22 @@ To cross compile a program from Kali, use the following command. Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c ``` -## EoP - AlwaysInstallElevated +## EoP - Microsoft Windows Installer -Check if these registry values are set to "1". +### AlwaysInstallElevated -```powershell -$ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated -$ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated +Using the `reg query` command, you can check the status of the `AlwaysInstallElevated` registry key for both the user and the machine. If both queries return a value of `0x1`, then `AlwaysInstallElevated` is enabled for both user and machine, indicating the system is vulnerable. -$ Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer -$ Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer -``` +* Shell command + ```powershell + reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated + reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated + ``` +* PowerShell command + ```powershell + Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer + Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer + ``` Then create an MSI package and install it. @@ -862,6 +869,45 @@ Technique also available in : * PowerUp.ps1 : `Get-RegistryAlwaysInstallElevated`, `Write-UserAddMSI` +### CustomActions + +> Custom Actions in MSI allow developers to specify scripts or executables to be run at various points during an installation + +* [mgeeky/msidump](https://github.com/mgeeky/msidump) - a tool that analyzes malicious MSI installation packages, extracts files, streams, binary data and incorporates YARA scanner. +* [activescott/lessmsi](https://github.com/activescott/lessmsi) - A tool to view and extract the contents of an Windows Installer (.msi) file. +* [mandiant/msi-search](https://github.com/mandiant/msi-search) - This tool simplifies the task for red team operators and security teams to identify which MSI files correspond to which software and enables them to download the relevant file. + +Enumerate products on the machine + +```ps1 +wmic product get identifyingnumber,name,vendor,version +``` + +Execute the repair process with the `/fa` parameter to trigger the CustomActions. +We can use both IdentifyingNumber `{E0F1535A-8414-5EF1-A1DD-E17EDCDC63F1}` or path to the installer `c:\windows\installer\XXXXXXX.msi`. +The repair will run with the NT SYSTEM account. + +```ps1 +$installed = Get-WmiObject Win32_Product +$string= $installed | select-string -pattern "PRODUCTNAME" +$string[0] -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}' +Start-Process -FilePath "msiexec.exe" -ArgumentList "/fa $($matches[0])" +``` + +Common mistakes in MSI installers: + +* Missing quiet parameters: it will spawn `conhost.exe` as `NT SYSTEM`. Use `[CTRL]+[A]` to select some text in it, it will pause the execution. + * conhost -> properties -> "legacy console mode" Link -> Internet Explorer -> CTRL+O –> cmd.exe +* GUI with direct actions: open a URL and start the browser then use the same scenario. +* Binaries/Scripts loaded from user writable paths: you might need to win the race condition. +* DLL hijacking/search order abusing +* PowerShell `-NoProfile` missing: Add custom commands into your profile + ```ps1 + new-item -Path $PROFILE -Type file -Force + echo "Start-Process -FilePath cmd.exe -Wait;" > $PROFILE + ``` + + ## EoP - Insecure GUI apps Application running as SYSTEM allowing an user to spawn a CMD, or browse directories. @@ -1444,4 +1490,7 @@ Detailed information about the vulnerability : https://www.zerodayinitiative.com * [Bypassing AppLocker by abusing HashInfo - 2022-08-19 - Ian](https://shells.systems/post-bypassing-applocker-by-abusing-hashinfo/) * [Giving JuicyPotato a second chance: JuicyPotatoNG - @decoder_it, @splinter_code](https://decoder.cloud/2022/09/21/giving-juicypotato-a-second-chance-juicypotatong/) * [IN THE POTATO FAMILY, I WANT THEM ALL - @BlWasp_ ](https://hideandsec.sh/books/windows-sNL/page/in-the-potato-family-i-want-them-all) -* [Potatoes - Windows Privilege Escalation - Jorge Lajara - November 22, 2020](https://jlajara.gitlab.io/Potatoes_Windows_Privesc) \ No newline at end of file +* [Potatoes - Windows Privilege Escalation - Jorge Lajara - November 22, 2020](https://jlajara.gitlab.io/Potatoes_Windows_Privesc) +* [MSIFortune - LPE with MSI Installers - Oct 3, 2023 - PfiatDe](https://badoption.eu/blog/2023/10/03/MSIFortune.html) +* [MSI Shenanigans. Part 1 – Offensive Capabilities Overview - DECEMBER 8, 2022 - Mariusz Banach](https://mgeeky.tech/msi-shenanigans-part-1/) +* [Escalating Privileges via Third-Party Windows Installers - ANDREW OLIVEAU - JUL 19, 2023](https://www.mandiant.com/resources/blog/privileges-third-party-windows-installers) \ No newline at end of file
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/679
2023-10-11T19:06:30Z
2023-10-11T19:06:37Z
2023-10-11T19:06:37Z
2023-10-11T19:06:48Z
1,697
swisskyrepo/PayloadsAllTheThings
8,498
remove Freebsd 13.1 from test matrix
diff --git a/.azure-pipelines/azure-pipelines.yml b/.azure-pipelines/azure-pipelines.yml index 9c3281b55e912d..a231cdc196a181 100644 --- a/.azure-pipelines/azure-pipelines.yml +++ b/.azure-pipelines/azure-pipelines.yml @@ -93,8 +93,6 @@ stages: test: rhel/9.2@3.11 - name: FreeBSD 12.4 test: freebsd/12.4 - - name: FreeBSD 13.1 - test: freebsd/13.1 - name: FreeBSD 13.2 test: freebsd/13.2 groups: @@ -109,8 +107,6 @@ stages: test: rhel/8.8 - name: RHEL 9.2 test: rhel/9.2 - - name: FreeBSD 13.1 - test: freebsd/13.1 - name: FreeBSD 13.2 test: freebsd/13.2 groups: diff --git a/changelogs/fragments/fbsd13_1_remove.yml b/changelogs/fragments/fbsd13_1_remove.yml new file mode 100644 index 00000000000000..a334c1f8f80f64 --- /dev/null +++ b/changelogs/fragments/fbsd13_1_remove.yml @@ -0,0 +1,2 @@ +minor_changes: + - ansible-test - Removed `freebsd/13.1` remote. diff --git a/test/lib/ansible_test/_data/completion/remote.txt b/test/lib/ansible_test/_data/completion/remote.txt index b317d8595c1909..9eb361a59486ca 100644 --- a/test/lib/ansible_test/_data/completion/remote.txt +++ b/test/lib/ansible_test/_data/completion/remote.txt @@ -3,7 +3,6 @@ alpine become=doas_sudo provider=aws arch=x86_64 fedora/37 python=3.11 become=sudo provider=aws arch=x86_64 fedora become=sudo provider=aws arch=x86_64 freebsd/12.4 python=3.9 python_dir=/usr/local/bin become=su_sudo provider=aws arch=x86_64 -freebsd/13.1 python=3.8,3.7,3.9,3.10 python_dir=/usr/local/bin become=su_sudo provider=aws arch=x86_64 freebsd/13.2 python=3.9,3.11 python_dir=/usr/local/bin become=su_sudo provider=aws arch=x86_64 freebsd python_dir=/usr/local/bin become=su_sudo provider=aws arch=x86_64 macos/13.2 python=3.11 python_dir=/usr/local/bin become=sudo provider=parallels arch=x86_64
fixes #80416 ##### ISSUE TYPE <!--- Pick one below and delete the rest --> - Test Pull Request ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below --> tests
https://api.github.com/repos/ansible/ansible/pulls/81058
2023-06-14T13:52:11Z
2023-06-15T18:59:33Z
2023-06-15T18:59:33Z
2023-06-22T13:00:12Z
664
ansible/ansible
49,223
Delete unused --deepspeed_mpi command line argument
diff --git a/deepspeed/__init__.py b/deepspeed/__init__.py index 87b959f56be0..06a04c791de3 100755 --- a/deepspeed/__init__.py +++ b/deepspeed/__init__.py @@ -234,12 +234,6 @@ def _add_core_arguments(parser): type=str, help='Deprecated DeepSpeed json configuration file.') - group.add_argument('--deepspeed_mpi', - default=False, - action='store_true', - help="Run via MPI, this will attempt to discover the necessary variables to initialize torch " - "distributed from the MPI environment") - return parser
I noticed this argument in my command-line arguments being added by DeepSpeed, and turns out it being False by default has no effect. Since it is not used anywhere, it's probably best to delete it.
https://api.github.com/repos/microsoft/DeepSpeed/pulls/4981
2024-01-19T20:17:27Z
2024-01-23T20:36:35Z
2024-01-23T20:36:35Z
2024-01-23T20:37:03Z
152
microsoft/DeepSpeed
10,135
Fix base.py
diff --git a/llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py b/llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py index ed58e7aa08f2e..e2b351e1ed248 100644 --- a/llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py +++ b/llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py @@ -54,7 +54,7 @@ def class_name(cls) -> str: def _format_query_text(self, query_text: str) -> List[str]: """Format query text.""" - instruction = self.text_instruction + instruction = self.query_instruction if instruction is None: instruction = get_query_instruct_for_model_name(self.model_name)
# Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. Fixes # (issue) The wrong instruction text was used for the query. ## Type of Change Please delete options that are not relevant. - [x] Bug fix (non-breaking change which fixes an issue)
https://api.github.com/repos/run-llama/llama_index/pulls/11327
2024-02-23T16:22:30Z
2024-02-23T17:47:42Z
2024-02-23T17:47:42Z
2024-02-23T17:47:42Z
226
run-llama/llama_index
6,704
Fix minor typo in ES.59
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 87483df80..2eeb06c42 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -12424,7 +12424,7 @@ The language already knows that a returned value is a temporary object that can * Flag use of `std::move(x)` where `x` is an rvalue or the language will already treat it as an rvalue, including `return std::move(local_variable);` and `std::move(f())` on a function that returns by value. * Flag functions taking an `S&&` parameter if there is no `const S&` overload to take care of lvalues. -* Flag a `std::move`s argument passed to a parameter, except when the parameter type is an `X&&` rvalue reference or the type is move-only and the parameter is passed by value. +* Flag a `std::move`d argument passed to a parameter, except when the parameter type is an `X&&` rvalue reference or the type is move-only and the parameter is passed by value. * Flag when `std::move` is applied to a forwarding reference (`T&&` where `T` is a template parameter type). Use `std::forward` instead. * Flag when `std::move` is applied to other than an rvalue reference to non-const. (More general case of the previous rule to cover the non-forwarding cases.) * Flag when `std::forward` is applied to an rvalue reference (`X&&` where `X` is a non-template parameter type). Use `std::move` instead.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/2037
2023-02-12T16:34:29Z
2023-02-12T18:46:45Z
2023-02-12T18:46:45Z
2023-02-12T18:46:45Z
362
isocpp/CppCoreGuidelines
16,065
Update UI and sponsers
diff --git a/fastchat/serve/gradio_block_arena_anony.py b/fastchat/serve/gradio_block_arena_anony.py index 978f76b75a..a598a8c9a4 100644 --- a/fastchat/serve/gradio_block_arena_anony.py +++ b/fastchat/serve/gradio_block_arena_anony.py @@ -196,7 +196,7 @@ def share_click(state0, state1, model_selector0, model_selector1, request: gr.Re "chatglm-6b": 0.5, } -SAMPLING_BOOST_MODELS = ["llama-2-70b-chat", "codellama-34b-instruct"] +SAMPLING_BOOST_MODELS = ["wizardlm-70b"] model_pairs = [] model_pairs_weights = [] @@ -420,12 +420,12 @@ def build_side_by_side_ui_anony(models): with gr.Column(scale=20): textbox = gr.Textbox( show_label=False, - placeholder="Enter text and press ENTER", + placeholder="Enter your prompt here and press ENTER", visible=False, container=False, ) with gr.Column(scale=1, min_width=50): - send_btn = gr.Button(value="Send", visible=False) + send_btn = gr.Button(value="Battle", visible=False, variant="primary") with gr.Row() as button_row2: regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) diff --git a/fastchat/serve/gradio_block_arena_named.py b/fastchat/serve/gradio_block_arena_named.py index b26172f3e4..c031d28c29 100644 --- a/fastchat/serve/gradio_block_arena_named.py +++ b/fastchat/serve/gradio_block_arena_named.py @@ -352,12 +352,12 @@ def build_side_by_side_ui_named(models): with gr.Column(scale=20): textbox = gr.Textbox( show_label=False, - placeholder="Enter text and press ENTER", + placeholder="Enter your prompt here and press ENTER", visible=False, container=False, ) with gr.Column(scale=1, min_width=50): - send_btn = gr.Button(value="Send", visible=False) + send_btn = gr.Button(value="Battle", visible=False, variant="primary") with gr.Row() as button_row2: regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) diff --git a/fastchat/serve/gradio_web_server.py b/fastchat/serve/gradio_web_server.py index c2e22e5627..2fae670dc1 100644 --- a/fastchat/serve/gradio_web_server.py +++ b/fastchat/serve/gradio_web_server.py @@ -591,12 +591,12 @@ def build_single_model_ui(models, add_promotion_links=False): with gr.Column(scale=20): textbox = gr.Textbox( show_label=False, - placeholder="Enter text and press ENTER", + placeholder="Enter your prompt here and press ENTER", visible=False, container=False, ) with gr.Column(scale=1, min_width=50): - send_btn = gr.Button(value="Send", visible=False) + send_btn = gr.Button(value="Send", visible=False, variant="primary") with gr.Row(visible=False) as button_row: upvote_btn = gr.Button(value="👍 Upvote", interactive=False) diff --git a/fastchat/serve/monitor/monitor.py b/fastchat/serve/monitor/monitor.py index 395f2bf84e..b2081bc0d8 100644 --- a/fastchat/serve/monitor/monitor.py +++ b/fastchat/serve/monitor/monitor.py @@ -30,11 +30,11 @@ def make_leaderboard_md(elo_results): | [Blog](https://lmsys.org/blog/2023-05-03-arena/) | [GitHub](https://github.com/lm-sys/FastChat) | [Paper](https://arxiv.org/abs/2306.05685) | [Dataset](https://huggingface.co/datasets/lmsys/chatbot_arena_conversations) | [Twitter](https://twitter.com/lmsysorg) | [Discord](https://discord.gg/HSWAKCrnFx) | 🏆 This leaderboard is based on the following three benchmarks. -- [Chatbot Arena](https://lmsys.org/blog/2023-05-03-arena/) - a crowdsourced, randomized battle platform. We use 50K+ user votes to compute Elo ratings. +- [Chatbot Arena](https://lmsys.org/blog/2023-05-03-arena/) - a crowdsourced, randomized battle platform. We use 70K+ user votes to compute Elo ratings. - [MT-Bench](https://arxiv.org/abs/2306.05685) - a set of challenging multi-turn questions. We use GPT-4 to grade the model responses. - [MMLU](https://arxiv.org/abs/2009.03300) (5-shot) - a test to measure a model's multitask accuracy on 57 tasks. -💻 Code: The Arena Elo ratings are computed by this [notebook]({notebook_url}). The MT-bench scores (single-answer grading on a scale of 10) are computed by [fastchat.llm_judge](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge). The MMLU scores are computed by [InstructEval](https://github.com/declare-lab/instruct-eval) and [Chain-of-Thought Hub](https://github.com/FranxYao/chain-of-thought-hub). Higher values are better for all benchmarks. Empty cells mean not available. +💻 Code: The Arena Elo ratings are computed by this [notebook]({notebook_url}). The MT-bench scores (single-answer grading on a scale of 10) are computed by [fastchat.llm_judge](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge). The MMLU scores are computed by [InstructEval](https://github.com/declare-lab/instruct-eval) and [Chain-of-Thought Hub](https://github.com/FranxYao/chain-of-thought-hub). Higher values are better for all benchmarks. Empty cells mean not available. Last updated: Sept, 2023. """ return leaderboard_md @@ -241,6 +241,11 @@ def build_leaderboard_tab(elo_results_file, leaderboard_table_file): "#### Figure 4: Average Win Rate Against All Other Models (Assuming Uniform Sampling and No Ties)" ) plot_4 = gr.Plot(p4, show_label=False) + + from fastchat.serve.gradio_web_server import acknowledgment_md + + gr.Markdown(acknowledgment_md) + return [md_1, plot_1, plot_2, plot_3, plot_4]
https://api.github.com/repos/lm-sys/FastChat/pulls/2387
2023-09-08T22:20:56Z
2023-09-08T22:21:19Z
2023-09-08T22:21:19Z
2023-09-08T22:21:22Z
1,548
lm-sys/FastChat
41,460
Fixing auto_test.py for Python 2.6
diff --git a/letsencrypt-auto-source/tests/auto_test.py b/letsencrypt-auto-source/tests/auto_test.py index 3b7e8731bc4..7f0b31b67f5 100644 --- a/letsencrypt-auto-source/tests/auto_test.py +++ b/letsencrypt-auto-source/tests/auto_test.py @@ -11,7 +11,7 @@ import socket import ssl from stat import S_IRUSR, S_IXUSR -from subprocess import CalledProcessError, check_output, Popen, PIPE +from subprocess import CalledProcessError, Popen, PIPE import sys from tempfile import mkdtemp from threading import Thread @@ -146,7 +146,9 @@ def out_and_err(command, input=None, shell=False, env=None): out, err = process.communicate(input=input) status = process.poll() # same as in check_output(), though wait() sounds better if status: - raise CalledProcessError(status, command, output=out) + error = CalledProcessError(status, command) + error.output = out + raise error return out, err
#2759 followup, required for #2671.
https://api.github.com/repos/certbot/certbot/pulls/2926
2016-05-05T07:24:56Z
2016-05-27T21:39:44Z
2016-05-27T21:39:44Z
2016-05-27T21:41:17Z
247
certbot/certbot
3,169
Fix XMPP room notifications
diff --git a/homeassistant/components/xmpp/notify.py b/homeassistant/components/xmpp/notify.py index 6b4faf324585..28d60d317e00 100644 --- a/homeassistant/components/xmpp/notify.py +++ b/homeassistant/components/xmpp/notify.py @@ -159,6 +159,9 @@ def __init__(self): async def start(self, event): """Start the communication and sends the message.""" + if room: + _LOGGER.debug("Joining room %s", room) + await self.plugin["xep_0045"].join_muc_wait(room, sender, seconds=0) # Sending image and message independently from each other if data: await self.send_file(timeout=timeout) @@ -173,9 +176,6 @@ async def send_file(self, timeout=None): Send XMPP file message using OOB (XEP_0066) and HTTP Upload (XEP_0363) """ - if room: - self.plugin["xep_0045"].join_muc(room, sender) - try: # Uploading with XEP_0363 _LOGGER.debug("Timeout set to %ss", timeout) @@ -335,8 +335,7 @@ def send_text_message(self): """Send a text only message to a room or a recipient.""" try: if room: - _LOGGER.debug("Joining room %s", room) - self.plugin["xep_0045"].join_muc(room, sender) + _LOGGER.debug("Sending message to room %s", room) self.send_message(mto=room, mbody=message, mtype="groupchat") else: for recipient in recipients:
<!-- You are amazing! Thanks for contributing to our project! Please, DO NOT DELETE ANY TEXT from this template! (unless instructed). --> ## Proposed change <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue in the additional information section. --> Fixes a bug with XMPP notifications sent to MUC rooms. Current code has a race condition between joining a room and sending the message, which causes the message to fail on ejabberd with the error `Only occupants are allowed to send messages to the conference`. The correct way is to wait for the join request to complete, and only then to send the message. Slixmpp v1.8.0 introduced a new `join_muc_wait` function that does that and deprecated the original `join_muc` function that does not wait. I also optimized the code, so that if you send a text and a picture, it only joins the room once for both messages instead of twice. Slixmpp deprecation note: https://github.com/poezio/slixmpp/blob/7a0fb970833c778ed50dcb49c5b7b4043d57b1e5/slixmpp/plugins/xep_0045/muc.py#L361 ## Type of change <!-- What type of change does your PR introduce to Home Assistant? NOTE: Please, check only 1! box! If your PR requires multiple boxes to be checked, you'll most likely need to split it into multiple PRs. This makes things easier and faster to code review. --> - [ ] Dependency upgrade - [X] Bugfix (non-breaking change which fixes an issue) - [ ] New integration (thank you!) - [ ] New feature (which adds functionality to an existing integration) - [ ] Deprecation (breaking change to happen in the future) - [ ] Breaking change (fix/feature causing existing functionality to break) - [ ] Code quality improvements to existing code or addition of tests ## Additional information <!-- Details are important, and help maintainers processing your PR. Please be sure to fill out additional details, if applicable. --> - This PR fixes or closes issue: fixes # - This PR is related to issue: - Link to documentation pull request: ## Checklist <!-- Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. --> - [X] The code change is tested and works locally. - [X] Local tests pass. **Your PR cannot be merged unless tests pass** - [X] There is no commented out code in this PR. - [X] I have followed the [development checklist][dev-checklist] - [ ] The code has been formatted using Black (`black --fast homeassistant tests`) - [ ] Tests have been added to verify that the new code works. If user exposed functionality or configuration variables are added/changed: - [ ] Documentation added/updated for [www.home-assistant.io][docs-repository] If the code communicates with devices, web services, or third-party tools: - [ ] The [manifest file][manifest-docs] has all fields filled out correctly. Updated and included derived files by running: `python3 -m script.hassfest`. - [ ] New or updated dependencies have been added to `requirements_all.txt`. Updated by running `python3 -m script.gen_requirements_all`. - [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description. - [ ] Untested files have been added to `.coveragerc`. <!-- This project is very active and we have a high turnover of pull requests. Unfortunately, the number of incoming pull requests is higher than what our reviewers can review and merge so there is a long backlog of pull requests waiting for review. You can help here! By reviewing another pull request, you will help raise the code quality of that pull request and the final review will be faster. This way the general pace of pull request reviews will go up and your wait time will go down. When picking a pull request to review, try to choose one that hasn't yet been reviewed. Thanks for helping out! --> To help with the load of incoming pull requests: - [ ] I have reviewed two other [open pull requests][prs] in this repository. [prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure <!-- Thank you for contributing <3 Below, some useful links you could explore: --> [dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html [manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html [quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html [docs-repository]: https://github.com/home-assistant/home-assistant.io
https://api.github.com/repos/home-assistant/core/pulls/80794
2022-10-22T21:40:45Z
2022-10-24T19:10:57Z
2022-10-24T19:10:57Z
2022-10-25T19:16:22Z
379
home-assistant/core
39,139
have multi-discrete use same dtype as discrete, fixes #1204
diff --git a/gym/spaces/multi_discrete.py b/gym/spaces/multi_discrete.py index b92173205e6..a8406e98dcf 100644 --- a/gym/spaces/multi_discrete.py +++ b/gym/spaces/multi_discrete.py @@ -1,4 +1,3 @@ -import gym import numpy as np from .space import Space @@ -29,9 +28,9 @@ def __init__(self, nvec): nvec: vector of counts of each categorical variable """ assert (np.array(nvec) > 0).all(), 'nvec (counts) have to be positive' - self.nvec = np.asarray(nvec, dtype=np.uint32) + self.nvec = np.asarray(nvec, dtype=np.int64) - super(MultiDiscrete, self).__init__(self.nvec.shape, np.uint32) + super(MultiDiscrete, self).__init__(self.nvec.shape, np.int64) self.np_random = np.random.RandomState() def seed(self, seed): diff --git a/gym/spaces/space.py b/gym/spaces/space.py index f12b631f171..d0f1483b5dc 100644 --- a/gym/spaces/space.py +++ b/gym/spaces/space.py @@ -1,6 +1,3 @@ -import numpy as np - - class Space(object): """Defines the observation and action spaces, so you can write generic code that applies to any Env. For example, you can choose a random
https://api.github.com/repos/openai/gym/pulls/1400
2019-03-22T22:02:56Z
2019-03-23T21:49:46Z
2019-03-23T21:49:46Z
2019-03-23T21:49:47Z
357
openai/gym
5,485
Fixed a type in a docstring
diff --git a/acme/acme/client.py b/acme/acme/client.py index 776ddb38a11..c3e28ef47f0 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -340,7 +340,7 @@ def poll_and_request_issuance( `PollError` with non-empty ``waiting`` is raised. :returns: ``(cert, updated_authzrs)`` `tuple` where ``cert`` is - the issued certificate (`.messages.CertificateResource.), + the issued certificate (`.messages.CertificateResource`), and ``updated_authzrs`` is a `tuple` consisting of updated Authorization Resources (`.AuthorizationResource`) as present in the responses from server, and in the same order
https://api.github.com/repos/certbot/certbot/pulls/1881
2015-12-12T21:12:17Z
2015-12-13T01:51:51Z
2015-12-13T01:51:51Z
2016-05-06T19:21:21Z
179
certbot/certbot
1,199
[extractor/twitch] Support AV1/HEVC extraction
diff --git a/yt_dlp/extractor/twitch.py b/yt_dlp/extractor/twitch.py index c55786a0dce..80cba09155d 100644 --- a/yt_dlp/extractor/twitch.py +++ b/yt_dlp/extractor/twitch.py @@ -191,17 +191,25 @@ def _get_thumbnails(self, thumbnail): }] if thumbnail else None def _extract_twitch_m3u8_formats(self, path, video_id, token, signature): - return self._extract_m3u8_formats( + formats = self._extract_m3u8_formats( f'{self._USHER_BASE}/{path}/{video_id}.m3u8', video_id, 'mp4', query={ 'allow_source': 'true', 'allow_audio_only': 'true', 'allow_spectre': 'true', 'p': random.randint(1000000, 10000000), + 'platform': 'web', 'player': 'twitchweb', + 'supported_codecs': 'av1,h265,h264', 'playlist_include_framerate': 'true', 'sig': signature, 'token': token, }) + for fmt in formats: + if fmt.get('vcodec') and fmt['vcodec'].startswith('av01'): + # mpegts does not yet have proper support for av1 + fmt['downloader_options'] = {'ffmpeg_args_out': ['-f', 'mp4']} + + return formats class TwitchVodIE(TwitchBaseIE):
Signals support for AV1 and HEVC codecs. Tested on this stream: https://www.twitch.tv/r0dn3y Before: ``` ID EXT RESOLUTION FPS │ TBR PROTO │ VCODEC ACODEC ABR ──────────────────────────────────────────────────────────────────────── audio_only mp4 audio only │ 160k m3u8 │ audio only mp4a.40.2 160k 480p30 mp4 854x480 30 │ 1385k m3u8 │ avc1.64001F mp4a.40.2 ``` After: ``` ID EXT RESOLUTION FPS HDR │ TBR PROTO │ VCODEC ACODEC ABR ───────────────────────────────────────────────────────────────────────────────────── audio_only mp4 audio only │ 160k m3u8 │ audio only mp4a.40.2 160k 480p30 mp4 854x480 30 │ 1385k m3u8 │ avc1.64001F mp4a.40.2 720p60 mp4 1280x720 60 10 │ 4041k m3u8 │ av01.0.08M.10 mp4a.40.2 1080p60 mp4 1920x1080 60 10 │ 6690k m3u8 │ av01.0.09M.10 mp4a.40.2 1440p60__source_ mp4 2560x1440 60 │ 12946k m3u8 │ hvc1.2.4.L150 mp4a.40.2 ``` <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 all of the following options that apply: - [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)) </details>
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/9158
2024-02-06T22:01:09Z
2024-04-03T18:38:51Z
2024-04-03T18:38:51Z
2024-04-03T18:38:51Z
353
yt-dlp/yt-dlp
8,150
feat(replays): Event Details Replay Section Player
diff --git a/static/app/components/events/eventEntries.tsx b/static/app/components/events/eventEntries.tsx index d9e1fe5503f31..ad7d8fb96f6e1 100644 --- a/static/app/components/events/eventEntries.tsx +++ b/static/app/components/events/eventEntries.tsx @@ -24,6 +24,7 @@ import RRWebIntegration from 'sentry/components/events/rrwebIntegration'; import EventSdkUpdates from 'sentry/components/events/sdkUpdates'; import {DataSection} from 'sentry/components/events/styles'; import EventUserFeedback from 'sentry/components/events/userFeedback'; +import LazyLoad from 'sentry/components/lazyLoad'; import ExternalLink from 'sentry/components/links/externalLink'; import {t, tct} from 'sentry/locale'; import space from 'sentry/styles/space'; @@ -100,6 +101,7 @@ const EventEntries = memo( const orgFeatures = organization?.features ?? []; const hasEventAttachmentsFeature = orgFeatures.includes('event-attachments'); + const replayId = event?.tags?.find(({key}) => key === 'replayId')?.value; useEffect(() => { checkProGuardError(); @@ -431,7 +433,7 @@ const EventEntries = memo( showGroupingConfig={orgFeatures.includes('set-grouping-config')} /> )} - {!isShare && hasEventAttachmentsFeature && ( + {!isShare && !replayId && hasEventAttachmentsFeature && ( <RRWebIntegration event={event} orgId={orgSlug} @@ -443,6 +445,14 @@ const EventEntries = memo( )} /> )} + {!isShare && replayId && orgFeatures.includes('session-replay') && ( + <LazyLoad + component={() => import('./eventReplay')} + replayId={replayId} + orgSlug={orgSlug} + projectSlug={projectSlug} + /> + )} </div> ); } diff --git a/static/app/components/events/eventReplay.tsx b/static/app/components/events/eventReplay.tsx new file mode 100644 index 0000000000000..3e7cf0ef00231 --- /dev/null +++ b/static/app/components/events/eventReplay.tsx @@ -0,0 +1,54 @@ +import styled from '@emotion/styled'; + +import EventDataSection from 'sentry/components/events/eventDataSection'; +import Link from 'sentry/components/links/link'; +import Placeholder from 'sentry/components/placeholder'; +import {Provider as ReplayContextProvider} from 'sentry/components/replays/replayContext'; +import ReplayView from 'sentry/components/replays/replayView'; +import {t} from 'sentry/locale'; +import space from 'sentry/styles/space'; +import useFullscreen from 'sentry/utils/replays/hooks/useFullscreen'; +import useReplayData from 'sentry/utils/replays/hooks/useReplayData'; + +type Props = { + orgSlug: string; + projectSlug: string; + replayId: string; +}; + +export default function EventReplay({replayId, orgSlug, projectSlug}: Props) { + const {fetching, replay} = useReplayData({ + eventSlug: `${projectSlug}:${replayId}`, + orgId: orgSlug, + }); + + const {ref: fullscreenRef, isFullscreen, toggle: toggleFullscreen} = useFullscreen(); + + return ( + <EventDataSection type="replay" title={t('Replay')}> + <Link to={`/organizations/${orgSlug}/replays/${projectSlug}:${replayId}`}> + {replayId} + </Link> + + <ReplayContextProvider replay={replay} initialTimeOffset={0}> + <PlayerContainer ref={fullscreenRef}> + {fetching ? ( + <Placeholder height="350px" width="100%" /> + ) : ( + replay && ( + <ReplayView + toggleFullscreen={toggleFullscreen} + isFullscreen={isFullscreen} + /> + ) + )} + </PlayerContainer> + </ReplayContextProvider> + </EventDataSection> + ); +} + +const PlayerContainer = styled('div')` + max-width: 420px; + margin-top: ${space(2)}; +`;
### Changes - Adds EventReplay component that contains the new Replay section - Adds ReplayView to add the replay player for the EventReplay section ### Notes The options dropdown bug strikes again but this time not in full-screen mode. When I click the option button on the player in this view it triggers a scroll and therefore never opens the menu. There isn't a mock or detail so I just added the player to the section with a max-width defined. Please feel free to let me know if there's something else that can be added or improved. The player works here as well without any changes or additional data fetching added. ![Screen Shot 2022-07-19 at 3 32 55 PM](https://user-images.githubusercontent.com/3721977/179833476-1d93012d-3eb4-4903-8faf-8e32dad171af.png) Closes #36589 ### Legal Boilerplate Look, I get it. The entity doing business as "Sentry" was incorporated in the State of Delaware in 2015 as Functional Software, Inc. and is gonna need some rights from me in order to utilize my contributions in this here PR. So here's the deal: I retain all rights, title and interest in and to my contributions, and by keeping this boilerplate intact I confirm that Sentry can use, modify, copy, and redistribute my contributions, under Sentry's choice of terms.
https://api.github.com/repos/getsentry/sentry/pulls/36818
2022-07-19T19:33:23Z
2022-07-22T17:13:56Z
2022-07-22T17:13:56Z
2023-03-16T16:16:45Z
972
getsentry/sentry
44,753
Fix typos
diff --git a/docs/templates/applications.md b/docs/templates/applications.md index 70b545d0da1..1333ae69655 100644 --- a/docs/templates/applications.md +++ b/docs/templates/applications.md @@ -253,7 +253,7 @@ The default input size for this model is 224x224. - input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) - or `(3, 224, 244)` (with `channels_first` data format). + or `(3, 224, 224)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 48. E.g. `(200, 200, 3)` would be one valid value. @@ -309,7 +309,7 @@ The default input size for this model is 224x224. - input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) - or `(3, 224, 244)` (with `channels_first` data format). + or `(3, 224, 224)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 48. E.g. `(200, 200, 3)` would be one valid value. @@ -367,7 +367,7 @@ The default input size for this model is 224x224. - input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) - or `(3, 224, 244)` (with `channels_first` data format). + or `(3, 224, 224)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 197. E.g. `(200, 200, 3)` would be one valid value. diff --git a/keras/applications/vgg16.py b/keras/applications/vgg16.py index 5ad7769d45b..7a1e6a05450 100644 --- a/keras/applications/vgg16.py +++ b/keras/applications/vgg16.py @@ -59,7 +59,7 @@ def VGG16(include_top=True, weights='imagenet', input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) - or `(3, 224, 244)` (with `channels_first` data format). + or `(3, 224, 224)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 48. E.g. `(200, 200, 3)` would be one valid value. diff --git a/keras/applications/vgg19.py b/keras/applications/vgg19.py index b6f97484563..38b925d7905 100644 --- a/keras/applications/vgg19.py +++ b/keras/applications/vgg19.py @@ -59,7 +59,7 @@ def VGG19(include_top=True, weights='imagenet', input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) - or `(3, 224, 244)` (with `channels_first` data format). + or `(3, 224, 224)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 48. E.g. `(200, 200, 3)` would be one valid value.
https://api.github.com/repos/keras-team/keras/pulls/6702
2017-05-21T08:30:56Z
2017-05-21T17:51:20Z
2017-05-21T17:51:20Z
2017-06-17T09:06:56Z
968
keras-team/keras
46,979
🌐 Add Chinese translation for Advanced User Guide - Intro
diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md new file mode 100644 index 0000000000000..d71838cd77e8d --- /dev/null +++ b/docs/zh/docs/advanced/index.md @@ -0,0 +1,18 @@ +# 高级用户指南 - 简介 + +## 额外特性 + +主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。 + +你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 + +!!! tip + 接下来的章节**并不一定是**「高级的」。 + + 而且对于你的使用场景来说,解决方案很可能就在其中。 + +## 先阅读教程 + +你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 中的大多数特性。 + +接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/){.internal-link target=_blank},并且假设你已经知晓其中主要思想。 diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index 42f6310c76570..3303ab6df977a 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -60,6 +60,8 @@ nav: - tutorial/path-params-numeric-validations.md - tutorial/body-multiple-params.md - tutorial/body-fields.md +- 高级用户指南: + - advanced/index.md - deployment.md - contributing.md - help-fastapi.md
Add Chinese translations for `advance/index.md`
https://api.github.com/repos/tiangolo/fastapi/pulls/1445
2020-05-21T03:29:01Z
2020-11-25T17:07:18Z
2020-11-25T17:07:18Z
2020-11-25T17:07:57Z
427
tiangolo/fastapi
23,326
fix pre output
diff --git a/CHANGELOG.md b/CHANGELOG.md index d9ce709eb..5d527500d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Reversed `pre` and `code` tags in base HTML format https://github.com/Textualize/rich/pull/2642 - Fix syntax error when building with nuitka https://github.com/Textualize/rich/pull/2635 - Fixed pretty printing of empty dataclass https://github.com/Textualize/rich/issues/2819 +- Fixes superfluous spaces in html output https://github.com/Textualize/rich/issues/2832 ### Added diff --git a/rich/_export_format.py b/rich/_export_format.py index ea4020904..094d2dc22 100644 --- a/rich/_export_format.py +++ b/rich/_export_format.py @@ -12,9 +12,7 @@ </head> <html> <body> - <pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"> - <code>{code}</code> - </pre> + <pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><code>{code}</code></pre> </body> </html> """ diff --git a/tests/test_console.py b/tests/test_console.py index 8c72e8da0..227752158 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -528,7 +528,8 @@ def test_export_html(): console = Console(record=True, width=100) console.print("[b]foo <script> 'test' [link=https://example.org]Click[/link]") html = console.export_html() - expected = '<!DOCTYPE html>\n<head>\n<meta charset="UTF-8">\n<style>\n.r1 {font-weight: bold}\n.r2 {color: #ff00ff; text-decoration-color: #ff00ff; font-weight: bold}\n.r3 {color: #008000; text-decoration-color: #008000; font-weight: bold}\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace">\n <code><span class="r1">foo &lt;</span><span class="r2">script</span><span class="r1">&gt; </span><span class="r3">&#x27;test&#x27;</span><span class="r1"> </span><a class="r1" href="https://example.org">Click</a>\n</code>\n </pre>\n</body>\n</html>\n' + print(repr(html)) + expected = '<!DOCTYPE html>\n<head>\n<meta charset="UTF-8">\n<style>\n.r1 {font-weight: bold}\n.r2 {color: #ff00ff; text-decoration-color: #ff00ff; font-weight: bold}\n.r3 {color: #008000; text-decoration-color: #008000; font-weight: bold}\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code><span class="r1">foo &lt;</span><span class="r2">script</span><span class="r1">&gt; </span><span class="r3">&#x27;test&#x27;</span><span class="r1"> </span><a class="r1" href="https://example.org">Click</a>\n</code></pre>\n</body>\n</html>\n' assert html == expected @@ -536,7 +537,8 @@ def test_export_html_inline(): console = Console(record=True, width=100) console.print("[b]foo [link=https://example.org]Click[/link]") html = console.export_html(inline_styles=True) - expected = '<!DOCTYPE html>\n<head>\n<meta charset="UTF-8">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace">\n <code><span style="font-weight: bold">foo </span><span style="font-weight: bold"><a href="https://example.org">Click</a></span>\n</code>\n </pre>\n</body>\n</html>\n' + print(repr(html)) + expected = '<!DOCTYPE html>\n<head>\n<meta charset="UTF-8">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code><span style="font-weight: bold">foo </span><span style="font-weight: bold"><a href="https://example.org">Click</a></span>\n</code></pre>\n</body>\n</html>\n' assert html == expected @@ -589,14 +591,16 @@ def test_save_text(): def test_save_html(): - expected = "<!DOCTYPE html>\n<head>\n<meta charset=\"UTF-8\">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style=\"font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n <code>foo\n</code>\n </pre>\n</body>\n</html>\n" + expected = "<!DOCTYPE html>\n<head>\n<meta charset=\"UTF-8\">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n <pre style=\"font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><code>foo\n</code></pre>\n</body>\n</html>\n" console = Console(record=True, width=100) console.print("foo") with tempfile.TemporaryDirectory() as path: export_path = os.path.join(path, "example.html") console.save_html(export_path) with open(export_path, "rt") as html_file: - assert html_file.read() == expected + html = html_file.read() + print(repr(html)) + assert html == expected def test_no_wrap():
Fixes https://github.com/Textualize/rich/issues/2832
https://api.github.com/repos/Textualize/rich/pulls/2844
2023-03-04T10:00:01Z
2023-03-04T10:13:43Z
2023-03-04T10:13:43Z
2023-03-04T10:13:44Z
1,627
Textualize/rich
48,243
Fix inference MP group initialization at consequent inference calls
diff --git a/deepspeed/inference/engine.py b/deepspeed/inference/engine.py index 8ea3d5619bba..67b656219978 100644 --- a/deepspeed/inference/engine.py +++ b/deepspeed/inference/engine.py @@ -17,6 +17,8 @@ class InferenceEngine(Module): + inference_mp_group = None + def __init__(self, model, mp_size=1, @@ -57,7 +59,7 @@ def __init__(self, self.mp_world_size = dist.get_world_size( group=self.mpu.get_model_parallel_group()) self.mp_group = self.mpu.get_model_parallel_group() - elif self.mp_world_size > 1 and not dist.is_initialized(): + elif self.mp_world_size > 1: self._create_model_parallel_group() # apply injection policy @@ -87,14 +89,17 @@ def _get_model_config_generate(self): def _create_model_parallel_group(self): # Call the init process + if InferenceEngine.inference_mp_group is None: + init_distributed() - init_distributed() - - local_rank = int(os.getenv('LOCAL_RANK', '0')) - torch.cuda.set_device(local_rank) + local_rank = int(os.getenv('LOCAL_RANK', '0')) + torch.cuda.set_device(local_rank) - ranks = [i for i in range(self.mp_world_size)] - self.mp_group = dist.new_group(ranks) + ranks = [i for i in range(self.mp_world_size)] + self.mp_group = dist.new_group(ranks) + InferenceEngine.inference_mp_group = self.mp_group + else: + self.mp_group = InferenceEngine.inference_mp_group def _check_quantize_setting(self, quantization_setting): self.quatize_bits = 8
This PR addresses https://github.com/microsoft/DeepSpeed/issues/1410
https://api.github.com/repos/microsoft/DeepSpeed/pulls/1411
2021-09-28T07:32:09Z
2021-09-30T21:59:14Z
2021-09-30T21:59:14Z
2021-09-30T21:59:14Z
415
microsoft/DeepSpeed
10,783
Docs: fix link and missing package
diff --git a/docs/docs/integrations/chat/maritalk.ipynb b/docs/docs/integrations/chat/maritalk.ipynb index 82e9b75dbc8eb0..bd2a04700f8e2c 100644 --- a/docs/docs/integrations/chat/maritalk.ipynb +++ b/docs/docs/integrations/chat/maritalk.ipynb @@ -4,13 +4,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "<a href=\"https://colab.research.google.com/github/langchain-ai/langchain/docs/docs/integrations/chat/maritalk.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", + "<a href=\"https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/integrations/chat/maritalk.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n", "\n", "# Maritalk\n", "\n", "## Introduction\n", "\n", - "MariTalk is an assistant developed by the Brazilian company [Maritaca AI](www.maritaca.ai).\n", + "MariTalk is an assistant developed by the Brazilian company [Maritaca AI](https://www.maritaca.ai).\n", "MariTalk is based on language models that have been specially trained to understand Portuguese well.\n", "\n", "This notebook demonstrates how to use MariTalk with LangChain through two examples:\n", @@ -33,7 +33,7 @@ "metadata": {}, "outputs": [], "source": [ - "!pip install langchain-core langchain-community" + "!pip install langchain langchain-core langchain-community" ] }, {
**Issue:** fix broken links and missing package on colab example
https://api.github.com/repos/langchain-ai/langchain/pulls/18405
2024-03-01T22:01:21Z
2024-03-05T23:50:06Z
2024-03-05T23:50:06Z
2024-03-15T09:58:46Z
443
langchain-ai/langchain
42,940
add Dog Facts
diff --git a/README.md b/README.md index 9ca12e6b80..ad116fb4bc 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ API | Description | Auth | HTTPS | CORS | | [catAPI](https://thatcopy.pw/catapi) | Random pictures of cats | No | Yes | Yes | | [Cats](https://docs.thecatapi.com/) | Pictures of cats from Tumblr | `apiKey` | Yes | No | | [Dog Facts](https://dukengn.github.io/Dog-facts-API/) | Random dog facts | No | Yes | Yes | +| [Dog Facts](https://kinduff.github.io/dog-api/) | Random facts of Dogs | No | Yes | Yes | | [Dogs](https://dog.ceo/dog-api/) | Based on the Stanford Dogs Dataset | No | Yes | Yes | | [Elephants](https://elephant-api.herokuapp.com/) | A free API to feature awesome elephants in your next project | No | Yes | Yes | | [HTTPCat](https://http.cat/) | Cat for every HTTP Status | No | Yes | Yes |
<!-- 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: --> - [x] My submission is formatted according to the guidelines in the [contributing guide](/CONTRIBUTING.md) - [x] My addition is ordered alphabetically - [x] My submission has a useful description - [x] The description does not have more than 100 characters - [x] The description does not end with punctuation - [x] Each table column is padded with one space on either side - [x] I have searched the repository for any relevant issues or pull requests - [x] Any category I am creating has the minimum requirement of 3 items - [x] All changes have been [squashed][squash-link] into a single commit [squash-link]: <https://github.com/todotxt/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit>
https://api.github.com/repos/public-apis/public-apis/pulls/2622
2021-10-20T04:51:41Z
2021-10-27T13:56:23Z
2021-10-27T13:56:23Z
2021-10-27T13:56:23Z
259
public-apis/public-apis
35,879
⬆ [pre-commit.ci] pre-commit autoupdate
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c4c1d4d9e8787..978114a65194c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,14 +12,14 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade - rev: v2.37.3 + rev: v3.1.0 hooks: - id: pyupgrade args: - --py3-plus - --keep-runtime-typing -- repo: https://github.com/myint/autoflake - rev: v1.5.3 +- repo: https://github.com/PyCQA/autoflake + rev: v1.7.6 hooks: - id: autoflake args: @@ -43,7 +43,7 @@ repos: name: isort (pyi) types: [pyi] - repo: https://github.com/psf/black - rev: 22.8.0 + rev: 22.10.0 hooks: - id: black ci:
<!--pre-commit.ci start--> updates: - [github.com/asottile/pyupgrade: v2.37.3 → v3.1.0](https://github.com/asottile/pyupgrade/compare/v2.37.3...v3.1.0) - https://github.com/myint/autoflake → https://github.com/PyCQA/autoflake - [github.com/PyCQA/autoflake: v1.5.3 → v1.7.6](https://github.com/PyCQA/autoflake/compare/v1.5.3...v1.7.6) - [github.com/psf/black: 22.8.0 → 22.10.0](https://github.com/psf/black/compare/22.8.0...22.10.0) <!--pre-commit.ci end-->
https://api.github.com/repos/tiangolo/fastapi/pulls/5408
2022-09-19T21:17:12Z
2022-10-20T11:15:19Z
2022-10-20T11:15:19Z
2022-10-20T11:15:20Z
297
tiangolo/fastapi
23,059
fix(monitors): Remove monitor context when appropriate
diff --git a/src/sentry/utils/monitors.py b/src/sentry/utils/monitors.py index df8b48cd2be3c..5dab770b20951 100644 --- a/src/sentry/utils/monitors.py +++ b/src/sentry/utils/monitors.py @@ -59,16 +59,19 @@ def inner(*a, **k): @suppress_errors def report_monitor_begin(task, **kwargs): + monitor_id = task.request.headers.get('X-Sentry-Monitor') + with configure_scope() as scope: + if monitor_id: + scope.set_context('monitor', {'id': monitor_id}) + else: + scope.remove_context('monitor') + if not SENTRY_DSN or not API_ROOT: return - monitor_id = task.request.headers.get('X-Sentry-Monitor') if not monitor_id: return - with configure_scope() as scope: - scope.set_context('monitor', {'id': monitor_id}) - session = SafeSession() req = session.post(u'{}/api/0/monitors/{}/checkins/'.format(API_ROOT, monitor_id), headers={ 'Authorization': u'DSN {}'.format(SENTRY_DSN) @@ -82,6 +85,9 @@ def report_monitor_begin(task, **kwargs): @suppress_errors def report_monitor_complete(task, retval, **kwargs): + with configure_scope() as scope: + scope.remove_context('monitor') + if not SENTRY_DSN or not API_ROOT: return
https://api.github.com/repos/getsentry/sentry/pulls/11869
2019-02-03T23:35:30Z
2019-02-04T16:26:56Z
2019-02-04T16:26:56Z
2020-12-20T20:38:59Z
337
getsentry/sentry
44,264
[GorillaVid] Added GorillaVid extractor
diff --git a/youtube_dl/extractor/__init__.py b/youtube_dl/extractor/__init__.py index 15a42ce4424..6c9a7593ae3 100644 --- a/youtube_dl/extractor/__init__.py +++ b/youtube_dl/extractor/__init__.py @@ -109,6 +109,7 @@ from .generic import GenericIE from .googleplus import GooglePlusIE from .googlesearch import GoogleSearchIE +from .gorillavid import GorillaVidIE from .hark import HarkIE from .helsinki import HelsinkiIE from .hentaistigma import HentaiStigmaIE diff --git a/youtube_dl/extractor/gorillavid.py b/youtube_dl/extractor/gorillavid.py new file mode 100644 index 00000000000..7e8b9f70629 --- /dev/null +++ b/youtube_dl/extractor/gorillavid.py @@ -0,0 +1,38 @@ +# coding: utf-8 +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor + +class GorillaVidIE(InfoExtractor): + _VALID_URL = r'https?://(?:www.)?gorillavid.in/(?:embed-)?(?P<id>\w+)(?:\-\d+x\d+)?(?:.html)?' + _TEST = { + 'url': "http://gorillavid.in/z08zf8le23c6", + 'md5': 'c9e293ca74d46cad638e199c3f3fe604', + 'info_dict': { + 'id': 'z08zf8le23c6', + 'ext': 'mp4', + 'title': 'Say something nice', + } + } + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + video_id = mobj.group('id') + + webpage = self._download_webpage(url, video_id) + title = self._html_search_regex(r"name=['\"]fname['\"]\s+value=['\"](.*?)['\"]", webpage, u"video title") + + # download embed page again with cookies to get url + embed_url = "http://gorillavid.in/embed-{0}-960x480.html".format(video_id) + webpage = self._download_webpage(embed_url, video_id, note=u'Downloading webpage again (with cookie)') + url = self._html_search_regex(r'file:\s+["\'](http://.*?video.\w{3})["\']', webpage, url) + + info_dict = { + 'id': video_id, + 'title': title, + 'url': url, + } + + return info_dict
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/3059
2014-06-08T02:16:59Z
2014-06-17T13:18:51Z
2014-06-17T13:18:51Z
2014-06-17T13:20:42Z
642
ytdl-org/youtube-dl
49,698
update centos9stream ami
diff --git a/letstest/targets/targets.yaml b/letstest/targets/targets.yaml index ed00d6e2b57..dbeb793f694 100644 --- a/letstest/targets/targets.yaml +++ b/letstest/targets/targets.yaml @@ -38,7 +38,7 @@ targets: type: centos virt: hvm user: centos - - ami: ami-0d5144f02e4eb6f05 + - ami: ami-08f2fe20b72b2ffa7 name: centos9stream type: centos virt: hvm
our "test farm tests" started failing with [this error](https://dev.azure.com/certbot/certbot/_build/results?buildId=7548&view=logs&j=9ad64ec1-64fe-5c1a-aa80-014a21728434&t=01dc0a99-87f2-5e74-d7b8-4950697fba7c&l=393). googling around i saw https://github.com/boto/boto3/issues/560#issuecomment-572666373 and checking the aws ami catalog, it appears this is the case here -- the ami we were using was deleted. to fix this, i updated to the ami to the current one. you can see tests passing with this change [here](https://dev.azure.com/certbot/certbot/_build/results?buildId=7550&view=results)
https://api.github.com/repos/certbot/certbot/pulls/9914
2024-03-20T00:12:27Z
2024-03-20T20:18:37Z
2024-03-20T20:18:37Z
2024-03-20T20:18:37Z
157
certbot/certbot
2,492
Use OpenAI for embeddings when openai mode is selected
diff --git a/private_gpt/components/embedding/embedding_component.py b/private_gpt/components/embedding/embedding_component.py index 41b4e1f43..61fe6fad1 100644 --- a/private_gpt/components/embedding/embedding_component.py +++ b/private_gpt/components/embedding/embedding_component.py @@ -13,14 +13,19 @@ class EmbeddingComponent: @inject def __init__(self) -> None: match settings.llm.mode: - case "mock": - # Not a random number, is the dimensionality used by - # the default embedding model - self.embedding_model = MockEmbedding(384) - case _: + case "local": from llama_index.embeddings import HuggingFaceEmbedding self.embedding_model = HuggingFaceEmbedding( model_name=settings.local.embedding_hf_model_name, cache_folder=str(models_cache_path), ) + case "openai": + from llama_index import OpenAIEmbedding + + openai_settings = settings.openai.api_key + self.embedding_model = OpenAIEmbedding(api_key=openai_settings) + case "mock": + # Not a random number, is the dimensionality used by + # the default embedding model + self.embedding_model = MockEmbedding(384)
At the moment, even if openai is selected as the execution mode, local Embeddings are being used. That blocks fully remote setups based on openai, as it uses HuggingFace torch-based embeddings. With this fix, openai is used both for the LLM and the embeddings when openai is selected in the .yaml llm->model configuration. Fixes #1093
https://api.github.com/repos/zylon-ai/private-gpt/pulls/1096
2023-10-23T07:54:26Z
2023-10-23T08:50:42Z
2023-10-23T08:50:42Z
2023-10-23T08:50:48Z
293
zylon-ai/private-gpt
38,607
DEPR: remove .ix from tests/indexing/multiindex/test_setitem.py
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 261d2e9c04e77..c383c38958692 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -1,5 +1,3 @@ -from warnings import catch_warnings, simplefilter - import numpy as np from numpy.random import randn import pytest @@ -10,133 +8,114 @@ from pandas.util import testing as tm -@pytest.mark.filterwarnings("ignore:\\n.ix:FutureWarning") class TestMultiIndexSetItem: def test_setitem_multiindex(self): - with catch_warnings(record=True): - - for index_fn in ("ix", "loc"): - - def assert_equal(a, b): - assert a == b - - def check(target, indexers, value, compare_fn, expected=None): - fn = getattr(target, index_fn) - fn.__setitem__(indexers, value) - result = fn.__getitem__(indexers) - if expected is None: - expected = value - compare_fn(result, expected) - - # GH7190 - index = MultiIndex.from_product( - [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"] - ) - t, n = 0, 2 - df = DataFrame( - np.nan, - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], - index=index, - ) - check( - target=df, indexers=((t, n), "X"), value=0, compare_fn=assert_equal - ) - - df = DataFrame( - -999, - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], - index=index, - ) - check( - target=df, indexers=((t, n), "X"), value=1, compare_fn=assert_equal - ) - - df = DataFrame( - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index - ) - check( - target=df, indexers=((t, n), "X"), value=2, compare_fn=assert_equal - ) - - # gh-7218: assigning with 0-dim arrays - df = DataFrame( - -999, - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], - index=index, - ) - check( - target=df, - indexers=((t, n), "X"), - value=np.array(3), - compare_fn=assert_equal, - expected=3, - ) - - # GH5206 - df = DataFrame( - np.arange(25).reshape(5, 5), - columns="A,B,C,D,E".split(","), - dtype=float, - ) - df["F"] = 99 - row_selection = df["A"] % 2 == 0 - col_selection = ["B", "C"] - with catch_warnings(record=True): - df.ix[row_selection, col_selection] = df["F"] - output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"]) - with catch_warnings(record=True): - tm.assert_frame_equal(df.ix[row_selection, col_selection], output) - check( - target=df, - indexers=(row_selection, col_selection), - value=df["F"], - compare_fn=tm.assert_frame_equal, - expected=output, - ) - - # GH11372 - idx = MultiIndex.from_product( - [["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")] - ) - cols = MultiIndex.from_product( - [["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")] - ) - - df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols) - - subidx = MultiIndex.from_tuples( - [("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))] - ) - subcols = MultiIndex.from_tuples( - [("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))] - ) - - vals = DataFrame( - np.random.random((2, 2)), index=subidx, columns=subcols - ) - check( - target=df, - indexers=(subidx, subcols), - value=vals, - compare_fn=tm.assert_frame_equal, - ) - # set all columns - vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols) - check( - target=df, - indexers=(subidx, slice(None, None, None)), - value=vals, - compare_fn=tm.assert_frame_equal, - ) - # identity - copy = df.copy() - check( - target=df, - indexers=(df.index, df.columns), - value=df, - compare_fn=tm.assert_frame_equal, - expected=copy, - ) + for index_fn in ("loc",): + + def assert_equal(a, b): + assert a == b + + def check(target, indexers, value, compare_fn, expected=None): + fn = getattr(target, index_fn) + fn.__setitem__(indexers, value) + result = fn.__getitem__(indexers) + if expected is None: + expected = value + compare_fn(result, expected) + + # GH7190 + index = MultiIndex.from_product( + [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"] + ) + t, n = 0, 2 + df = DataFrame( + np.nan, + columns=["A", "w", "l", "a", "x", "X", "d", "profit"], + index=index, + ) + check(target=df, indexers=((t, n), "X"), value=0, compare_fn=assert_equal) + + df = DataFrame( + -999, columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index + ) + check(target=df, indexers=((t, n), "X"), value=1, compare_fn=assert_equal) + + df = DataFrame( + columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index + ) + check(target=df, indexers=((t, n), "X"), value=2, compare_fn=assert_equal) + + # gh-7218: assigning with 0-dim arrays + df = DataFrame( + -999, columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index + ) + check( + target=df, + indexers=((t, n), "X"), + value=np.array(3), + compare_fn=assert_equal, + expected=3, + ) + + # GH5206 + df = DataFrame( + np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float + ) + df["F"] = 99 + row_selection = df["A"] % 2 == 0 + col_selection = ["B", "C"] + df.loc[row_selection, col_selection] = df["F"] + output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"]) + tm.assert_frame_equal(df.loc[row_selection, col_selection], output) + check( + target=df, + indexers=(row_selection, col_selection), + value=df["F"], + compare_fn=tm.assert_frame_equal, + expected=output, + ) + + # GH11372 + idx = MultiIndex.from_product( + [["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")] + ) + cols = MultiIndex.from_product( + [["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")] + ) + + df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols) + + subidx = MultiIndex.from_tuples( + [("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))] + ) + subcols = MultiIndex.from_tuples( + [("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))] + ) + + vals = DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols) + check( + target=df, + indexers=(subidx, subcols), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # set all columns + vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols) + check( + target=df, + indexers=(subidx, slice(None, None, None)), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # identity + copy = df.copy() + check( + target=df, + indexers=(df.index, df.columns), + value=df, + compare_fn=tm.assert_frame_equal, + expected=copy, + ) def test_multiindex_setitem(self): @@ -204,9 +183,8 @@ def test_multiindex_assignment(self): df["d"] = np.nan arr = np.array([0.0, 1.0]) - with catch_warnings(record=True): - df.ix[4, "d"] = arr - tm.assert_series_equal(df.ix[4, "d"], Series(arr, index=[8, 10], name="d")) + df.loc[4, "d"] = arr + tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d")) # single dtype df = DataFrame( @@ -215,25 +193,21 @@ def test_multiindex_assignment(self): index=[[4, 4, 8], [8, 10, 12]], ) - with catch_warnings(record=True): - df.ix[4, "c"] = arr - exp = Series(arr, index=[8, 10], name="c", dtype="float64") - tm.assert_series_equal(df.ix[4, "c"], exp) + df.loc[4, "c"] = arr + exp = Series(arr, index=[8, 10], name="c", dtype="float64") + tm.assert_series_equal(df.loc[4, "c"], exp) # scalar ok - with catch_warnings(record=True): - df.ix[4, "c"] = 10 - exp = Series(10, index=[8, 10], name="c", dtype="float64") - tm.assert_series_equal(df.ix[4, "c"], exp) + df.loc[4, "c"] = 10 + exp = Series(10, index=[8, 10], name="c", dtype="float64") + tm.assert_series_equal(df.loc[4, "c"], exp) # invalid assignments with pytest.raises(ValueError): - with catch_warnings(record=True): - df.ix[4, "c"] = [0, 1, 2, 3] + df.loc[4, "c"] = [0, 1, 2, 3] with pytest.raises(ValueError): - with catch_warnings(record=True): - df.ix[4, "c"] = [0] + df.loc[4, "c"] = [0] # groupby example NUM_ROWS = 100 @@ -264,8 +238,7 @@ def f(name, df2): # but in this case, that's ok for name, df2 in grp: new_vals = np.arange(df2.shape[0]) - with catch_warnings(record=True): - df.ix[name, "new_col"] = new_vals + df.loc[name, "new_col"] = new_vals def test_series_setitem(self, multiindex_year_month_day_dataframe_random_data): ymd = multiindex_year_month_day_dataframe_random_data @@ -313,11 +286,6 @@ def test_frame_getitem_setitem_multislice(self): result = df.loc[:, "value"] tm.assert_series_equal(df["value"], result) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[:, "value"] - tm.assert_series_equal(df["value"], result) - result = df.loc[df.index[1:3], "value"] tm.assert_series_equal(df["value"][1:3], result) @@ -412,7 +380,7 @@ def test_setitem_change_dtype(self, multiindex_dataframe_random_data): reindexed = dft.reindex(columns=[("foo", "two")]) tm.assert_series_equal(reindexed["foo", "two"], s > s.median()) - def test_set_column_scalar_with_ix(self, multiindex_dataframe_random_data): + def test_set_column_scalar_with_loc(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data subset = frame.index[[1, 4, 5]]
https://api.github.com/repos/pandas-dev/pandas/pulls/27574
2019-07-24T18:59:43Z
2019-07-25T16:56:28Z
2019-07-25T16:56:28Z
2019-07-26T03:06:20Z
3,216
pandas-dev/pandas
45,276
Updated for Onyx platform for distributed processing.
diff --git a/README.md b/README.md index 93149fe1..4729bf7d 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,7 @@ For a list of free-to-attend meetups and local events, go [here](https://github. * [Flink](http://flink.apache.org/) - Open source platform for distributed stream and batch data processing. * [Hadoop](https://github.com/apache/hadoop-mapreduce) - Hadoop/HDFS +* [Onyx](https://github.com/onyx-platform/onyx) - Distributed, masterless, high performance, fault tolerant data processing. Written entirely in Clojure. * [Spark](https://github.com/apache/spark) - Spark is a fast and general engine for large-scale data processing. * [Storm](http://storm.apache.org/) - Storm is a distributed realtime computation system. * [Impala](https://github.com/cloudera/impala) - Real-time Query for Hadoop
Hi :) I saw that the Onyx platform is missing out in the list.
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/406
2017-07-31T02:52:55Z
2017-08-01T14:25:54Z
2017-08-01T14:25:54Z
2017-08-01T14:25:57Z
226
josephmisiti/awesome-machine-learning
52,034
Set up 2.0 pre-releases
diff --git a/.azure-pipelines/2.0-prerelease.yml b/.azure-pipelines/2.0-prerelease.yml new file mode 100644 index 00000000000..2cdcf8f3035 --- /dev/null +++ b/.azure-pipelines/2.0-prerelease.yml @@ -0,0 +1,18 @@ +# Pipeline for testing, building, and deploying Certbot 2.0 pre-releases. +trigger: none +pr: none + +variables: + # We don't publish our Docker images in this pipeline, but when building them + # for testing, let's use the nightly tag. + dockerTag: nightly + snapBuildTimeout: 5400 + +stages: + - template: templates/stages/test-and-package-stage.yml + - stage: DeploySnaps + jobs: + - template: templates/jobs/snap-deploy-job.yml + parameters: + snapReleaseChannel: beta + - template: templates/stages/notify-failure-stage.yml diff --git a/.azure-pipelines/release.yml b/.azure-pipelines/release.yml index 26639151f95..9169dc950f9 100644 --- a/.azure-pipelines/release.yml +++ b/.azure-pipelines/release.yml @@ -15,5 +15,5 @@ stages: - template: templates/stages/changelog-stage.yml - template: templates/stages/deploy-stage.yml parameters: - snapReleaseChannel: beta + snapReleaseChannel: candidate - template: templates/stages/notify-failure-stage.yml diff --git a/.azure-pipelines/templates/jobs/snap-deploy-job.yml b/.azure-pipelines/templates/jobs/snap-deploy-job.yml new file mode 100644 index 00000000000..d1d709cb99d --- /dev/null +++ b/.azure-pipelines/templates/jobs/snap-deploy-job.yml @@ -0,0 +1,75 @@ +# As (somewhat) described at +# https://docs.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#context, +# each template only has access to the parameters passed into it. To help make +# use of this design, we define snapReleaseChannel without a default value +# which requires the user of this template to define it as described at +# https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/parameters-name?view=azure-pipelines#remarks. +# This makes the user of this template be explicit while allowing them to +# define their own parameters with defaults that make sense for that context. +parameters: +- name: snapReleaseChannel + type: string + values: + - edge + - beta + - candidate + +jobs: + # This job relies on credentials used to publish the Certbot snaps. This + # credential file was created by running: + # + # snapcraft logout + # snapcraft export-login --channels=candidate,beta,edge snapcraft.cfg + # (provide the shared snapcraft credentials when prompted) + # + # Then the file was added as a secure file in Azure pipelines + # with the name snapcraft.cfg by following the instructions at + # https://docs.microsoft.com/en-us/azure/devops/pipelines/library/secure-files?view=azure-devops + # including authorizing the file for use in the "nightly" and "release" + # pipelines as described at + # https://docs.microsoft.com/en-us/azure/devops/pipelines/library/secure-files?view=azure-devops#q-how-do-i-authorize-a-secure-file-for-use-in-a-specific-pipeline. + # + # This file has a maximum lifetime of one year and the current file will + # expire on 2023-09-06. The file will need to be updated before then to + # prevent automated deploys from breaking. + # + # Revoking these credentials can be done by changing the password of the + # account used to generate the credentials. See + # https://forum.snapcraft.io/t/revoking-exported-credentials/19031 for + # more info. + - job: publish_snap + pool: + vmImage: ubuntu-22.04 + variables: + - group: certbot-common + strategy: + matrix: + amd64: + SNAP_ARCH: amd64 + arm32v6: + SNAP_ARCH: armhf + arm64v8: + SNAP_ARCH: arm64 + steps: + - bash: | + set -e + sudo apt-get update + sudo apt-get install -y --no-install-recommends snapd + sudo snap install --classic snapcraft + displayName: Install dependencies + - task: DownloadPipelineArtifact@2 + inputs: + artifact: snaps_$(SNAP_ARCH) + path: $(Build.SourcesDirectory)/snap + displayName: Retrieve Certbot snaps + - task: DownloadSecureFile@1 + name: snapcraftCfg + inputs: + secureFile: snapcraft.cfg + - bash: | + set -e + export SNAPCRAFT_STORE_CREDENTIALS=$(cat "$(snapcraftCfg.secureFilePath)") + for SNAP_FILE in snap/*.snap; do + tools/retry.sh eval snapcraft upload --release=${{ parameters.snapReleaseChannel }} "${SNAP_FILE}" + done + displayName: Publish to Snap store diff --git a/.azure-pipelines/templates/stages/deploy-stage.yml b/.azure-pipelines/templates/stages/deploy-stage.yml index 8144f4beeb1..cb8b24e2846 100644 --- a/.azure-pipelines/templates/stages/deploy-stage.yml +++ b/.azure-pipelines/templates/stages/deploy-stage.yml @@ -1,74 +1,16 @@ parameters: +# We do not define acceptable values for this parameter here as it is passed +# through to ../jobs/snap-deploy-job.yml which does its own sanity checking. - name: snapReleaseChannel type: string default: edge - values: - - edge - - beta stages: - stage: Deploy jobs: - # This job relies on credentials used to publish the Certbot snaps. This - # credential file was created by running: - # - # snapcraft logout - # snapcraft export-login --channels=beta,edge snapcraft.cfg - # (provide the shared snapcraft credentials when prompted) - # - # Then the file was added as a secure file in Azure pipelines - # with the name snapcraft.cfg by following the instructions at - # https://docs.microsoft.com/en-us/azure/devops/pipelines/library/secure-files?view=azure-devops - # including authorizing the file for use in the "nightly" and "release" - # pipelines as described at - # https://docs.microsoft.com/en-us/azure/devops/pipelines/library/secure-files?view=azure-devops#q-how-do-i-authorize-a-secure-file-for-use-in-a-specific-pipeline. - # - # This file has a maximum lifetime of one year and the current - # file will expire on 2023-06-17 which is also tracked by - # https://github.com/certbot/certbot/issues/7931. The file will - # need to be updated before then to prevent automated deploys - # from breaking. - # - # Revoking these credentials can be done by changing the password of the - # account used to generate the credentials. See - # https://forum.snapcraft.io/t/revoking-exported-credentials/19031 for - # more info. - - job: publish_snap - pool: - vmImage: ubuntu-22.04 - variables: - - group: certbot-common - strategy: - matrix: - amd64: - SNAP_ARCH: amd64 - arm32v6: - SNAP_ARCH: armhf - arm64v8: - SNAP_ARCH: arm64 - steps: - - bash: | - set -e - sudo apt-get update - sudo apt-get install -y --no-install-recommends snapd - sudo snap install --classic snapcraft - displayName: Install dependencies - - task: DownloadPipelineArtifact@2 - inputs: - artifact: snaps_$(SNAP_ARCH) - path: $(Build.SourcesDirectory)/snap - displayName: Retrieve Certbot snaps - - task: DownloadSecureFile@1 - name: snapcraftCfg - inputs: - secureFile: snapcraft.cfg - - bash: | - set -e - export SNAPCRAFT_STORE_CREDENTIALS=$(cat $(snapcraftCfg.secureFilePath)) - for SNAP_FILE in snap/*.snap; do - tools/retry.sh eval snapcraft upload --release=${{ parameters.snapReleaseChannel }} "${SNAP_FILE}" - done - displayName: Publish to Snap store + - template: ../jobs/snap-deploy-job.yml + parameters: + snapReleaseChannel: ${{ parameters.snapReleaseChannel }} - job: publish_docker pool: vmImage: ubuntu-22.04 diff --git a/tools/finish_release.py b/tools/finish_release.py index ec749d48f6a..18aa8ee30ee 100755 --- a/tools/finish_release.py +++ b/tools/finish_release.py @@ -4,7 +4,7 @@ This currently includes: -* Moving snaps from the beta channel to the stable channel +* Moving snaps from the candidate channel to the stable channel * Publishing the Windows installer in a GitHub release Setup: @@ -110,7 +110,7 @@ def assert_logged_into_snapcraft(): def get_snap_revisions(snap, version): - """Finds the revisions for the snap and version in the beta channel. + """Finds the revisions for the snap and version in the candidate channel. If you call this function without being logged in with snapcraft, it will hang with no output. @@ -130,20 +130,20 @@ def get_snap_revisions(snap, version): print('Getting revision numbers for', snap, version) cmd = ['snapcraft', 'status', snap] process = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, universal_newlines=True) - pattern = f'^\s+beta\s+{version}\s+(\d+)\s*' + pattern = f'^\s+candidate\s+{version}\s+(\d+)\s*' revisions = re.findall(pattern, process.stdout, re.MULTILINE) assert len(revisions) == SNAP_ARCH_COUNT, f'Unexpected number of snaps found for {snap} {version} (expected {SNAP_ARCH_COUNT}, found {len(revisions)})' return revisions def promote_snaps(version): - """Promotes all Certbot snaps from the beta to stable channel. + """Promotes all Certbot snaps from the candidate to stable channel. If the snaps have already been released to the stable channel, this function will try to release them again which has no effect. :param str version: the version number that should be found in the - beta channel, e.g. 1.7.0 + candidate channel, e.g. 1.7.0 :raises SystemExit: if the command snapcraft is unavailable or it isn't logged into an account
This implements the majority of https://docs.google.com/document/d/1t02y0qQvTgc4eNPY4OwfYu7oW41DEBNhr8fq_O97kXo/edit?usp=sharing. The work that remains after this is merged into master is merging this into the 2.0 branch, setting up the 2.0-prerelease pipeline for the 2.0 branch, writing documentation on how to use that pipeline, doing a prerelease, and writing a post on the community forum. One change I made in this PR that's not easily seen/understandable is I removed the reference to https://github.com/certbot/certbot/issues/7931 for the reason I wrote at https://github.com/certbot/certbot/issues/7931#issuecomment-1238650122. I also set up a dummy 2.0 prerelease pipeline to test this at https://dev.azure.com/certbot/certbot/_build?definitionId=6&_a=summary which seems to be working properly.
https://api.github.com/repos/certbot/certbot/pulls/9400
2022-09-07T21:49:30Z
2022-09-09T21:23:39Z
2022-09-09T21:23:39Z
2022-09-09T21:23:40Z
2,614
certbot/certbot
1,123
Bump cryptography from 1.7 to 3.2
diff --git a/requirements_dev.txt b/requirements_dev.txt index ff7da8df9..f39b3d2a2 100644 --- a/requirements_dev.txt +++ b/requirements_dev.txt @@ -6,7 +6,7 @@ flake8 tox==2.3.1 coverage==4.1 Sphinx==1.4.8 -cryptography==1.7 +cryptography==3.2 pyyaml>=4.2b1 face_recognition_models Click>=6.0
Bumps [cryptography](https://github.com/pyca/cryptography) from 1.7 to 3.2. <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/pyca/cryptography/blob/master/CHANGELOG.rst">cryptography's changelog</a>.</em></p> <blockquote> <p>3.2 - 2020-10-25</p> <pre><code> * **SECURITY ISSUE:** Attempted to make RSA PKCS#1v1.5 decryption more constant time, to protect against Bleichenbacher vulnerabilities. Due to limitations imposed by our API, we cannot completely mitigate this vulnerability and a future release will contain a new API which is designed to be resilient to these for contexts where it is required. Credit to **Hubert Kario** for reporting the issue. *CVE-2020-25659* * Support for OpenSSL 1.0.2 has been removed. Users on older version of OpenSSL will need to upgrade. * Added basic support for PKCS7 signing (including SMIME) via :class:`~cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder`. <p>.. _v3-1-1:</p> <p>3.1.1 - 2020-09-22 </code></pre></p> <ul> <li>Updated Windows, macOS, and <code>manylinux</code> wheels to be compiled with OpenSSL 1.1.1h.</li> </ul> <p>.. _v3-1:</p> <p>3.1 - 2020-08-26</p> <pre><code> * **BACKWARDS INCOMPATIBLE:** Removed support for ``idna`` based :term:`U-label` parsing in various X.509 classes. This support was originally deprecated in version 2.1 and moved to an extra in 2.5. * Deprecated OpenSSL 1.0.2 support. OpenSSL 1.0.2 is no longer supported by the OpenSSL project. The next version of ``cryptography`` will drop support for it. * Deprecated support for Python 3.5. This version sees very little use and will be removed in the next release. * ``backend`` arguments to functions are no longer required and the default backend will automatically be selected if no ``backend`` is provided. * Added initial support for parsing certificates from PKCS7 files with :func:`~cryptography.hazmat.primitives.serialization.pkcs7.load_pem_pkcs7_certificates` and :func:`~cryptography.hazmat.primitives.serialization.pkcs7.load_der_pkcs7_certificates` . * Calling ``update`` or ``update_into`` on :class:`~cryptography.hazmat.primitives.ciphers.CipherContext` with ``data`` longer than 2\ :sup:`31` bytes no longer raises an ``OverflowError``. This also resolves the same issue in :doc:`/fernet`. <p>.. _v3-0:</p> <p>3.0 - 2020-07-20 &lt;/tr&gt;&lt;/table&gt; </code></pre></p> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/pyca/cryptography/commit/c9e65222c91df8b6f61650a3460e30232962c1e0"><code>c9e6522</code></a> 3.2 release (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5508">#5508</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/58494b41d6ecb0f56b7c5f05d5f5e3ca0320d494"><code>58494b4</code></a> Attempt to mitigate Bleichenbacher attacks on RSA decryption (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5507">#5507</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/cf9bd6a36bc7b05abca114b76e216598d9ad9b16"><code>cf9bd6a</code></a> move blinding to <strong>init</strong> on both RSA public and private (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5506">#5506</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/bf4b962f4b92a1633835b2d17974f18de2d61620"><code>bf4b962</code></a> be more verbose in the 102 deprecation notice (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5505">#5505</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/ada53e7ca0f04a33711c330a130d34376e5ecc2b"><code>ada53e7</code></a> make the regexes for branches more strict (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5504">#5504</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/8be1d4b1113eabea306dd60ab64e7f00815d6a52"><code>8be1d4b</code></a> Stop using <a href="https://github.com/master">@master</a> for GH actions (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5503">#5503</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/08a97cca715ca0842d6792d0079e351efbb48ec9"><code>08a97cc</code></a> Bump actions/upload-artifact from v1 to v2.2.0 (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5502">#5502</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/52a0e44e97dd6e150509b14c9b1f76a261f12786"><code>52a0e44</code></a> Add a dependabot configuration to bump our github actions (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5501">#5501</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/611c4a340f6c53a7e28a9695a3248bd4e9f8558d"><code>611c4a3</code></a> PKCS7SignatureBuilder now supports new option NoCerts when signing (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5500">#5500</a>)</li> <li><a href="https://github.com/pyca/cryptography/commit/836a92a28fbe9df8c37121e340b91ed9cd519ddd"><code>836a92a</code></a> chunking didn't actually work (<a href="https://github-redirect.dependabot.com/pyca/cryptography/issues/5499">#5499</a>)</li> <li>Additional commits viewable in <a href="https://github.com/pyca/cryptography/compare/1.7...3.2">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=cryptography&package-manager=pip&previous-version=1.7&new-version=3.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/configuring-github-dependabot-security-updates) 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 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) - `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language - `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language - `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language - `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/ageitgey/face_recognition/network/alerts). </details>
https://api.github.com/repos/ageitgey/face_recognition/pulls/1236
2020-10-27T21:07:21Z
2021-06-14T10:07:49Z
2021-06-14T10:07:49Z
2021-06-14T10:08:01Z
119
ageitgey/face_recognition
22,594
Example of pad_to_multiple_of for padding and truncation guide & docstring update
diff --git a/docs/source/en/pad_truncation.mdx b/docs/source/en/pad_truncation.mdx index f848e23bed502..8862e0be008de 100644 --- a/docs/source/en/pad_truncation.mdx +++ b/docs/source/en/pad_truncation.mdx @@ -50,6 +50,7 @@ The following table summarizes the recommended way to setup padding and truncati | | | `tokenizer(batch_sentences, padding='longest')` | | | padding to max model input length | `tokenizer(batch_sentences, padding='max_length')` | | | padding to specific length | `tokenizer(batch_sentences, padding='max_length', max_length=42)` | +| | padding to a multiple of a value | `tokenizer(batch_sentences, padding=True, pad_to_multiple_of=8) | | truncation to max model input length | no padding | `tokenizer(batch_sentences, truncation=True)` or | | | | `tokenizer(batch_sentences, truncation=STRATEGY)` | | | padding to max sequence in batch | `tokenizer(batch_sentences, padding=True, truncation=True)` or | diff --git a/src/transformers/tokenization_utils_base.py b/src/transformers/tokenization_utils_base.py index eb52ef0adb28a..66164c27788c8 100644 --- a/src/transformers/tokenization_utils_base.py +++ b/src/transformers/tokenization_utils_base.py @@ -1342,8 +1342,9 @@ def all_special_ids(self) -> List[int]: tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification. pad_to_multiple_of (`int`, *optional*): - If set will pad the sequence to a multiple of the provided value. This is especially useful to enable - the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). + If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. + This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability + `>= 7.5` (Volta). return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are:
This PR adds a minor update to the docs as previously it was not clear that `pad_to_multiple_of` has to be used with `padding=True`. Based on https://huggingface.slack.com/archives/C027NLU6CE9/p1679325764920509
https://api.github.com/repos/huggingface/transformers/pulls/22278
2023-03-20T15:58:44Z
2023-03-20T18:18:55Z
2023-03-20T18:18:55Z
2023-11-03T15:31:11Z
544
huggingface/transformers
12,305
[NVIDIA] Add FP8 example using TE
diff --git a/examples/tutorial/fp8/mnist/README.md b/examples/tutorial/fp8/mnist/README.md new file mode 100644 index 000000000000..308549cd29f7 --- /dev/null +++ b/examples/tutorial/fp8/mnist/README.md @@ -0,0 +1,7 @@ +# Basic MNIST Example with optional FP8 + +```bash +python main.py +python main.py --use-te # Linear layers from TransformerEngine +python main.py --use-fp8 # FP8 + TransformerEngine for Linear layers +``` diff --git a/examples/tutorial/fp8/mnist/main.py b/examples/tutorial/fp8/mnist/main.py new file mode 100644 index 000000000000..000ded2f111f --- /dev/null +++ b/examples/tutorial/fp8/mnist/main.py @@ -0,0 +1,237 @@ +# Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +import argparse +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +from torchvision import datasets, transforms +from torch.optim.lr_scheduler import StepLR + +try: + from transformer_engine import pytorch as te + HAVE_TE = True +except (ImportError, ModuleNotFoundError): + HAVE_TE = False + + +class Net(nn.Module): + def __init__(self, use_te=False): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(1, 32, 3, 1) + self.conv2 = nn.Conv2d(32, 64, 3, 1) + self.dropout1 = nn.Dropout(0.25) + self.dropout2 = nn.Dropout(0.5) + if use_te: + self.fc1 = te.Linear(9216, 128) + self.fc2 = te.Linear(128, 16) + else: + self.fc1 = nn.Linear(9216, 128) + self.fc2 = nn.Linear(128, 16) + self.fc3 = nn.Linear(16, 10) + + def forward(self, x): + """FWD""" + x = self.conv1(x) + x = F.relu(x) + x = self.conv2(x) + x = F.relu(x) + x = F.max_pool2d(x, 2) + x = self.dropout1(x) + x = torch.flatten(x, 1) + x = self.fc1(x) + x = F.relu(x) + x = self.dropout2(x) + x = self.fc2(x) + x = self.fc3(x) + output = F.log_softmax(x, dim=1) + return output + + +def train(args, model, device, train_loader, optimizer, epoch, use_fp8): + """Training function.""" + model.train() + for batch_idx, (data, target) in enumerate(train_loader): + data, target = data.to(device), target.to(device) + optimizer.zero_grad() + with te.fp8_autocast(enabled=use_fp8): + output = model(data) + loss = F.nll_loss(output, target) + loss.backward() + optimizer.step() + if batch_idx % args.log_interval == 0: + print( + f"Train Epoch: {epoch} " + f"[{batch_idx * len(data)}/{len(train_loader.dataset)} " + f"({100. * batch_idx / len(train_loader):.0f}%)]\t" + f"Loss: {loss.item():.6f}" + ) + if args.dry_run: + break + + +def calibrate(model, device, test_loader): + """Calibration function.""" + model.eval() + test_loss = 0 + correct = 0 + with torch.no_grad(): + for data, target in test_loader: + data, target = data.to(device), target.to(device) + with te.fp8_autocast(enabled=False, calibrating=True): + output = model(data) + +def test(model, device, test_loader, use_fp8): + """Testing function.""" + model.eval() + test_loss = 0 + correct = 0 + with torch.no_grad(): + for data, target in test_loader: + data, target = data.to(device), target.to(device) + with te.fp8_autocast(enabled=use_fp8): + output = model(data) + test_loss += F.nll_loss( + output, target, reduction="sum" + ).item() # sum up batch loss + pred = output.argmax( + dim=1, keepdim=True + ) # get the index of the max log-probability + correct += pred.eq(target.view_as(pred)).sum().item() + + test_loss /= len(test_loader.dataset) + + print( + f"\nTest set: Average loss: {test_loss:.4f}, " + f"Accuracy: {correct}/{len(test_loader.dataset)} " + f"({100. * correct / len(test_loader.dataset):.0f}%)\n" + ) + + +def main(): + # Training settings + parser = argparse.ArgumentParser(description="PyTorch MNIST Example") + parser.add_argument( + "--batch-size", + type=int, + default=64, + metavar="N", + help="input batch size for training (default: 64)", + ) + parser.add_argument( + "--test-batch-size", + type=int, + default=1000, + metavar="N", + help="input batch size for testing (default: 1000)", + ) + parser.add_argument( + "--epochs", + type=int, + default=14, + metavar="N", + help="number of epochs to train (default: 14)", + ) + parser.add_argument( + "--lr", + type=float, + default=1.0, + metavar="LR", + help="learning rate (default: 1.0)", + ) + parser.add_argument( + "--gamma", + type=float, + default=0.7, + metavar="M", + help="Learning rate step gamma (default: 0.7)", + ) + parser.add_argument( + "--dry-run", + action="store_true", + default=False, + help="quickly check a single pass", + ) + parser.add_argument( + "--seed", type=int, default=1, metavar="S", help="random seed (default: 1)" + ) + parser.add_argument( + "--log-interval", + type=int, + default=10, + metavar="N", + help="how many batches to wait before logging training status", + ) + parser.add_argument( + "--save-model", + action="store_true", + default=False, + help="For Saving the current Model", + ) + parser.add_argument( + "--use-fp8", action="store_true", default=False, help="Use FP8 for inference and training without recalibration" + ) + parser.add_argument( + "--use-fp8-infer", action="store_true", default=False, help="Use FP8 inference only" + ) + parser.add_argument( + "--use-te", action="store_true", default=False, help="Use Transformer Engine" + ) + args = parser.parse_args() + use_cuda = torch.cuda.is_available() + + if args.use_te or args.use_fp8 or args.use_fp8_infer: + assert HAVE_TE, "TransformerEngine not installed." + + if args.use_fp8 or args.use_fp8_infer: + args.use_te = True + + if args.use_te: + assert use_cuda, "CUDA needed for FP8 execution." + + if args.use_fp8_infer: + assert not args.use_fp8, "fp8-infer path currently only supports calibration from a bfloat checkpoint" + + torch.manual_seed(args.seed) + + device = torch.device("cuda" if use_cuda else "cpu") + + train_kwargs = {"batch_size": args.batch_size} + test_kwargs = {"batch_size": args.test_batch_size} + if use_cuda: + cuda_kwargs = {"num_workers": 1, "pin_memory": True, "shuffle": True} + train_kwargs.update(cuda_kwargs) + test_kwargs.update(cuda_kwargs) + + transform = transforms.Compose( + [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] + ) + dataset1 = datasets.MNIST("../data", train=True, download=True, transform=transform) + dataset2 = datasets.MNIST("../data", train=False, transform=transform) + train_loader = torch.utils.data.DataLoader(dataset1, **train_kwargs) + test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs) + + model = Net(use_te=args.use_te).to(device) + optimizer = optim.Adadelta(model.parameters(), lr=args.lr) + + scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma) + for epoch in range(1, args.epochs + 1): + train(args, model, device, train_loader, optimizer, epoch, args.use_fp8) + test(model, device, test_loader, args.use_fp8) + scheduler.step() + + if args.use_fp8_infer: + calibrate(model, device, test_loader) + + if args.save_model or args.use_fp8_infer: + torch.save(model.state_dict(), "mnist_cnn.pt") + print('Eval with reloaded checkpoint : fp8='+str(args.use_fp8_infer)) + weights = torch.load("mnist_cnn.pt") + model.load_state_dict(weights) + test(model, device, test_loader, args.use_fp8_infer) + + +if __name__ == "__main__": + main()
## 📝 What does this PR do? Adds a sample script to use the [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) API for a simple classification task on the MNIST dataset with FP8 capability.
https://api.github.com/repos/hpcaitech/ColossalAI/pulls/3080
2023-03-09T19:05:08Z
2023-03-10T08:24:09Z
2023-03-10T08:24:09Z
2023-03-10T08:24:09Z
2,304
hpcaitech/ColossalAI
11,774
python3: scrapy.__version__, NoneType, urlparse_monkeypatches
diff --git a/scrapy/__init__.py b/scrapy/__init__.py index af904e89df6..cd362dac565 100644 --- a/scrapy/__init__.py +++ b/scrapy/__init__.py @@ -4,6 +4,8 @@ from __future__ import print_function import pkgutil __version__ = pkgutil.get_data(__package__, 'VERSION').strip() +if not isinstance(__version__, str): + __version__ = __version__.decode('ascii') version_info = tuple(__version__.split('.')[:3]) import sys, os, warnings diff --git a/scrapy/utils/trackref.py b/scrapy/utils/trackref.py index 59d6e6727b2..b930b95dd01 100644 --- a/scrapy/utils/trackref.py +++ b/scrapy/utils/trackref.py @@ -14,7 +14,8 @@ from collections import defaultdict from time import time from operator import itemgetter -from types import NoneType + +NoneType = type(None) live_refs = defaultdict(weakref.WeakKeyDictionary) diff --git a/scrapy/xlib/urlparse_monkeypatches.py b/scrapy/xlib/urlparse_monkeypatches.py index fc37810d643..e0ae45b648a 100644 --- a/scrapy/xlib/urlparse_monkeypatches.py +++ b/scrapy/xlib/urlparse_monkeypatches.py @@ -1,11 +1,14 @@ -from urlparse import urlparse +import sys -# workaround for http://bugs.python.org/issue7904 - Python < 2.7 -if urlparse('s3://bucket/key').netloc != 'bucket': - from urlparse import uses_netloc - uses_netloc.append('s3') +if sys.version_info[0] == 2: + from urlparse import urlparse -# workaround for http://bugs.python.org/issue9374 - Python < 2.7.4 -if urlparse('s3://bucket/key?key=value').query != 'key=value': - from urlparse import uses_query - uses_query.append('s3') + # workaround for http://bugs.python.org/issue7904 - Python < 2.7 + if urlparse('s3://bucket/key').netloc != 'bucket': + from urlparse import uses_netloc + uses_netloc.append('s3') + + # workaround for http://bugs.python.org/issue9374 - Python < 2.7.4 + if urlparse('s3://bucket/key?key=value').query != 'key=value': + from urlparse import uses_query + uses_query.append('s3')
Python 3 compatibility changes: 1. `__version__` will be `str` in both 2 and 3. Necessary because pkgutil.get_data returns `bytes` in 3. 2. `NoneType` is not available in 3 3. Apply `urlparse_monkeypatches` in Python 2 only. Patches are not needed in 3 (tested in 3.2-3.4).
https://api.github.com/repos/scrapy/scrapy/pulls/452
2013-11-03T16:57:19Z
2013-11-04T08:54:02Z
2013-11-04T08:54:02Z
2014-06-12T16:08:00Z
587
scrapy/scrapy
34,549
Update openai_tools.ipynb
diff --git a/docs/docs/modules/agents/agent_types/openai_tools.ipynb b/docs/docs/modules/agents/agent_types/openai_tools.ipynb index 99260fd32fc29a..51f99a3b9c3190 100644 --- a/docs/docs/modules/agents/agent_types/openai_tools.ipynb +++ b/docs/docs/modules/agents/agent_types/openai_tools.ipynb @@ -19,7 +19,7 @@ "\n", "Newer OpenAI models have been fine-tuned to detect when **one or more** function(s) should be called and respond with the inputs that should be passed to the function(s). In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call these functions. The goal of the OpenAI tools APIs is to more reliably return valid and useful function calls than what can be done using a generic text completion or chat API.\n", "\n", - "OpenAI termed the capability to invoke a **single** function as **functions**, and the capability to invoke **one or more** funcitons as **tools**.\n", + "OpenAI termed the capability to invoke a **single** function as **functions**, and the capability to invoke **one or more** functions as **tools**.\n", "\n", ":::tip\n", "\n",
typo <!-- 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. -->
https://api.github.com/repos/langchain-ai/langchain/pulls/16618
2024-01-26T06:51:34Z
2024-01-26T23:26:27Z
2024-01-26T23:26:27Z
2024-01-26T23:26:28Z
303
langchain-ai/langchain
43,127
correct spelling
diff --git a/selfdrive/mapd/mapd.py b/selfdrive/mapd/mapd.py index d3c82bf40f6a6f..b123fc68b75cc8 100755 --- a/selfdrive/mapd/mapd.py +++ b/selfdrive/mapd/mapd.py @@ -240,7 +240,7 @@ def mapsd_thread(): if cur_way is not None: dat.liveMapData.wayId = cur_way.id - # Seed limit + # Speed limit max_speed = cur_way.max_speed() if max_speed is not None: dat.liveMapData.speedLimitValid = True
https://api.github.com/repos/commaai/openpilot/pulls/672
2019-05-27T18:40:08Z
2019-05-28T23:16:33Z
2019-05-28T23:16:33Z
2019-12-02T12:58:41Z
141
commaai/openpilot
9,461
✏ Fix typo: 'wll' to 'will' in `docs/en/docs/tutorial/query-params-str-validations.md`
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 6a5a507b91af8..2debd088a0599 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -110,7 +110,7 @@ Notice that the default value is still `None`, so the parameter is still optiona But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎 -FastAPI wll now: +FastAPI will now: * **Validate** the data making sure that the max length is 50 characters * Show a **clear error** for the client when the data is not valid
https://api.github.com/repos/tiangolo/fastapi/pulls/9380
2023-04-11T16:16:42Z
2023-04-13T18:21:17Z
2023-04-13T18:21:17Z
2023-04-13T18:21:17Z
233
tiangolo/fastapi
23,478
document inherited attributes for Flask and Blueprint
diff --git a/flask/app.py b/flask/app.py index 7034b75500..d80514bfc5 100644 --- a/flask/app.py +++ b/flask/app.py @@ -346,6 +346,21 @@ def _set_request_globals_class(self, value): #: .. versionadded:: 0.8 session_interface = SecureCookieSessionInterface() + # TODO remove the next three attrs when Sphinx :inherited-members: works + # https://github.com/sphinx-doc/sphinx/issues/741 + + #: The name of the package or module that this app belongs to. Do not + #: change this once it is set by the constructor. + import_name = None + + #: Location of the template files to be added to the template lookup. + #: ``None`` if templates should not be added. + template_folder = None + + #: Absolute path to the package on the filesystem. Used to look up + #: resources contained in the package. + root_path = None + def __init__(self, import_name, static_path=None, static_url_path=None, static_folder='static', static_host=None, host_matching=False, template_folder='templates', diff --git a/flask/blueprints.py b/flask/blueprints.py index 57d77512e6..ed51094e53 100644 --- a/flask/blueprints.py +++ b/flask/blueprints.py @@ -96,6 +96,21 @@ class Blueprint(_PackageBoundObject): #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`. json_decoder = None + # TODO remove the next three attrs when Sphinx :inherited-members: works + # https://github.com/sphinx-doc/sphinx/issues/741 + + #: The name of the package or module that this app belongs to. Do not + #: change this once it is set by the constructor. + import_name = None + + #: Location of the template files to be added to the template lookup. + #: ``None`` if templates should not be added. + template_folder = None + + #: Absolute path to the package on the filesystem. Used to look up + #: resources contained in the package. + root_path = None + def __init__(self, name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, diff --git a/flask/helpers.py b/flask/helpers.py index f37be677c2..94c5ce7770 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -480,10 +480,10 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, .. versionchanged:: 0.12 The `attachment_filename` is preferred over `filename` for MIME-type detection. - + .. versionchanged:: 0.13 UTF-8 filenames, as specified in `RFC 2231`_, are supported. - + .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4 :param filename_or_fp: the filename of the file to send. @@ -848,43 +848,56 @@ def __get__(self, obj, type=None): class _PackageBoundObject(object): + #: The name of the package or module that this app belongs to. Do not + #: change this once it is set by the constructor. + import_name = None + + #: Location of the template files to be added to the template lookup. + #: ``None`` if templates should not be added. + template_folder = None + + #: Absolute path to the package on the filesystem. Used to look up + #: resources contained in the package. + root_path = None def __init__(self, import_name, template_folder=None, root_path=None): - #: The name of the package or module. Do not change this once - #: it was set by the constructor. self.import_name = import_name - - #: location of the templates. ``None`` if templates should not be - #: exposed. self.template_folder = template_folder if root_path is None: root_path = get_root_path(self.import_name) - #: Where is the app root located? self.root_path = root_path - self._static_folder = None self._static_url_path = None def _get_static_folder(self): if self._static_folder is not None: return os.path.join(self.root_path, self._static_folder) + def _set_static_folder(self, value): self._static_folder = value - static_folder = property(_get_static_folder, _set_static_folder, doc=''' - The absolute path to the configured static folder. - ''') + + static_folder = property( + _get_static_folder, _set_static_folder, + doc='The absolute path to the configured static folder.' + ) del _get_static_folder, _set_static_folder def _get_static_url_path(self): if self._static_url_path is not None: return self._static_url_path + if self.static_folder is not None: return '/' + os.path.basename(self.static_folder) + def _set_static_url_path(self, value): self._static_url_path = value - static_url_path = property(_get_static_url_path, _set_static_url_path) + + static_url_path = property( + _get_static_url_path, _set_static_url_path, + doc='The URL prefix that the static route will be registered for.' + ) del _get_static_url_path, _set_static_url_path @property
Sphinx autodoc `:inherited-members:` doesn't include attributes. The only solution is to duplicate the `_PackageBoundObject` attributes and their docs in the `Flask` and `Blueprint` classes. The duplicated attributes can be removed once sphinx-doc/sphinx#741 is fixed. closes #480
https://api.github.com/repos/pallets/flask/pulls/2363
2017-06-06T14:52:41Z
2017-06-06T14:52:56Z
2017-06-06T14:52:56Z
2020-11-14T03:53:04Z
1,288
pallets/flask
20,371
Improve JSON output when there is leading data before the actual JSON body
diff --git a/CHANGELOG.md b/CHANGELOG.md index 847e70b519..ec56074ab6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [2.6.0.dev0](https://github.com/httpie/httpie/compare/2.5.0...master) (unreleased) +- Added support for formatting & coloring of JSON bodies preceded by non-JSON data (e.g., an XXSI prefix). ([#1130](https://github.com/httpie/httpie/issues/1130)) + ## [2.5.0](https://github.com/httpie/httpie/compare/2.4.0...2.5.0) (2021-09-06) Blog post: [What’s new in HTTPie 2.5.0](https://httpie.io/blog/httpie-2.5.0) diff --git a/httpie/output/formatters/colors.py b/httpie/output/formatters/colors.py index ff182d2387..d0187337b0 100644 --- a/httpie/output/formatters/colors.py +++ b/httpie/output/formatters/colors.py @@ -9,10 +9,12 @@ from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer +from pygments.lexers.data import JsonLexer from pygments.lexers.special import TextLexer from pygments.lexers.text import HttpLexer as PygmentsHttpLexer from pygments.util import ClassNotFound +from ..lexers.json import EnhancedJsonLexer from ...compat import is_windows from ...context import Environment from ...plugins import FormatterPlugin @@ -60,6 +62,7 @@ def __init__( http_lexer = PygmentsHttpLexer() formatter = TerminalFormatter() else: + from ..lexers.http import SimplifiedHTTPLexer http_lexer = SimplifiedHTTPLexer() formatter = Terminal256Formatter( style=self.get_style_class(color_scheme) @@ -151,55 +154,12 @@ def get_lexer( else: lexer = pygments.lexers.get_lexer_by_name('json') - return lexer - - -class SimplifiedHTTPLexer(pygments.lexer.RegexLexer): - """Simplified HTTP lexer for Pygments. - - It only operates on headers and provides a stronger contrast between - their names and values than the original one bundled with Pygments - (:class:`pygments.lexers.text import HttpLexer`), especially when - Solarized color scheme is used. + # Use our own JSON lexer: it supports JSON bodies preceded by non-JSON data + # as well as legit JSON bodies. + if isinstance(lexer, JsonLexer): + lexer = EnhancedJsonLexer() - """ - name = 'HTTP' - aliases = ['http'] - filenames = ['*.http'] - tokens = { - 'root': [ - # Request-Line - (r'([A-Z]+)( +)([^ ]+)( +)(HTTP)(/)(\d+\.\d+)', - pygments.lexer.bygroups( - pygments.token.Name.Function, - pygments.token.Text, - pygments.token.Name.Namespace, - pygments.token.Text, - pygments.token.Keyword.Reserved, - pygments.token.Operator, - pygments.token.Number - )), - # Response Status-Line - (r'(HTTP)(/)(\d+\.\d+)( +)(\d{3})( +)(.+)', - pygments.lexer.bygroups( - pygments.token.Keyword.Reserved, # 'HTTP' - pygments.token.Operator, # '/' - pygments.token.Number, # Version - pygments.token.Text, - pygments.token.Number, # Status code - pygments.token.Text, - pygments.token.Name.Exception, # Reason - )), - # Header - (r'(.*?)( *)(:)( *)(.+)', pygments.lexer.bygroups( - pygments.token.Name.Attribute, # Name - pygments.token.Text, - pygments.token.Operator, # Colon - pygments.token.Text, - pygments.token.String # Value - )) - ] - } + return lexer class Solarized256Style(pygments.style.Style): diff --git a/httpie/output/formatters/json.py b/httpie/output/formatters/json.py index 65cbcd1989..bc6151e42f 100644 --- a/httpie/output/formatters/json.py +++ b/httpie/output/formatters/json.py @@ -17,15 +17,16 @@ def format_body(self, body: str, mime: str) -> str: ] if (self.kwargs['explicit_json'] or any(token in mime for token in maybe_json)): + from ..utils import load_prefixed_json try: - obj = json.loads(body) + data_prefix, json_obj = load_prefixed_json(body) except ValueError: pass # Invalid JSON, ignore. else: # Indent, sort keys by name, and avoid # unicode escapes to improve readability. - body = json.dumps( - obj=obj, + body = data_prefix + json.dumps( + obj=json_obj, sort_keys=self.format_options['json']['sort_keys'], ensure_ascii=False, indent=self.format_options['json']['indent'] diff --git a/httpie/output/lexers/__init__.py b/httpie/output/lexers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/httpie/output/lexers/http.py b/httpie/output/lexers/http.py new file mode 100644 index 0000000000..4c2b00d252 --- /dev/null +++ b/httpie/output/lexers/http.py @@ -0,0 +1,49 @@ +import pygments + + +class SimplifiedHTTPLexer(pygments.lexer.RegexLexer): + """Simplified HTTP lexer for Pygments. + + It only operates on headers and provides a stronger contrast between + their names and values than the original one bundled with Pygments + (:class:`pygments.lexers.text import HttpLexer`), especially when + Solarized color scheme is used. + + """ + name = 'HTTP' + aliases = ['http'] + filenames = ['*.http'] + tokens = { + 'root': [ + # Request-Line + (r'([A-Z]+)( +)([^ ]+)( +)(HTTP)(/)(\d+\.\d+)', + pygments.lexer.bygroups( + pygments.token.Name.Function, + pygments.token.Text, + pygments.token.Name.Namespace, + pygments.token.Text, + pygments.token.Keyword.Reserved, + pygments.token.Operator, + pygments.token.Number + )), + # Response Status-Line + (r'(HTTP)(/)(\d+\.\d+)( +)(\d{3})( +)(.+)', + pygments.lexer.bygroups( + pygments.token.Keyword.Reserved, # 'HTTP' + pygments.token.Operator, # '/' + pygments.token.Number, # Version + pygments.token.Text, + pygments.token.Number, # Status code + pygments.token.Text, + pygments.token.Name.Exception, # Reason + )), + # Header + (r'(.*?)( *)(:)( *)(.+)', pygments.lexer.bygroups( + pygments.token.Name.Attribute, # Name + pygments.token.Text, + pygments.token.Operator, # Colon + pygments.token.Text, + pygments.token.String # Value + )) + ] + } diff --git a/httpie/output/lexers/json.py b/httpie/output/lexers/json.py new file mode 100644 index 0000000000..a235c4f3a3 --- /dev/null +++ b/httpie/output/lexers/json.py @@ -0,0 +1,31 @@ +import re + +from pygments.lexer import bygroups, using, RegexLexer +from pygments.lexers.data import JsonLexer +from pygments.token import Token + +PREFIX_TOKEN = Token.Error +PREFIX_REGEX = r'[^{\["]+' + + +class EnhancedJsonLexer(RegexLexer): + """ + Enhanced JSON lexer for Pygments. + + It adds support for eventual data prefixing the actual JSON body. + + """ + name = 'JSON' + flags = re.IGNORECASE | re.DOTALL + tokens = { + 'root': [ + # Eventual non-JSON data prefix followed by actual JSON body. + # FIX: data prefix + number (integer or float) are not correctly handled. + ( + fr'({PREFIX_REGEX})' + r'((?:[{\["]|true|false|null).+)', + bygroups(PREFIX_TOKEN, using(JsonLexer)) + ), + # JSON body. + (r'.+', using(JsonLexer)), + ], + } diff --git a/httpie/output/utils.py b/httpie/output/utils.py new file mode 100644 index 0000000000..5ae7f603d5 --- /dev/null +++ b/httpie/output/utils.py @@ -0,0 +1,36 @@ +import json +import re +from typing import Tuple + +from .lexers.json import PREFIX_REGEX + + +def load_prefixed_json(data: str) -> Tuple[str, json.JSONDecoder]: + """Simple JSON loading from `data`. + + """ + # First, the full data. + try: + return '', json.loads(data) + except ValueError: + pass + + # Then, try to find the start of the actual body. + data_prefix, body = parse_prefixed_json(data) + try: + return data_prefix, json.loads(body) + except ValueError: + raise ValueError('Invalid JSON') + + +def parse_prefixed_json(data: str) -> Tuple[str, str]: + """Find the potential JSON body from `data`. + + Sometimes the JSON body is prefixed with a XSSI magic string, specific to the server. + Return a tuple (data prefix, actual JSON body). + + """ + matches = re.findall(PREFIX_REGEX, data) + data_prefix = matches[0] if matches else '' + body = data[len(data_prefix):] + return data_prefix, body diff --git a/tests/test_json.py b/tests/test_json.py new file mode 100644 index 0000000000..4d210f23e0 --- /dev/null +++ b/tests/test_json.py @@ -0,0 +1,40 @@ +import json + +import pytest +import responses + +from httpie.cli.constants import PRETTY_MAP +from httpie.compat import is_windows +from httpie.output.formatters.colors import ColorFormatter + +from .utils import MockEnvironment, http, URL_EXAMPLE + +TEST_JSON_XXSI_PREFIXES = (r")]}',\n", ")]}',", 'while(1);', 'for(;;)', ')', ']', '}') +TEST_JSON_VALUES = ({}, {'a': 0, 'b': 0}, [], ['a', 'b'], 'foo', True, False, None) # FIX: missing int & float +TEST_PREFIX_TOKEN_COLOR = '\x1b[38;5;15m' if is_windows else '\x1b[04m\x1b[91m' + + +@pytest.mark.parametrize('data_prefix', TEST_JSON_XXSI_PREFIXES) +@pytest.mark.parametrize('json_data', TEST_JSON_VALUES) +@pytest.mark.parametrize('pretty', PRETTY_MAP.keys()) +@responses.activate +def test_json_formatter_with_body_preceded_by_non_json_data(data_prefix, json_data, pretty): + """Test JSON bodies preceded by non-JSON data.""" + body = data_prefix + json.dumps(json_data) + content_type = 'application/json' + responses.add(responses.GET, URL_EXAMPLE, body=body, + content_type=content_type) + + colored_output = pretty in ('all', 'colors') + env = MockEnvironment(colors=256) if colored_output else None + r = http('--pretty=' + pretty, URL_EXAMPLE, env=env) + + indent = None if pretty in ('none', 'colors') else 4 + expected_body = data_prefix + json.dumps(json_data, indent=indent) + if colored_output: + fmt = ColorFormatter(env, format_options={'json': {'format': True, 'indent': 4}}) + expected_body = fmt.format_body(expected_body, content_type) + # Check to ensure the non-JSON data prefix is colored only one time, + # meaning it was correctly handled as a whole. + assert TEST_PREFIX_TOKEN_COLOR + data_prefix in expected_body, expected_body + assert expected_body in r
In some special cases, to prevent against Cross Site Script Inclusion (XSSI) attacks, the JSON response body starts with a magic prefix line that must be stripped before feeding the rest of the response body to the JSON parser. Such prefix is now simply ignored from the parser but still printed in the terminal. Supersedes #529.
https://api.github.com/repos/httpie/cli/pulls/1130
2021-08-18T15:03:00Z
2021-09-21T09:15:43Z
2021-09-21T09:15:43Z
2021-10-11T11:54:55Z
2,953
httpie/cli
34,166
Avoid breaking crappy distribution methods.
diff --git a/setup.py b/setup.py index 16ba717b68..879d94a636 100755 --- a/setup.py +++ b/setup.py @@ -30,8 +30,6 @@ readme = f.read() with open('HISTORY.rst') as f: history = f.read() -with open('LICENSE') as f: - license = f.read() setup( name='requests', @@ -46,7 +44,7 @@ package_dir={'requests': 'requests'}, include_package_data=True, install_requires=requires, - license=license, + license='Apache 2.0', zip_safe=False, classifiers=( 'Development Status :: 5 - Production/Stable',
Apparently RPM doesn't like us having the full license text in the 'license' section, as in #1878. Seems innocuous to change this, because realistically who the hell cares?
https://api.github.com/repos/psf/requests/pulls/1893
2014-01-29T19:23:36Z
2014-01-30T17:23:57Z
2014-01-30T17:23:57Z
2021-09-08T23:11:10Z
161
psf/requests
32,136
Fix dtype error in MHA layer/change dtype checking mechanism for manual cast
diff --git a/modules/devices.py b/modules/devices.py index dfffaf24fd0..8f49f7a486b 100644 --- a/modules/devices.py +++ b/modules/devices.py @@ -4,7 +4,6 @@ import torch from modules import errors, shared -from modules import torch_utils if sys.platform == "darwin": from modules import mac_specific @@ -141,7 +140,12 @@ def forward_wrapper(self, *args, **kwargs): args = [arg.to(target_dtype) if isinstance(arg, torch.Tensor) else arg for arg in args] kwargs = {k: v.to(target_dtype) if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()} - org_dtype = torch_utils.get_param(self).dtype + org_dtype = target_dtype + for param in self.parameters(): + if param.dtype != target_dtype: + org_dtype = param.dtype + break + if org_dtype != target_dtype: self.to(target_dtype) result = self.org_forward(*args, **kwargs) @@ -170,7 +174,7 @@ def manual_cast(target_dtype): continue applied = True org_forward = module_type.forward - if module_type == torch.nn.MultiheadAttention and has_xpu(): + if module_type == torch.nn.MultiheadAttention: module_type.forward = manual_cast_forward(torch.float32) else: module_type.forward = manual_cast_forward(target_dtype)
## Description torch.nn.MultiheadAttention have so much forks inside their forward call and is impossible to patch their inside call of computation operationg. I decide to give it "always fp32" when manual_cast is used. And since the dtype error I got is weird, it claim the tensor it got is fp32 and fp8, which should never happen.(Should at least be fp32 and fp16) So it is possible that torch_utils.get_param is not working for my case. Based on some test, I finally decide to just go through all the parameters to check if there are any different dtype parameters. ## Checklist: - [x] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) - [x] I have performed a self-review of my own code - [x] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style) - [x] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/14791
2024-01-29T15:04:34Z
2024-01-29T17:39:06Z
2024-01-29T17:39:06Z
2024-01-29T17:39:09Z
322
AUTOMATIC1111/stable-diffusion-webui
39,710
bug fixes and updates for eos connections
diff --git a/lib/ansible/module_utils/eos.py b/lib/ansible/module_utils/eos.py index f283fe4cbbcbe8..622331cb8daa67 100644 --- a/lib/ansible/module_utils/eos.py +++ b/lib/ansible/module_utils/eos.py @@ -94,6 +94,15 @@ class Cli: def __init__(self, module): self._module = module self._device_configs = {} + self._session_support = None + + @property + def supports_sessions(self): + if self._session_support is not None: + return self._session_support + rc, out, err = self.exec_command('show configuration sessions') + self._session_support = rc == 0 + return self._session_support def exec_command(self, command): if isinstance(command, dict): @@ -195,7 +204,7 @@ def load_config(self, commands, commit=False, replace=False): except ValueError: pass - if not all((bool(use_session), self.supports_sessions())): + if not all((bool(use_session), self.supports_sessions)): return configure(self, commands) conn = get_connection(self) @@ -255,6 +264,14 @@ def __init__(self, module): else: self._enable = 'enable' + @property + def supports_sessions(self): + if self._session_support: + return self._session_support + response = self.send_request(['show configuration sessions']) + self._session_support = 'error' not in response + return self._session_support + def _request_builder(self, commands, output, reqid=None): params = dict(version=1, cmds=commands, format=output) return dict(jsonrpc='2.0', id=reqid, method='runCmds', params=params) @@ -344,13 +361,6 @@ def get_config(self, flags=[]): self._device_configs[cmd] = cfg return cfg - def supports_sessions(self): - if self._session_support: - return self._session_support - response = self.send_request(['show configuration sessions']) - self._session_support = 'error' not in response - return self._session_support - def configure(self, commands): """Sends the ordered set of commands to the device """ @@ -371,7 +381,7 @@ def load_config(self, config, commit=False, replace=False): fallback to using configure() to load the commands. If that happens, there will be no returned diff or session values """ - if not supports_sessions(): + if not self.supports_sessions: return configure(self, commands) session = 'ansible_%s' % int(time.time()) @@ -406,6 +416,8 @@ def load_config(self, config, commit=False, replace=False): is_json = lambda x: str(x).endswith('| json') is_text = lambda x: not str(x).endswith('| json') +supports_sessions = lambda x: get_connection(module).supports_sessions + def get_config(module, flags=[]): conn = get_connection(module) return conn.get_config(flags) diff --git a/lib/ansible/plugins/action/eos.py b/lib/ansible/plugins/action/eos.py index 9b6d1484bb7acc..ef067392c57ada 100644 --- a/lib/ansible/plugins/action/eos.py +++ b/lib/ansible/plugins/action/eos.py @@ -31,20 +31,28 @@ from ansible.module_utils.basic import AnsibleFallbackNotFound from ansible.module_utils._text import to_bytes +try: + from __main__ import display +except ImportError: + from ansible.utils.display import Display + display = Display() + class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): if self._play_context.connection != 'local': return dict( - fail=True, + failed=True, msg='invalid connection specified, expected connection=local, ' 'got %s' % self._play_context.connection ) provider = self.load_provider() - transport = provider['transport'] + transport = provider['transport'] or 'cli' + + display.vvv('transport is %s' % transport, self._play_context.remote_addr) - if not transport or 'cli' in transport: + if transport == 'cli': pc = copy.deepcopy(self._play_context) pc.connection = 'network_cli' pc.network_os = 'eos' @@ -53,12 +61,14 @@ def run(self, tmp=None, task_vars=None): pc.become = provider['authorize'] or False pc.become_pass = provider['auth_pass'] + connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin) socket_path = self._get_socket_path(pc) if not os.path.exists(socket_path): # start the connection if it isn't started - connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin) - connection.exec_command('EXEC: show version') + rc, out, err = connection.exec_command('open_shell()') + if not rc == 0: + return {'failed': True, 'msg': 'unable to open shell', 'rc': rc} task_vars['ansible_socket'] = socket_path @@ -80,7 +90,13 @@ def run(self, tmp=None, task_vars=None): self._play_context.become = False self._play_context.become_method = None - return super(ActionModule, self).run(tmp, task_vars) + result = super(ActionModule, self).run(tmp, task_vars) + + if transport == 'cli': + display.vvv('closing cli shell connection', self._play_context.remote_addr) + rc, out, err = connection.exec_command('close_shell()') + + return result def _get_socket_path(self, play_context): ssh = connection_loader.get('ssh', class_only=True) diff --git a/lib/ansible/plugins/connection/network_cli.py b/lib/ansible/plugins/connection/network_cli.py index 1a283cb87a3305..ef3d2017b91b79 100644 --- a/lib/ansible/plugins/connection/network_cli.py +++ b/lib/ansible/plugins/connection/network_cli.py @@ -99,7 +99,6 @@ def _connect(self): @ensure_connect def open_shell(self): - """Opens the vty shell on the connection""" self._shell = self.ssh.invoke_shell() self._shell.settimeout(self._play_context.timeout) @@ -112,6 +111,8 @@ def open_shell(self): auth_pass = self._play_context.become_pass self._terminal.on_authorize(passwd=auth_pass) + return (0, 'ok', '') + def close(self): display.vvv('closing connection', host=self._play_context.remote_addr) self.close_shell() @@ -127,7 +128,7 @@ def close_shell(self): self._shell.close() self._shell = None - return (0, 'shell closed', '') + return (0, 'ok', '') def receive(self, obj=None): """Handles receiving of output from command""" @@ -233,6 +234,8 @@ def exec_command(self, cmd): if obj['command'] == 'close_shell()': return self.close_shell() + elif obj['command'] == 'open_shell()': + return self.open_shell() elif obj['command'] == 'prompt()': return (0, self._matched_prompt, '') elif obj['command'] == 'history()':
* refactors supports_sessions to a property * exposes supports_sessions as a toplevel function * adds open_shell() to network_cli * implements open_shell() in eos action plugin
https://api.github.com/repos/ansible/ansible/pulls/21534
2017-02-16T20:18:41Z
2017-02-17T01:26:49Z
2017-02-17T01:26:49Z
2019-04-26T20:33:12Z
1,705
ansible/ansible
49,072
Bitstamp fetchOrder string math
diff --git a/js/bitstamp.js b/js/bitstamp.js index 8231d27b89ed..1f23a7c42798 100644 --- a/js/bitstamp.js +++ b/js/bitstamp.js @@ -1567,8 +1567,10 @@ module.exports = class bitstamp extends Exchange { } parseTransactionStatus (status) { - // withdrawals: - // 0 (open), 1 (in process), 2 (finished), 3 (canceled) or 4 (failed). + // + // withdrawals: + // 0 (open), 1 (in process), 2 (finished), 3 (canceled) or 4 (failed). + // const statuses = { '0': 'pending', // Open '1': 'pending', // In process @@ -1580,43 +1582,44 @@ module.exports = class bitstamp extends Exchange { } parseOrder (order, market = undefined) { - // from fetch order: - // { status: 'Finished', - // id: 731693945, - // client_order_id: '', - // transactions: - // [ { fee: '0.000019', - // price: '0.00015803', - // datetime: '2018-01-07 10:45:34.132551', - // btc: '0.0079015000000000', - // tid: 42777395, - // type: 2, - // xrp: '50.00000000' } ] } - // - // partially filled order: - // { "id": 468646390, - // "client_order_id": "", - // "status": "Canceled", - // "transactions": [{ - // "eth": "0.23000000", - // "fee": "0.09", - // "tid": 25810126, - // "usd": "69.8947000000000000", - // "type": 2, - // "price": "303.89000000", - // "datetime": "2017-11-11 07:22:20.710567" - // }]} - // - // from create order response: - // { - // price: '0.00008012', - // client_order_id: '', - // currency_pair: 'XRP/BTC', - // datetime: '2019-01-31 21:23:36', - // amount: '15.00000000', - // type: '0', - // id: '2814205012' - // } + // + // from fetch order: + // { status: 'Finished', + // id: 731693945, + // client_order_id: '', + // transactions: + // [ { fee: '0.000019', + // price: '0.00015803', + // datetime: '2018-01-07 10:45:34.132551', + // btc: '0.0079015000000000', + // tid: 42777395, + // type: 2, + // xrp: '50.00000000' } ] } + // + // partially filled order: + // { "id": 468646390, + // "client_order_id": "", + // "status": "Canceled", + // "transactions": [{ + // "eth": "0.23000000", + // "fee": "0.09", + // "tid": 25810126, + // "usd": "69.8947000000000000", + // "type": 2, + // "price": "303.89000000", + // "datetime": "2017-11-11 07:22:20.710567" + // }]} + // + // from create order response: + // { + // price: '0.00008012', + // client_order_id: '', + // currency_pair: 'XRP/BTC', + // datetime: '2019-01-31 21:23:36', + // amount: '15.00000000', + // type: '0', + // id: '2814205012' + // } // const id = this.safeString (order, 'id'); const clientOrderId = this.safeString (order, 'client_order_id'); @@ -1734,13 +1737,13 @@ module.exports = class bitstamp extends Exchange { const parsedTransaction = this.parseTransaction (item, currency); let direction = undefined; if ('amount' in item) { - const amount = this.safeNumber (item, 'amount'); - direction = (amount > 0) ? 'in' : 'out'; + const amount = this.safeString (item, 'amount'); + direction = Precise.stringGt (amount, '0') ? 'in' : 'out'; } else if (('currency' in parsedTransaction) && parsedTransaction['currency'] !== undefined) { const currencyCode = this.safeString (parsedTransaction, 'currency'); currency = this.currency (currencyCode); - const amount = this.safeNumber (item, currency['id']); - direction = (amount > 0) ? 'in' : 'out'; + const amount = this.safeString (item, currency['id']); + direction = Precise.stringGt (amount, '0') ? 'in' : 'out'; } return { 'id': parsedTransaction['id'], @@ -1803,6 +1806,7 @@ module.exports = class bitstamp extends Exchange { market = this.market (symbol); } const response = await this.privatePostOpenOrdersAll (params); + // // [ // { // price: '0.00008012', @@ -1822,6 +1826,12 @@ module.exports = class bitstamp extends Exchange { } getCurrencyName (code) { + /** + * @ignore + * @method + * @param {str} code Unified currency code + * @returns {str} lowercase version of code + */ return code.toLowerCase (); } @@ -1958,6 +1968,7 @@ module.exports = class bitstamp extends Exchange { // {"error": "No permission found"} // fetchDepositAddress returns this on apiKeys that don't have the permission required // {"status": "error", "reason": {"__all__": ["Minimum order size is 5.0 EUR."]}} // reuse of a nonce gives: { status: 'error', reason: 'Invalid nonce', code: 'API0004' } + // const status = this.safeString (response, 'status'); const error = this.safeValue (response, 'error'); if ((status === 'error') || (error !== undefined)) {
``` % bitstamp fetchLedger LTC 2022-09-15T23:41:33.286Z Node.js: v18.4.0 CCXT v1.93.59 (node:10554) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) bitstamp.fetchLedger (LTC) 2022-09-15T23:41:34.515Z iteration 0 passed in 534 ms id | timestamp | datetime | direction | account | referenceId | referenceAccount | type | currency | amount | before | after | status | fee ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 247608267 | 1663283603858 | 2022-09-15T23:13:23.858Z | in | | | | transaction | LTC | 0.227 | | | ok | {"currency":"LTC","cost":"0.00000000"} 1 objects 2022-09-15T23:41:34.515Z iteration 1 passed in 534 ms ```
https://api.github.com/repos/ccxt/ccxt/pulls/15019
2022-09-15T23:00:05Z
2022-09-30T16:46:15Z
2022-09-30T16:46:15Z
2022-09-30T16:46:16Z
1,649
ccxt/ccxt
13,825
Bugfix/changelog
diff --git a/certbot/CHANGELOG.md b/certbot/CHANGELOG.md index d01d5906908..6f39a27b98d 100644 --- a/certbot/CHANGELOG.md +++ b/certbot/CHANGELOG.md @@ -6,7 +6,8 @@ Certbot adheres to [Semantic Versioning](https://semver.org/). ### Added -* +* Added the ability to remove email and phone contact information from an account + using `update_account --register-unsafely-without-email` ### Changed @@ -16,6 +17,8 @@ Certbot adheres to [Semantic Versioning](https://semver.org/). * The problem causing the Apache plugin in the Certbot snap on ARM systems to fail to load the Augeas library it depends on has been fixed. +* The `acme` library can now tell the ACME server to clear contact information by passing an empty + `tuple` to the `contact` field of a `Registration` message. More details about these changes can be found on our GitHub repo. @@ -27,8 +30,6 @@ More details about these changes can be found on our GitHub repo. this concerns the plugin name, CLI flags, and keys in credential files. The prefixed form is still supported but is deprecated, and will be removed in a future release. * Added `--nginx-sleep-seconds` (default `1`) for environments where nginx takes a long time to reload. -* Added the ability to remove email and phone contact information from an account - using `update_account --register-unsafely-without-email` ### Changed @@ -39,8 +40,6 @@ More details about these changes can be found on our GitHub repo. ### Fixed -* The `acme` library can now tell the ACME server to clear contact information by passing an empty - `tuple` to the `contact` field of a `Registration` message. More details about these changes can be found on our GitHub repo.
Fixing a mistake in pull request #8212 where I recorded my changes in an already released version 😳.
https://api.github.com/repos/certbot/certbot/pulls/8236
2020-08-27T00:55:46Z
2020-08-27T16:45:11Z
2020-08-27T16:45:11Z
2020-08-27T16:45:11Z
451
certbot/certbot
2,288
Ensure `skip_defaults` doesn't cause extra fields to be serialized
diff --git a/fastapi/routing.py b/fastapi/routing.py index 930cbe001ff1d..08f43bf524a8d 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -45,6 +45,8 @@ def serialize_response( ) -> Any: if field: errors = [] + if skip_defaults and isinstance(response, BaseModel): + response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) @@ -52,8 +54,6 @@ def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) - if skip_defaults and isinstance(response, BaseModel): - value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=include, diff --git a/tests/test_skip_defaults.py b/tests/test_skip_defaults.py index 8579b50ea560a..9997ba7b2c4b1 100644 --- a/tests/test_skip_defaults.py +++ b/tests/test_skip_defaults.py @@ -16,9 +16,13 @@ class Model(BaseModel): sub: SubModel +class ModelSubclass(Model): + y: int + + @app.get("/", response_model=Model, response_model_skip_defaults=True) -def get() -> Model: - return Model(sub={}) +def get() -> ModelSubclass: + return ModelSubclass(sub={}, y=1) client = TestClient(app)
Currently, if `skip_defaults` is true, the secure cloned field is not used when serializing the response. This can lead to extra information leaking out if the `response_model` differs in type from the returned model. This pull request fixes this bug, and updates the relevant unit test to check for it. (The bug was introduced in #422 -- sorry about that!) ----- I believe this pull request also improves performance in the case where `skip_defaults` is `True`, as the response will now only be validated once in the `serialize_response` call, instead of twice.
https://api.github.com/repos/tiangolo/fastapi/pulls/485
2019-08-29T22:59:39Z
2019-08-30T23:56:14Z
2019-08-30T23:56:14Z
2019-09-04T14:30:12Z
347
tiangolo/fastapi
23,567
[3.8] bpo-40121: Fix exception type in test (GH-19267)
diff --git a/Lib/test/audit-tests.py b/Lib/test/audit-tests.py index dda52a5a518f6a..b90c4b8f75794d 100644 --- a/Lib/test/audit-tests.py +++ b/Lib/test/audit-tests.py @@ -343,7 +343,7 @@ def hook(event, args): try: # Don't care if this fails, we just want the audit message sock.bind(('127.0.0.1', 8080)) - except error: + except Exception: pass finally: sock.close()
(cherry picked from commit 3ef4a7e5a7c29e17d5152d1fa6ceeb1fee269699) Co-authored-by: Steve Dower <steve.dower@python.org> <!-- issue-number: [bpo-40121](https://bugs.python.org/issue40121) --> https://bugs.python.org/issue40121 <!-- /issue-number -->
https://api.github.com/repos/python/cpython/pulls/19276
2020-04-01T12:45:06Z
2020-04-01T13:02:56Z
2020-04-01T13:02:56Z
2020-04-01T13:12:22Z
138
python/cpython
4,414
[FIFA] Back-port extractor from yt-dlp
diff --git a/youtube_dl/extractor/extractors.py b/youtube_dl/extractor/extractors.py index 947cbe8fdb4..21b17185eca 100644 --- a/youtube_dl/extractor/extractors.py +++ b/youtube_dl/extractor/extractors.py @@ -374,6 +374,7 @@ FC2EmbedIE, ) from .fczenit import FczenitIE +from .fifa import FifaIE from .filmon import ( FilmOnIE, FilmOnChannelIE, diff --git a/youtube_dl/extractor/fifa.py b/youtube_dl/extractor/fifa.py new file mode 100644 index 00000000000..15157774ee4 --- /dev/null +++ b/youtube_dl/extractor/fifa.py @@ -0,0 +1,101 @@ +# coding: utf-8 +from __future__ import unicode_literals + +from .common import InfoExtractor + +from ..utils import ( + int_or_none, + traverse_obj, + unified_timestamp, +) + +if not callable(getattr(InfoExtractor, '_match_valid_url', None)): + + BaseInfoExtractor = InfoExtractor + + import re + + class InfoExtractor(BaseInfoExtractor): + + @classmethod + def _match_valid_url(cls, url): + return re.match(cls._VALID_URL, url) + + +class FifaIE(InfoExtractor): + _VALID_URL = r'https?://www.fifa.com/fifaplus/(?P<locale>\w{2})/watch/([^#?]+/)?(?P<id>\w+)' + _TESTS = [{ + 'url': 'https://www.fifa.com/fifaplus/en/watch/7on10qPcnyLajDDU3ntg6y', + 'info_dict': { + 'id': '7on10qPcnyLajDDU3ntg6y', + 'title': 'Italy v France | Final | 2006 FIFA World Cup Germany™ | Full Match Replay', + 'description': 'md5:f4520d0ee80529c8ba4134a7d692ff8b', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments'], + 'thumbnail': 'https://digitalhub.fifa.com/transform/135e2656-3a51-407b-8810-6c34bec5b59b/FMR_2006_Italy_France_Final_Hero', + 'duration': 8165, + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://www.fifa.com/fifaplus/pt/watch/1cg5r5Qt6Qt12ilkDgb1sV', + 'info_dict': { + 'id': '1cg5r5Qt6Qt12ilkDgb1sV', + 'title': 'Brazil v Germany | Semi-finals | 2014 FIFA World Cup Brazil™ | Extended Highlights', + 'description': 'md5:d908c74ee66322b804ae2e521b02a855', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments', 'Highlights'], + 'thumbnail': 'https://digitalhub.fifa.com/transform/d8fe6f61-276d-4a73-a7fe-6878a35fd082/FIFAPLS_100EXTHL_2014BRAvGER_TMB', + 'duration': 902, + 'release_timestamp': 1404777600, + 'release_date': '20140708', + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://www.fifa.com/fifaplus/fr/watch/3C6gQH9C2DLwzNx7BMRQdp', + 'info_dict': { + 'id': '3C6gQH9C2DLwzNx7BMRQdp', + 'title': 'Josimar goal against Northern Ireland | Classic Goals', + 'description': 'md5:cbe7e7bb52f603c9f1fe9a4780fe983b', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments', 'Goal'], + 'duration': 28, + 'thumbnail': 'https://digitalhub.fifa.com/transform/f9301391-f8d9-48b5-823e-c093ac5e3e11/CG_MEN_1986_JOSIMAR', + }, + 'params': {'skip_download': 'm3u8'}, + }] + + def _real_extract(self, url): + video_id, locale = self._match_valid_url(url).group('id', 'locale') + webpage = self._download_webpage(url, video_id) + + preconnect_link = self._search_regex( + r'<link\b[^>]+\brel\s*=\s*"preconnect"[^>]+href\s*=\s*"([^"]+)"', webpage, 'Preconnect Link') + + video_details = self._download_json( + '{preconnect_link}/sections/videoDetails/{video_id}'.format(**locals()), video_id, 'Downloading Video Details', fatal=False) + + preplay_parameters = self._download_json( + '{preconnect_link}/videoPlayerData/{video_id}'.format(**locals()), video_id, 'Downloading Preplay Parameters')['preplayParameters'] + + content_data = self._download_json( + # 1. query string is expected to be sent as-is + # 2. `sig` must be appended + # 3. if absent, the call appears to work but the manifest is bad (404) + 'https://content.uplynk.com/preplay/{contentId}/multiple.json?{queryStr}&sig={signature}'.format(**preplay_parameters), + video_id, 'Downloading Content Data') + + # formats, subtitles = self._extract_m3u8_formats_and_subtitles(content_data['playURL'], video_id) + formats, subtitles = self._extract_m3u8_formats(content_data['playURL'], video_id, ext='mp4', entry_protocol='m3u8_native'), None + self._sort_formats(formats) + + return { + 'id': video_id, + 'title': video_details['title'], + 'description': video_details.get('description'), + 'duration': int_or_none(video_details.get('duration')), + 'release_timestamp': unified_timestamp(video_details.get('dateOfRelease')), + 'categories': traverse_obj(video_details, (('videoCategory', 'videoSubcategory'),)), + 'thumbnail': traverse_obj(video_details, ('backgroundImage', 'src')), + 'formats': formats, + 'subtitles': subtitles, + }
<details> <summary>Boilerplate: mixed code, new extractor</summary> ## 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 that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [x] [Searched](https://github.com/ytdl-org/youtube-dl/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Read [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) - [x] Read [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) and adjusted the code to meet them - [x] Covered the code with tests (note that PRs without tests will be REJECTED) - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) ### 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/), but the below applies to the majority of the code - [x] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (yt-dlp) ### What is the purpose of your *pull request*? - [ ] Bug fix - [ ] Improvement - [x] New extractor - [ ] New feature </details> --- ### Description of your *pull request* and other information Back-port of yt-dlp FIFA extractor as requested in #31365.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/31385
2022-11-29T18:58:27Z
2023-02-02T23:19:03Z
2023-02-02T23:19:03Z
2023-02-02T23:19:04Z
1,554
ytdl-org/youtube-dl
50,259
remove hangouts.users state, simplifies hangouts.conversations
diff --git a/homeassistant/components/hangouts/hangouts_bot.py b/homeassistant/components/hangouts/hangouts_bot.py index d4c5606799d9b5..d9ffb4cbace7da 100644 --- a/homeassistant/components/hangouts/hangouts_bot.py +++ b/homeassistant/components/hangouts/hangouts_bot.py @@ -195,23 +195,15 @@ async def _async_list_conversations(self): import hangups self._user_list, self._conversation_list = \ (await hangups.build_user_conversation_list(self._client)) - users = {} conversations = {} - for user in self._user_list.get_all(): - users[str(user.id_.chat_id)] = {'full_name': user.full_name, - 'is_self': user.is_self} - - for conv in self._conversation_list.get_all(): - users_in_conversation = {} + for i, conv in enumerate(self._conversation_list.get_all()): + users_in_conversation = [] for user in conv.users: - users_in_conversation[str(user.id_.chat_id)] = \ - {'full_name': user.full_name, 'is_self': user.is_self} - conversations[str(conv.id_)] = \ - {'name': conv.name, 'users': users_in_conversation} - - self.hass.states.async_set("{}.users".format(DOMAIN), - len(self._user_list.get_all()), - attributes=users) + users_in_conversation.append(user.full_name) + conversations[str(i)] = {'id': str(conv.id_), + 'name': conv.name, + 'users': users_in_conversation} + self.hass.states.async_set("{}.conversations".format(DOMAIN), len(self._conversation_list.get_all()), attributes=conversations)
## Description: removes the `hangouts.users` state, it is nice to read for devs, but completely useless for users and confusing. simplifies the hangouts.conversations, its reduced to the the id and name and a list of usernames of the conversation. ## Checklist: - [x] The code change is tested and works locally. - [x] Local tests pass with `tox`. **Your PR cannot be merged unless tests pass** If user exposed functionality or configuration variables are added/changed: - [ ] Documentation added/updated in [home-assistant.github.io](https://github.com/home-assistant/home-assistant.github.io) If the code communicates with devices, web services, or third-party tools: - [x] New dependencies have been added to the `REQUIREMENTS` variable ([example][ex-requir]). - [x] New dependencies are only imported inside functions that use them ([example][ex-import]). - [x] New or updated dependencies have been added to `requirements_all.txt` by running `script/gen_requirements_all.py`. - [x] New files were added to `.coveragerc`. If the code does not interact with devices: - [ ] Tests have been added to verify that the new code works. [ex-requir]: https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/keyboard.py#L14 [ex-import]: https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/keyboard.py#L54
https://api.github.com/repos/home-assistant/core/pulls/16191
2018-08-25T15:47:16Z
2018-08-26T19:28:43Z
2018-08-26T19:28:43Z
2018-12-10T15:21:42Z
402
home-assistant/core
39,135
http2: normalize headers before sending
diff --git a/mitmproxy/proxy/protocol/http2.py b/mitmproxy/proxy/protocol/http2.py index cdce24b38e..019159defc 100644 --- a/mitmproxy/proxy/protocol/http2.py +++ b/mitmproxy/proxy/protocol/http2.py @@ -97,7 +97,6 @@ def __init__(self, ctx, mode: str) -> None: client_side=False, header_encoding=False, validate_outbound_headers=False, - normalize_outbound_headers=False, validate_inbound_headers=False) self.connections[self.client_conn] = SafeH2Connection(self.client_conn, config=config) @@ -107,7 +106,6 @@ def _initiate_server_conn(self): client_side=True, header_encoding=False, validate_outbound_headers=False, - normalize_outbound_headers=False, validate_inbound_headers=False) self.connections[self.server_conn] = SafeH2Connection(self.server_conn, config=config) self.connections[self.server_conn].initiate_connection()
This might have prevented https://github.com/mitmproxy/mitmproxy/pull/2034.
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/2055
2017-02-23T11:53:50Z
2017-02-23T15:04:11Z
2017-02-23T15:04:11Z
2017-02-23T15:04:13Z
226
mitmproxy/mitmproxy
27,763
Revert "fix: added platform support for ghcr.io images to be run on Apple Sil…"
diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml index 76eef77f73..ac2b8f816c 100644 --- a/.github/workflows/docker-build.yaml +++ b/.github/workflows/docker-build.yaml @@ -52,7 +52,6 @@ jobs: - name: Build and push Docker image uses: docker/build-push-action@v3.2.0 with: - platforms: linux/amd64,linux/arm64,linux/arm/v7 file: ${{ inputs.dockerfile }} context: ${{ inputs.context }} build-args: ${{ inputs.build-args }}
Reverts LAION-AI/Open-Assistant#1763
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/2080
2023-03-15T19:13:20Z
2023-03-15T19:13:29Z
2023-03-15T19:13:29Z
2023-03-15T19:13:30Z
148
LAION-AI/Open-Assistant
37,383
Set correct Nginx server root on FreeBSD and Darwin
diff --git a/certbot-nginx/certbot_nginx/constants.py b/certbot-nginx/certbot_nginx/constants.py index 3f263fea3f5..dfc45120251 100644 --- a/certbot-nginx/certbot_nginx/constants.py +++ b/certbot-nginx/certbot_nginx/constants.py @@ -1,9 +1,14 @@ """nginx plugin constants.""" import pkg_resources +import platform +if platform.system() in ('FreeBSD', 'Darwin'): + server_root_tmp = "/usr/local/etc/nginx" +else: + server_root_tmp = "/etc/nginx" CLI_DEFAULTS = dict( - server_root="/etc/nginx", + server_root=server_root_tmp, ctl="nginx", ) """CLI defaults."""
Fork of #5862. This patch should be merged not squashed to preserve authorship.
https://api.github.com/repos/certbot/certbot/pulls/6020
2018-05-18T03:05:22Z
2018-05-21T23:53:12Z
2018-05-21T23:53:12Z
2018-06-06T21:49:01Z
176
certbot/certbot
318
Include mypy instructions in CONTRIBUTING.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e4c81a5ecd98..76ee1312f345 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -155,6 +155,8 @@ We want your work to be readable by others; therefore, we encourage you to note return a + b ``` + Instructions on how to install mypy can be found [here](https://github.com/python/mypy). Please use the command `mypy --ignore-missing-imports .` to test all files or `mypy --ignore-missing-imports path/to/file.py` to test a specific file. + - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.
### **Describe your change:** * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### **Checklist:** * [ ] 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. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] 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. * [ ] 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/4271
2021-03-19T06:40:10Z
2021-03-19T10:29:54Z
2021-03-19T10:29:54Z
2021-03-21T10:33:17Z
242
TheAlgorithms/Python
30,332
installbuilder: use own mirror
diff --git a/release/build.py b/release/build.py index f14adaf0f1..b1f44cafad 100644 --- a/release/build.py +++ b/release/build.py @@ -202,8 +202,8 @@ def installbuilder_installer(): """Windows: Build the InstallBuilder installer.""" _ensure_pyinstaller_onedir() - IB_VERSION = "22.10.0" - IB_SETUP_SHA256 = "49cbfc3ee8de02426abc0c1b92839934bdb0bf0ea12d88388dde9e4102fc429f" + IB_VERSION = "23.4.0" + IB_SETUP_SHA256 = "e4ff212ed962f9e0030d918b8a6e4d6dd8a9adc8bf8bc1833459351ee649eff3" IB_DIR = here / "installbuilder" IB_SETUP = IB_DIR / "setup" / f"{IB_VERSION}-installer.exe" IB_CLI = Path( @@ -221,7 +221,11 @@ def installbuilder_installer(): if not IB_CLI.exists(): if not IB_SETUP.exists(): - print("Downloading InstallBuilder...") + url = ( + f"https://github.com/mitmproxy/installbuilder-mirror/releases/download/" + f"{IB_VERSION}/installbuilder-enterprise-{IB_VERSION}-windows-x64-installer.exe" + ) + print(f"Downloading InstallBuilder from {url}...") def report(block, blocksize, total): done = block * blocksize @@ -230,7 +234,7 @@ def report(block, blocksize, total): tmp = IB_SETUP.with_suffix(".tmp") urllib.request.urlretrieve( - f"https://clients.bitrock.com/installbuilder/installbuilder-enterprise-{IB_VERSION}-windows-x64-installer.exe", + url, tmp, reporthook=report, )
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/6173
2023-06-14T10:45:33Z
2023-06-14T12:06:11Z
2023-06-14T12:06:11Z
2023-07-02T20:17:02Z
424
mitmproxy/mitmproxy
27,900
[MINOR] fix link in documentation
diff --git a/docs/pathod/test.rst b/docs/pathod/test.rst index cd6e8a29c5..b337795ae3 100644 --- a/docs/pathod/test.rst +++ b/docs/pathod/test.rst @@ -14,7 +14,7 @@ The canonical docs can be accessed using pydoc: >>> pydoc pathod.test The remainder of this page demonstrates some common interaction patterns using -<a href="http://nose.readthedocs.org/en/latest/">nose</a>. These examples are +`Nose`_. These examples are also applicable with only minor modification to most commonly used Python testing engines. @@ -33,3 +33,6 @@ One instance per test .. literalinclude:: ../../examples/pathod/test_setup.py :caption: examples/pathod/test_setup.py :language: python + + +.. _Nose: https://nose.readthedocs.org/en/latest/
Fix Nose link in pathod test documentation. Current: http://docs.mitmproxy.org/en/stable/pathod/test.html Fixed: http://imgur.com/a/aRDZS
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/1712
2016-11-03T21:38:50Z
2016-11-03T21:57:28Z
2016-11-03T21:57:28Z
2016-11-03T22:28:20Z
209
mitmproxy/mitmproxy
27,616
Add Qwen adapter support
diff --git a/docs/model_support.md b/docs/model_support.md index 5f9b349319..21ff29a98d 100644 --- a/docs/model_support.md +++ b/docs/model_support.md @@ -31,6 +31,7 @@ - [WizardLM/WizardLM-13B-V1.0](https://huggingface.co/WizardLM/WizardLM-13B-V1.0) - [baichuan-inc/baichuan-7B](https://huggingface.co/baichuan-inc/baichuan-7B) - [internlm/internlm-chat-7b](https://huggingface.co/internlm/internlm-chat-7b) +- [Qwen/Qwen-7B-Chat](https://huggingface.co/Qwen/Qwen-7B-Chat) - [HuggingFaceH4/starchat-beta](https://huggingface.co/HuggingFaceH4/starchat-beta) - 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 diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 71d92b97bb..e5456a829d 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -897,6 +897,28 @@ def get_conv_template(name: str) -> Conversation: ) +# Qwen-chat default template +# source: https://huggingface.co/Qwen/Qwen-7B-Chat/blob/main/qwen_generation_utils.py#L130 +register_conv_template( + Conversation( + name="qwen-7b-chat", + system_template="<|im_start|>system\n{system_message}", + system_message="You are a helpful assistant.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[ + 151643, + 151644, + 151645, + ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>" + stop_str="<|endoftext|>", + ) +) + + if __name__ == "__main__": print("Vicuna template:") conv = get_conv_template("vicuna_v1.1") diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index 569c9b1287..efe7c23501 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -1263,6 +1263,52 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("open-orca") +class QwenChatAdapter(BaseModelAdapter): + """The model adapter for Qwen/Qwen-7B-Chat + To run this model, you need to ensure additional flash attention installation: + ``` bash + git clone https://github.com/Dao-AILab/flash-attention + cd flash-attention && pip install . + pip install csrc/layer_norm + pip install csrc/rotary + ``` + + Since from 2.0, the following change happened + - `flash_attn_unpadded_func` -> `flash_attn_varlen_func` + - `flash_attn_unpadded_qkvpacked_func` -> `flash_attn_varlen_qkvpacked_func` + - `flash_attn_unpadded_kvpacked_func` -> `flash_attn_varlen_kvpacked_func` + You may need to revise the code in: https://huggingface.co/Qwen/Qwen-7B-Chat/blob/main/modeling_qwen.py#L69 + to from flash_attn.flash_attn_interface import flash_attn_varlen_func as flash_attn_unpadded_func + """ + + def match(self, model_path: str): + return "qwen" in model_path.lower() + + def load_model(self, model_path: str, from_pretrained_kwargs: dict): + from transformers.generation import GenerationConfig + + revision = from_pretrained_kwargs.get("revision", "main") + model = AutoModelForCausalLM.from_pretrained( + model_path, + low_cpu_mem_usage=True, + trust_remote_code=True, + fp16=True, + **from_pretrained_kwargs, + ).eval() + model.generation_config = GenerationConfig.from_pretrained( + model_path, trust_remote_code=True + ) + if hasattr(model.config, "use_dynamic_ntk") and model.config.use_dynamic_ntk: + model.config.max_sequence_length = 16384 + tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True, revision=revision + ) + return model, tokenizer + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("qwen-7b-chat") + + # Note: the registration order matters. # The one registered earlier has a higher matching priority. register_model_adapter(PeftModelAdapter) @@ -1309,6 +1355,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: register_model_adapter(Llama2Adapter) register_model_adapter(CuteGPTAdapter) register_model_adapter(OpenOrcaAdapter) +register_model_adapter(QwenChatAdapter) # 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 f507b4fda1..d89fbafde0 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -236,3 +236,9 @@ def get_model_info(name: str) -> ModelInfo: "https://huggingface.co/internlm/internlm-chat-7b", "InternLM is a multi-language large-scale language model (LLM), developed by SHLAB.", ) +register_model_info( + ["Qwen-7B-Chat"], + "Qwen", + "https://huggingface.co/Qwen/Qwen-7B-Chat", + "Qwen is a multi-language large-scale language model (LLM), developed by Damo Academy.", +)
<!-- 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? 1. Support new model <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number (if applicable) <!-- For example: "Closes #1234" --> ## Checks - [x] 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/2153
2023-08-04T07:17:40Z
2023-08-08T10:19:27Z
2023-08-08T10:19:27Z
2023-08-09T02:48:26Z
1,480
lm-sys/FastChat
41,124
CI: add Twine check in check workflow
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index b26f344ffb0..e515959ad04 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -25,6 +25,9 @@ jobs: - python-version: "3.10" # Keep in sync with .readthedocs.yml env: TOXENV: docs + - python-version: "3.10" + env: + TOXENV: twinecheck steps: - uses: actions/checkout@v2 diff --git a/tox.ini b/tox.ini index 2bf9454d0c3..2d94ba78f0d 100644 --- a/tox.ini +++ b/tox.ini @@ -71,6 +71,14 @@ deps = commands = pylint conftest.py docs extras scrapy setup.py tests +[testenv:twinecheck] +basepython = python3 +deps = + twine==4.0.1 +commands = + python setup.py sdist + twine check dist/* + [pinned] deps = cryptography==3.3
Closes: #5655
https://api.github.com/repos/scrapy/scrapy/pulls/5656
2022-10-02T14:18:39Z
2022-10-03T12:00:35Z
2022-10-03T12:00:35Z
2022-10-03T12:00:35Z
276
scrapy/scrapy
34,254
Action: Support running in a docker container
diff --git a/CHANGES.md b/CHANGES.md index cb637d94c11..a687f3090bf 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,10 @@ - All upper version bounds on dependencies have been removed (#2718) +### Integrations + +- Update GitHub action to support containerized runs (#2748) + ## 21.12b0 ### _Black_ diff --git a/action.yml b/action.yml index ddf07933a3e..dd2de1b62ad 100644 --- a/action.yml +++ b/action.yml @@ -38,7 +38,7 @@ runs: import subprocess; from pathlib import Path; - MAIN_SCRIPT = Path(r'${{ github.action_path }}') / 'action' / 'main.py'; + MAIN_SCRIPT = Path(r'${GITHUB_ACTION_PATH}') / 'action' / 'main.py'; proc = subprocess.run([sys.executable, str(MAIN_SCRIPT)]); sys.exit(proc.returncode)
`${{ github.action_path }}` doesn't point to the correct path when run in a docker container, you have to use the environmental variable `GITHUB_ACTION_PATH` https://github.com/actions/runner/issues/716 <!-- Hello! Thanks for submitting a PR. To help make things go a bit more smoothly we would appreciate that you go through this template. --> ### Description <!-- Good things to put here include: reasoning for the change (please link any relevant issues!), any noteworthy (or hacky) choices to be aware of, or what the problem resolved here looked like ... we won't mind a ranty story :) --> ### Checklist - did you ... <!-- If any of the following items aren't relevant for your contribution please still tick them so we know you've gone through the checklist. All user-facing changes should get an entry. Otherwise, signal to us this should get the magical label to silence the CHANGELOG entry check. Tests are required for bugfixes and new features. Documentation changes are necessary for formatting and most enhancement changes. --> - [ ] Add a CHANGELOG entry if necessary? - [ ] Add / update tests if necessary? - [ ] Add new / update outdated documentation? <!-- Just as a reminder, everyone in all psf/black spaces including PRs must follow the PSF Code of Conduct (link below). Finally, once again thanks for your time and effort. If you have any feedback in regards to your experience contributing here, please let us know! Helpful links: PSF COC: https://www.python.org/psf/conduct/ Contributing docs: https://black.readthedocs.io/en/latest/contributing/index.html Chat on Python Discord: https://discord.gg/RtVdv86PrH -->
https://api.github.com/repos/psf/black/pulls/2748
2022-01-05T06:59:55Z
2022-01-07T16:50:50Z
2022-01-07T16:50:50Z
2022-01-07T17:10:28Z
238
psf/black
24,311
Standardize capitalization.
diff --git a/README.md b/README.md index 9337c587..404e8c9d 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ For a list of free machine learning books available for download, go [here](http <a name="cpp-general-purpose" /> #### General-Purpose Machine Learning -* [MLPack](http://www.mlpack.org/) - A scalable C++ machine learning library +* [mlpack](http://www.mlpack.org/) - A scalable C++ machine learning library * [DLib](http://dlib.net/ml.html) - A suite of ML tools designed to be easy to imbed in other applications * [encog-cpp](https://code.google.com/p/encog-cpp/) * [shark](http://image.diku.dk/shark/sphinx_pages/build/html/index.html)
Hi there, This fix just brings the capitalization in line with what the mlpack project uses. I hope it is helpful. :) Thanks!
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/244
2016-02-04T14:36:54Z
2016-02-04T14:42:40Z
2016-02-04T14:42:40Z
2016-02-04T14:42:40Z
199
josephmisiti/awesome-machine-learning
52,504