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 |
|---|---|---|---|---|---|---|---|---|---|---|
Upgrade pipstrap to 1.5.1 | diff --git a/letsencrypt-auto-source/letsencrypt-auto b/letsencrypt-auto-source/letsencrypt-auto
index 9ff1c1386ba..f97dc078d2c 100755
--- a/letsencrypt-auto-source/letsencrypt-auto
+++ b/letsencrypt-auto-source/letsencrypt-auto
@@ -1216,7 +1216,7 @@ UNLIKELY_EOF
# -------------------------------------------------------------------------
cat << "UNLIKELY_EOF" > "$TEMP_DIR/pipstrap.py"
#!/usr/bin/env python
-"""A small script that can act as a trust root for installing pip 8
+"""A small script that can act as a trust root for installing pip >=8
Embed this in your project, and your VCS checkout is all you have to trust. In
a post-peep era, this lets you claw your way to a hash-checking version of pip,
@@ -1274,7 +1274,7 @@ except ImportError:
from urllib.parse import urlparse # 3.4
-__version__ = 1, 5, 0
+__version__ = 1, 5, 1
PIP_VERSION = '9.0.1'
DEFAULT_INDEX_BASE = 'https://pypi.python.org'
@@ -1287,14 +1287,11 @@ maybe_argparse = (
if version_info < (2, 7, 0) else [])
-# Pip has no dependencies, as it vendors everything:
-PIP_PACKAGE = [
+PACKAGES = maybe_argparse + [
+ # Pip has no dependencies, as it vendors everything:
('11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/'
'pip-{0}.tar.gz'.format(PIP_VERSION),
- '09f243e1a7b461f654c26a725fa373211bb7ff17a9300058b205c61658ca940d')]
-
-
-OTHER_PACKAGES = maybe_argparse + [
+ '09f243e1a7b461f654c26a725fa373211bb7ff17a9300058b205c61658ca940d'),
# This version of setuptools has only optional dependencies:
('59/88/2f3990916931a5de6fa9706d6d75eb32ee8b78627bb2abaab7ed9e6d0622/'
'setuptools-29.0.1.tar.gz',
@@ -1379,21 +1376,16 @@ def main():
index_base = get_index_base()
temp = mkdtemp(prefix='pipstrap-')
try:
- # We download and install pip first, then the rest, to avoid the bug
- # https://github.com/certbot/certbot/issues/4938.
- pip_downloads, other_downloads = [
- [hashed_download(index_base + '/packages/' + path,
- temp,
- digest)
- for path, digest in packages]
- for packages in (PIP_PACKAGE, OTHER_PACKAGES)]
- for downloads in (pip_downloads, other_downloads):
- check_output('pip install --no-index --no-deps -U ' +
- # Disable cache since we're not using it and it
- # otherwise sometimes throws permission warnings:
- ('--no-cache-dir ' if has_pip_cache else '') +
- ' '.join(quote(d) for d in downloads),
- shell=True)
+ downloads = [hashed_download(index_base + '/packages/' + path,
+ temp,
+ digest)
+ for path, digest in PACKAGES]
+ check_output('pip install --no-index --no-deps -U ' +
+ # Disable cache since we're not using it and it otherwise
+ # sometimes throws permission warnings:
+ ('--no-cache-dir ' if has_pip_cache else '') +
+ ' '.join(quote(d) for d in downloads),
+ shell=True)
except HashError as exc:
print(exc)
except Exception:
diff --git a/letsencrypt-auto-source/pieces/pipstrap.py b/letsencrypt-auto-source/pieces/pipstrap.py
index ed55b37e9af..d55d5bcebe5 100755
--- a/letsencrypt-auto-source/pieces/pipstrap.py
+++ b/letsencrypt-auto-source/pieces/pipstrap.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-"""A small script that can act as a trust root for installing pip 8
+"""A small script that can act as a trust root for installing pip >=8
Embed this in your project, and your VCS checkout is all you have to trust. In
a post-peep era, this lets you claw your way to a hash-checking version of pip,
@@ -57,7 +57,7 @@ def check_output(*popenargs, **kwargs):
from urllib.parse import urlparse # 3.4
-__version__ = 1, 5, 0
+__version__ = 1, 5, 1
PIP_VERSION = '9.0.1'
DEFAULT_INDEX_BASE = 'https://pypi.python.org'
@@ -70,14 +70,11 @@ def check_output(*popenargs, **kwargs):
if version_info < (2, 7, 0) else [])
-# Pip has no dependencies, as it vendors everything:
-PIP_PACKAGE = [
+PACKAGES = maybe_argparse + [
+ # Pip has no dependencies, as it vendors everything:
('11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/'
'pip-{0}.tar.gz'.format(PIP_VERSION),
- '09f243e1a7b461f654c26a725fa373211bb7ff17a9300058b205c61658ca940d')]
-
-
-OTHER_PACKAGES = maybe_argparse + [
+ '09f243e1a7b461f654c26a725fa373211bb7ff17a9300058b205c61658ca940d'),
# This version of setuptools has only optional dependencies:
('59/88/2f3990916931a5de6fa9706d6d75eb32ee8b78627bb2abaab7ed9e6d0622/'
'setuptools-29.0.1.tar.gz',
@@ -162,21 +159,16 @@ def main():
index_base = get_index_base()
temp = mkdtemp(prefix='pipstrap-')
try:
- # We download and install pip first, then the rest, to avoid the bug
- # https://github.com/certbot/certbot/issues/4938.
- pip_downloads, other_downloads = [
- [hashed_download(index_base + '/packages/' + path,
- temp,
- digest)
- for path, digest in packages]
- for packages in (PIP_PACKAGE, OTHER_PACKAGES)]
- for downloads in (pip_downloads, other_downloads):
- check_output('pip install --no-index --no-deps -U ' +
- # Disable cache since we're not using it and it
- # otherwise sometimes throws permission warnings:
- ('--no-cache-dir ' if has_pip_cache else '') +
- ' '.join(quote(d) for d in downloads),
- shell=True)
+ downloads = [hashed_download(index_base + '/packages/' + path,
+ temp,
+ digest)
+ for path, digest in PACKAGES]
+ check_output('pip install --no-index --no-deps -U ' +
+ # Disable cache since we're not using it and it otherwise
+ # sometimes throws permission warnings:
+ ('--no-cache-dir ' if has_pip_cache else '') +
+ ' '.join(quote(d) for d in downloads),
+ shell=True)
except HashError as exc:
print(exc)
except Exception:
| Brings https://github.com/erikrose/pipstrap/pull/18 to Certbot by upgrading `pipstrap` to 1.5.1. The release tag is https://github.com/erikrose/pipstrap/blob/1.5.1/pipstrap.py. | https://api.github.com/repos/certbot/certbot/pulls/5681 | 2018-03-07T16:46:57Z | 2018-03-07T17:10:48Z | 2018-03-07T17:10:48Z | 2018-03-07T17:11:06Z | 1,779 | certbot/certbot | 1,246 |
System stats endpoint | diff --git a/comfy/model_management.py b/comfy/model_management.py
index e9af7f3a70..0ea0c71e50 100644
--- a/comfy/model_management.py
+++ b/comfy/model_management.py
@@ -308,6 +308,33 @@ def pytorch_attention_flash_attention():
return True
return False
+def get_total_memory(dev=None, torch_total_too=False):
+ global xpu_available
+ global directml_enabled
+ if dev is None:
+ dev = get_torch_device()
+
+ if hasattr(dev, 'type') and (dev.type == 'cpu' or dev.type == 'mps'):
+ mem_total = psutil.virtual_memory().total
+ else:
+ if directml_enabled:
+ mem_total = 1024 * 1024 * 1024 #TODO
+ mem_total_torch = mem_total
+ elif xpu_available:
+ mem_total = torch.xpu.get_device_properties(dev).total_memory
+ mem_total_torch = mem_total
+ else:
+ stats = torch.cuda.memory_stats(dev)
+ mem_reserved = stats['reserved_bytes.all.current']
+ _, mem_total_cuda = torch.cuda.mem_get_info(dev)
+ mem_total_torch = mem_reserved
+ mem_total = mem_total_cuda
+
+ if torch_total_too:
+ return (mem_total, mem_total_torch)
+ else:
+ return mem_total
+
def get_free_memory(dev=None, torch_free_too=False):
global xpu_available
global directml_enabled
diff --git a/server.py b/server.py
index 0b64df147b..acbc88f66e 100644
--- a/server.py
+++ b/server.py
@@ -7,6 +7,7 @@
import uuid
import json
import glob
+import torch
from PIL import Image
from io import BytesIO
@@ -23,6 +24,7 @@
import mimetypes
from comfy.cli_args import args
import comfy.utils
+import comfy.model_management
@web.middleware
async def cache_control(request: web.Request, handler):
@@ -280,6 +282,28 @@ async def view_metadata(request):
return web.Response(status=404)
return web.json_response(dt["__metadata__"])
+ @routes.get("/system_stats")
+ async def get_queue(request):
+ device_index = comfy.model_management.get_torch_device()
+ device = torch.device(device_index)
+ device_name = comfy.model_management.get_torch_device_name(device_index)
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
+ system_stats = {
+ "devices": [
+ {
+ "name": device_name,
+ "type": device.type,
+ "index": device.index,
+ "vram_total": vram_total,
+ "vram_free": vram_free,
+ "torch_vram_total": torch_vram_total,
+ "torch_vram_free": torch_vram_free,
+ }
+ ]
+ }
+ return web.json_response(system_stats)
+
@routes.get("/prompt")
async def get_prompt(request):
return web.json_response(self.get_queue_info())
| https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/726 | 2023-06-02T04:26:47Z | 2023-06-02T19:23:07Z | 2023-06-02T19:23:07Z | 2023-06-02T19:23:07Z | 739 | comfyanonymous/ComfyUI | 17,779 | |
Print EarlyStopping verbose message on_train_end. | diff --git a/keras/callbacks.py b/keras/callbacks.py
index c3f7378f23c..b44236b4f1e 100644
--- a/keras/callbacks.py
+++ b/keras/callbacks.py
@@ -337,6 +337,7 @@ def __init__(self, monitor='val_loss', min_delta=0, patience=0, verbose=0, mode=
self.verbose = verbose
self.min_delta = min_delta
self.wait = 0
+ self.stopped_epoch = 0
if mode not in ['auto', 'min', 'max']:
warnings.warn('EarlyStopping mode %s is unknown, '
@@ -374,11 +375,14 @@ def on_epoch_end(self, epoch, logs={}):
self.wait = 0
else:
if self.wait >= self.patience:
- if self.verbose > 0:
- print('Epoch %05d: early stopping' % (epoch))
+ self.stopped_epoch = epoch
self.model.stop_training = True
self.wait += 1
+ def on_train_end(self, logs={}):
+ if self.stopped_epoch > 0 and self.verbose > 0:
+ print('Epoch %05d: early stopping' % (self.stopped_epoch))
+
class RemoteMonitor(Callback):
'''Callback used to stream events to a server.
| The message print EarlyStopping.on_epoch_end would be overwritten by ProgbarLogger.
I've found https://github.com/fchollet/keras/issues/2354 and the comment on https://github.com/fchollet/keras/pull/3195 and I understood print() in callback is bad idea if you use ProgbarLogger. But EarlyStopping is built-in class. I think EarlyStopping should work fine with ProgbarLogger.
I think printing in on_train_end callback is safe with ProgbarLogger.
In fact with this patch, EarlyStopping(verbose=1) can show its message like below.
```
Epoch 1/100
54000/54000 [==============================] - 2s - loss: 1.1670 - acc: 0.5984 - val_loss: 0.4293 - val_acc: 0.8937
Epoch 2/100
54000/54000 [==============================] - 2s - loss: 0.8022 - acc: 0.7288 - val_loss: 0.3453 - val_acc: 0.9102
Epoch 3/100
54000/54000 [==============================] - 2s - loss: 0.7428 - acc: 0.7502 - val_loss: 0.3219 - val_acc: 0.9170
Epoch 4/100
54000/54000 [==============================] - 2s - loss: 0.6987 - acc: 0.7648 - val_loss: 0.3231 - val_acc: 0.9168
Epoch 00003: early stopping
```
| https://api.github.com/repos/keras-team/keras/pulls/4332 | 2016-11-09T15:14:27Z | 2016-11-10T00:35:22Z | 2016-11-10T00:35:22Z | 2016-11-10T12:41:46Z | 308 | keras-team/keras | 47,555 |
[runner/launch] propagate the error | diff --git a/deepspeed/launcher/runner.py b/deepspeed/launcher/runner.py
index 6ce482060358..ac873f4ca3f4 100755
--- a/deepspeed/launcher/runner.py
+++ b/deepspeed/launcher/runner.py
@@ -359,6 +359,12 @@ def main(args=None):
result = subprocess.Popen(cmd, env=env)
result.wait()
+ # In case of failure must propagate the error-condition back to the caller (usually shell). The
+ # actual error and traceback should have been printed in the subprocess, so in order to avoid
+ # unnecessary noise we just quietly exit here with the same code as the subprocess
+ if result.returncode > 0:
+ sys.exit(result.returncode)
+
if __name__ == "__main__":
main()
| Currently when the launcher terminates due to one of the failing sub-processes, the runner doesn't propagate the error back to the caller. So it results in `exit(0)`. This is a problem in tests, a test fails but the sub-process launching `deepspeed` doesn't get the error back. This PR fixes it by exiting with the same error code.
Notes:
- I'm not sure if exit is the best approach - I originally coded it as:
```
if result.returncode > 0:
cmd_str = " ".join(cmd)
raise RuntimeError(
f"'{cmd_str}' failed with returncode {result.returncode}\n"
)
```
But then we end up with 2 errors - one from the sub-process, another from the runner. For example:
```
IndexError: list index out of range
Killing subprocess 3232868
Killing subprocess 3232869
Traceback (most recent call last):
File "/home/stas/anaconda3/envs/main-38/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/home/stas/anaconda3/envs/main-38/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 171, in <module>
main()
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 161, in main
sigkill_handler(signal.SIGTERM, None) # not coming back
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 139, in sigkill_handler
raise subprocess.CalledProcessError(returncode=last_return_code, cmd=cmd)
subprocess.CalledProcessError: Command '['/home/stas/anaconda3/envs/main-38/bin/python', '-u', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/seq2seq/run_seq2seq.py', '--local_rank=1', '--model_name_or_path', 't5-small', '--train_file', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/train.json', '--validation_file', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/val.json', '--output_dir', '/tmp/zero3', '--overwrite_output_dir', '--max_source_length', '32', '--max_target_length', '32', '--val_max_target_length', '32', '--warmup_steps', '8', '--predict_with_generate', '--logging_steps', '0', '--save_steps', '0', '--eval_steps', '10', '--group_by_length', '--label_smoothing_factor', '0.1', '--adafactor', '--dataset_name', 'wmt16', '--dataset_config', 'ro-en', '--task', 'translation_en_to_ro', '--source_prefix', 'translate English to Romanian: ', '--do_train', '--num_train_epochs', '1', '--max_train_samples', '100', '--per_device_train_batch_size', '2', '--learning_rate', '3e-3', '--do_eval', '--max_val_samples', '100', '--per_device_eval_batch_size', '2', '--deepspeed', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/tests/deepspeed/ds_config.json']' returned non-zero exit status 1.
Traceback (most recent call last):
File "/home/stas/anaconda3/envs/main-38/bin/deepspeed", line 7, in <module>
exec(compile(f.read(), __file__, 'exec'))
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/bin/deepspeed", line 9, in <module>
main()
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/runner.py", line 367, in main
raise RuntimeError(
RuntimeError: '/home/stas/anaconda3/envs/main-38/bin/python -u -m deepspeed.launcher.launch --world_info=eyJsb2NhbGhvc3QiOiBbMCwgMV19 --master_addr=127.0.0.1 --master_port=29500 /mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/seq2seq/run_seq2seq.py --model_name_or_path t5-small --train_file /mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/train.json --validation_file /mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/val.json --output_dir /tmp/zero3 --overwrite_output_dir --max_source_length 32 --max_target_length 32 --val_max_target_length 32 --warmup_steps 8 --predict_with_generate --logging_steps 0 --save_steps 0 --eval_steps 10 --group_by_length --label_smoothing_factor 0.1 --adafactor --dataset_name wmt16 --dataset_config ro-en --task translation_en_to_ro --source_prefix translate English to Romanian: --do_train --num_train_epochs 1 --max_train_samples 100 --per_device_train_batch_size 2 --learning_rate 3e-3 --do_eval --max_val_samples 100 --per_device_eval_batch_size 2 --deepspeed /mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/tests/deepspeed/ds_config.json' failed with returncode 1
```
with the PR's way we only get:
```
IndexError: list index out of range
Killing subprocess 3232868
Killing subprocess 3232869
Traceback (most recent call last):
File "/home/stas/anaconda3/envs/main-38/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/home/stas/anaconda3/envs/main-38/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 171, in <module>
main()
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 161, in main
sigkill_handler(signal.SIGTERM, None) # not coming back
File "/mnt/nvme1/code/github/00optimize/DeepSpeed/deepspeed/launcher/launch.py", line 139, in sigkill_handler
raise subprocess.CalledProcessError(returncode=last_return_code, cmd=cmd)
subprocess.CalledProcessError: Command '['/home/stas/anaconda3/envs/main-38/bin/python', '-u', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/seq2seq/run_seq2seq.py', '--local_rank=1', '--model_name_or_path', 't5-small', '--train_file', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/train.json', '--validation_file', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/test_data/wmt_en_ro/val.json', '--output_dir', '/tmp/zero3', '--overwrite_output_dir', '--max_source_length', '32', '--max_target_length', '32', '--val_max_target_length', '32', '--warmup_steps', '8', '--predict_with_generate', '--logging_steps', '0', '--save_steps', '0', '--eval_steps', '10', '--group_by_length', '--label_smoothing_factor', '0.1', '--adafactor', '--dataset_name', 'wmt16', '--dataset_config', 'ro-en', '--task', 'translation_en_to_ro', '--source_prefix', 'translate English to Romanian: ', '--do_train', '--num_train_epochs', '1', '--max_train_samples', '100', '--per_device_train_batch_size', '2', '--learning_rate', '3e-3', '--do_eval', '--max_val_samples', '100', '--per_device_eval_batch_size', '2', '--deepspeed', '/mnt/nvme1/code/huggingface/transformers-ds-zero-3/examples/tests/deepspeed/ds_config.json']' returned non-zero exit status 1.
```
which is exactly the same as it behaves before this PR, plus the program returns with non-zero exit code, and thus the failure can be caught.
| https://api.github.com/repos/microsoft/DeepSpeed/pulls/854 | 2021-03-12T06:45:02Z | 2021-03-16T16:23:45Z | 2021-03-16T16:23:45Z | 2021-03-16T16:29:02Z | 188 | microsoft/DeepSpeed | 10,225 |
Disable verbose in K8S Tests | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d86d771745b91..5bf2e916e21e5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1726,6 +1726,7 @@ jobs:
KUBERNETES_VERSIONS: ${{needs.build-info.outputs.kubernetes-versions-list-as-string}}
EXECUTOR: ${{matrix.executor}}
USE_STANDARD_NAMING: ${{matrix.use-standard-naming}}
+ VERBOSE: "false"
- name: Upload KinD logs on failure ${{needs.build-info.outputs.kubernetes-combos-list-as-string}}
uses: actions/upload-artifact@v3
if: failure() || cancelled()
| The verbose output is ... too verbose - it does not give much of an information and it clutters the progress information.
It's been enabled recently to test some failures but we can disable it now.
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
Thank you for contributing! Please make sure that your code changes
are covered with tests. And in case of new features or big changes
remember to adjust the documentation.
Feel free to ping committers for the review!
In case of an existing issue, reference it using one of the following:
closes: #ISSUE
related: #ISSUE
How to write a good git commit message:
http://chris.beams.io/posts/git-commit/
-->
<!-- Please keep an empty line above the dashes. -->
---
**^ Add meaningful description above**
Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
| https://api.github.com/repos/apache/airflow/pulls/35441 | 2023-11-04T17:58:18Z | 2023-11-04T18:01:28Z | 2023-11-04T18:01:28Z | 2023-11-20T15:07:48Z | 174 | apache/airflow | 14,754 |
Remove pos unsqueeze(0) | diff --git a/model.py b/model.py
index 1e5e1fdec..ae90db6b1 100644
--- a/model.py
+++ b/model.py
@@ -178,11 +178,11 @@ def forward(self, idx, targets=None):
device = idx.device
b, t = idx.size()
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
- pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) # shape (1, t)
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
# forward the GPT model itself
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
- pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, n_embd)
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
x = self.transformer.drop(tok_emb + pos_emb)
for block in self.transformer.h:
x = block(x)
| Adding fake batch dim with size 1 to `pos` tensor is not needed.
`tok_emb + pos_emb` works fine. Broadcast works.
`tok_emb` - shape `(b, t, n_embd)`
`pos_emb ` - shape `(t, n_embd)` | https://api.github.com/repos/karpathy/nanoGPT/pulls/275 | 2023-05-17T02:35:04Z | 2023-06-14T22:38:46Z | 2023-06-14T22:38:46Z | 2023-06-14T22:38:59Z | 268 | karpathy/nanoGPT | 40,963 |
Add more useful usage instructions for all subcommands | diff --git a/certbot/cli.py b/certbot/cli.py
index a74b506365d..533acb4b2b1 100644
--- a/certbot/cli.py
+++ b/certbot/cli.py
@@ -357,7 +357,8 @@ def _get_help_string(self, action):
}),
("delete", {
"short": "Clean up all files related to a certificate",
- "opts": "Options for deleting a certificate"
+ "opts": "Options for deleting a certificate",
+ "usage": "\n\n certbot delete --cert-name CERTNAME\n\n"
}),
("revoke", {
"short": "Revoke a certificate specified with --cert-path",
@@ -366,33 +367,41 @@ def _get_help_string(self, action):
}),
("register", {
"short": "Register for account with Let's Encrypt / other ACME server",
- "opts": "Options for account registration & modification"
+ "opts": "Options for account registration & modification",
+ "usage": "\n\n certbot register --email user@example.com [options]\n\n"
}),
("unregister", {
"short": "Irrevocably deactivate your account",
- "opts": "Options for account deactivation."
+ "opts": "Options for account deactivation.",
+ "usage": "\n\n certbot unregister [options]\n\n"
}),
("install", {
"short": "Install an arbitrary certificate in a server",
- "opts": "Options for modifying how a certificate is deployed"
+ "opts": "Options for modifying how a certificate is deployed",
+ "usage": "\n\n certbot install --cert-path /path/to/fullchain.pem "
+ " --key-path /path/to/private-key [options]\n\n"
}),
("config_changes", {
"short": "Show changes that Certbot has made to server configurations",
- "opts": "Options for controlling which changes are displayed"
+ "opts": "Options for controlling which changes are displayed",
+ "usage": "\n\n certbot config_changes --num NUM [options]\n\n"
}),
("rollback", {
"short": "Roll back server conf changes made during certificate installation",
- "opts": "Options for rolling back server configuration changes"
+ "opts": "Options for rolling back server configuration changes",
+ "usage": "\n\n certbot rollback --checkpoints 3 [options]\n\n"
}),
("plugins", {
"short": "List plugins that are installed and available on your system",
- "opts": 'Options for for the "plugins" subcommand'
+ "opts": 'Options for for the "plugins" subcommand',
+ "usage": "\n\n certbot plugins [options]\n\n"
}),
("update_symlinks", {
"short": "Recreate symlinks in your /etc/letsencrypt/live/ directory",
"opts": ("Recreates certificate and key symlinks in {0}, if you changed them by hand "
"or edited a renewal configuration file".format(
- os.path.join(flag_default("config_dir"), "live")))
+ os.path.join(flag_default("config_dir"), "live"))),
+ "usage": "\n\n certbot update_symlinks [options]\n\n"
}),
]
| Fixes #3875. | https://api.github.com/repos/certbot/certbot/pulls/4710 | 2017-05-22T20:40:55Z | 2017-06-12T15:12:42Z | 2017-06-12T15:12:42Z | 2017-06-12T15:12:42Z | 744 | certbot/certbot | 755 |
Bump github/codeql-action from 3.23.0 to 3.24.0 | diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index c03a8a7ca8..26a4348a4b 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -45,7 +45,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@e5f05b81d5b6ff8cfa111c80c22c5fd02a384118 # v3.23.0
+ uses: github/codeql-action/init@e8893c57a1f3a2b659b6b55564fdfdbbd2982911 # v3.24.0
with:
languages: "python"
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -56,7 +56,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
- uses: github/codeql-action/autobuild@e5f05b81d5b6ff8cfa111c80c22c5fd02a384118 # v3.23.0
+ uses: github/codeql-action/autobuild@e8893c57a1f3a2b659b6b55564fdfdbbd2982911 # v3.24.0
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -70,4 +70,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@e5f05b81d5b6ff8cfa111c80c22c5fd02a384118 # v3.23.0
+ uses: github/codeql-action/analyze@e8893c57a1f3a2b659b6b55564fdfdbbd2982911 # v3.24.0
| Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.23.0 to 3.24.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/github/codeql-action/blob/main/CHANGELOG.md">github/codeql-action's changelog</a>.</em></p>
<blockquote>
<h1>CodeQL Action Changelog</h1>
<p>See the <a href="https://github.com/github/codeql-action/releases">releases page</a> for the relevant changes to the CodeQL CLI and language packs.</p>
<p>Note that the only difference between <code>v2</code> and <code>v3</code> of the CodeQL Action is the node version they support, with <code>v3</code> running on node 20 while we continue to release <code>v2</code> to support running on node 16. For example <code>3.22.11</code> was the first <code>v3</code> release and is functionally identical to <code>2.22.11</code>. This approach ensures an easy way to track exactly which features are included in different versions, indicated by the minor and patch version numbers.</p>
<h2>[UNRELEASED]</h2>
<p>No user facing changes.</p>
<h2>3.24.0 - 02 Feb 2024</h2>
<ul>
<li>CodeQL Python analysis will no longer install dependencies on GitHub Enterprise Server, as is already the case for GitHub.com. See <a href="https://github.com/github/codeql-action/blob/main/#3230---08-jan-2024">release notes for 3.23.0</a> for more details. <a href="https://redirect.github.com/github/codeql-action/pull/2106">#2106</a></li>
</ul>
<h2>3.23.2 - 26 Jan 2024</h2>
<ul>
<li>On Linux, the maximum possible value for the <code>--threads</code> option now respects the CPU count as specified in <code>cgroup</code> files to more accurately reflect the number of available cores when running in containers. <a href="https://redirect.github.com/github/codeql-action/pull/2083">#2083</a></li>
<li>Update default CodeQL bundle version to 2.16.1. <a href="https://redirect.github.com/github/codeql-action/pull/2096">#2096</a></li>
</ul>
<h2>3.23.1 - 17 Jan 2024</h2>
<ul>
<li>Update default CodeQL bundle version to 2.16.0. <a href="https://redirect.github.com/github/codeql-action/pull/2073">#2073</a></li>
<li>Change the retention period for uploaded debug artifacts to 7 days. Previously, this was whatever the repository default was. <a href="https://redirect.github.com/github/codeql-action/pull/2079">#2079</a></li>
</ul>
<h2>3.23.0 - 08 Jan 2024</h2>
<ul>
<li>We are rolling out a feature in January 2024 that will disable Python dependency installation by default for all users. This improves the speed of analysis while having only a very minor impact on results. You can override this behavior by setting <code>CODEQL_ACTION_DISABLE_PYTHON_DEPENDENCY_INSTALLATION=false</code> in your workflow, however we plan to remove this ability in future versions of the CodeQL Action. <a href="https://redirect.github.com/github/codeql-action/pull/2031">#2031</a></li>
<li>The CodeQL Action now requires CodeQL version 2.11.6 or later. For more information, see <a href="https://github.com/github/codeql-action/blob/main/#2227---16-nov-2023">the corresponding changelog entry for CodeQL Action version 2.22.7</a>. <a href="https://redirect.github.com/github/codeql-action/pull/2009">#2009</a></li>
</ul>
<h2>3.22.12 - 22 Dec 2023</h2>
<ul>
<li>Update default CodeQL bundle version to 2.15.5. <a href="https://redirect.github.com/github/codeql-action/pull/2047">#2047</a></li>
</ul>
<h2>3.22.11 - 13 Dec 2023</h2>
<ul>
<li>[v3+ only] The CodeQL Action now runs on Node.js v20. <a href="https://redirect.github.com/github/codeql-action/pull/2006">#2006</a></li>
</ul>
<h2>2.22.10 - 12 Dec 2023</h2>
<ul>
<li>Update default CodeQL bundle version to 2.15.4. <a href="https://redirect.github.com/github/codeql-action/pull/2016">#2016</a></li>
</ul>
<h2>2.22.9 - 07 Dec 2023</h2>
<p>No user facing changes.</p>
<h2>2.22.8 - 23 Nov 2023</h2>
<ul>
<li>Update default CodeQL bundle version to 2.15.3. <a href="https://redirect.github.com/github/codeql-action/pull/2001">#2001</a></li>
</ul>
<h2>2.22.7 - 16 Nov 2023</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/github/codeql-action/commit/e8893c57a1f3a2b659b6b55564fdfdbbd2982911"><code>e8893c5</code></a> Merge pull request <a href="https://redirect.github.com/github/codeql-action/issues/2113">#2113</a> from github/update-v3.24.0-2db032717</li>
<li><a href="https://github.com/github/codeql-action/commit/78d6c8e84d016cf4acb354a3303db8635054030f"><code>78d6c8e</code></a> Update changelog for v3.24.0</li>
<li><a href="https://github.com/github/codeql-action/commit/2db03271718eb704357b7bbf29ef6876a898f966"><code>2db0327</code></a> Merge pull request <a href="https://redirect.github.com/github/codeql-action/issues/2112">#2112</a> from github/henrymercer/status-report-handle-disk-fa...</li>
<li><a href="https://github.com/github/codeql-action/commit/f9dea84e297d93b380c8e1fbee3b726ae2f9a0d1"><code>f9dea84</code></a> Status report: Handle failures determining disk usage</li>
<li><a href="https://github.com/github/codeql-action/commit/81eb6b2bf41204db055248bd3f7a89f335b6e4d9"><code>81eb6b2</code></a> Merge pull request <a href="https://redirect.github.com/github/codeql-action/issues/2108">#2108</a> from github/henrymercer/build-mode-input</li>
<li><a href="https://github.com/github/codeql-action/commit/483bef1dab1b4345c7aaad6b5ab530b6296dc57e"><code>483bef1</code></a> Merge pull request <a href="https://redirect.github.com/github/codeql-action/issues/2106">#2106</a> from github/rasmuswl/default-no-dep-inst</li>
<li><a href="https://github.com/github/codeql-action/commit/b58c2f67a6ee7168ff2d21176f29c8e7a25f34f8"><code>b58c2f6</code></a> Detail requirements for different build modes</li>
<li><a href="https://github.com/github/codeql-action/commit/f7d53249e3ff1b2d2bc99288527e155561d1ba90"><code>f7d5324</code></a> Update wording for CHANGELOG.md</li>
<li><a href="https://github.com/github/codeql-action/commit/254b53d99969befd5b84fbe43df37bc8e9350bfc"><code>254b53d</code></a> Merge branch 'main' into henrymercer/build-mode-input</li>
<li><a href="https://github.com/github/codeql-action/commit/e34513334c80bc03203d626a9c14243c9bf67245"><code>e345133</code></a> Merge pull request <a href="https://redirect.github.com/github/codeql-action/issues/2107">#2107</a> from github/henrymercer/refactor-config</li>
<li>Additional commits viewable in <a href="https://github.com/github/codeql-action/compare/e5f05b81d5b6ff8cfa111c80c22c5fd02a384118...e8893c57a1f3a2b659b6b55564fdfdbbd2982911">compare view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details> | https://api.github.com/repos/psf/requests/pulls/6632 | 2024-02-05T16:38:02Z | 2024-02-06T02:54:27Z | 2024-02-06T02:54:27Z | 2024-02-06T02:54:28Z | 511 | psf/requests | 32,417 |
send flagged message notification to discord | diff --git a/.github/workflows/deploy-to-node.yaml b/.github/workflows/deploy-to-node.yaml
index a86a6385cb..bbfacbb64c 100644
--- a/.github/workflows/deploy-to-node.yaml
+++ b/.github/workflows/deploy-to-node.yaml
@@ -64,6 +64,8 @@ jobs:
STATS_INTERVAL_WEEK: ${{ vars.STATS_INTERVAL_WEEK }}
STATS_INTERVAL_MONTH: ${{ vars.STATS_INTERVAL_MONTH }}
STATS_INTERVAL_TOTAL: ${{ vars.STATS_INTERVAL_TOTAL }}
+ DISCORD_API_KEY: ${{ secrets.DISCORD_API_KEY }}
+ DISCORD_CHANNEL_ID: ${{ vars.DISCORD_CHANNEL_ID }}
WEB_NEXT_PUBLIC_CLOUDFLARE_CAPTCHA_SITE_KEY:
${{ secrets.WEB_NEXT_PUBLIC_CLOUDFLARE_CAPTCHA_SITE_KEY }}
WEB_CLOUDFLARE_CAPTCHA_SECRET_KEY:
diff --git a/ansible/deploy-to-node.yaml b/ansible/deploy-to-node.yaml
index b0c6efa807..d75311655f 100644
--- a/ansible/deploy-to-node.yaml
+++ b/ansible/deploy-to-node.yaml
@@ -179,6 +179,10 @@
true) }}"
BACKEND_CORS_ORIGINS_CSV:
"{{ lookup('ansible.builtin.env', 'BACKEND_CORS_ORIGINS') }}"
+ DISCORD_API_KEY:
+ "{{ lookup('ansible.builtin.env', 'DISCORD_API_KEY') }}"
+ DISCORD_CHANNEL_ID:
+ "{{ lookup('ansible.builtin.env', 'DISCORD_CHANNEL_ID') }}"
ports:
- "{{ backend_port }}:8080"
diff --git a/backend/oasst_backend/config.py b/backend/oasst_backend/config.py
index e3d37c7ba0..44721a76ab 100644
--- a/backend/oasst_backend/config.py
+++ b/backend/oasst_backend/config.py
@@ -274,6 +274,9 @@ def validate_user_stats_intervals(cls, v: int):
TASK_VALIDITY_MINUTES: int = 60 * 24 * 2 # tasks expire after 2 days
+ DISCORD_API_KEY: str | None = None
+ DISCORD_CHANNEL_ID: str | None = None
+
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
diff --git a/backend/oasst_backend/prompt_repository.py b/backend/oasst_backend/prompt_repository.py
index 26c5cc8168..d7b3ee4133 100644
--- a/backend/oasst_backend/prompt_repository.py
+++ b/backend/oasst_backend/prompt_repository.py
@@ -29,6 +29,7 @@
from oasst_backend.models.payload_column_type import PayloadContainer
from oasst_backend.task_repository import TaskRepository, validate_frontend_message_id
from oasst_backend.user_repository import UserRepository
+from oasst_backend.utils import discord
from oasst_backend.utils.database_utils import CommitMode, managed_tx_method
from oasst_shared.exceptions import OasstError, OasstErrorCode
from oasst_shared.schemas import protocol as protocol_schema
@@ -546,6 +547,8 @@ def store_text_labels(self, text_labels: protocol_schema.TextLabels) -> tuple[Te
message_id, protocol_schema.EmojiOp.add, protocol_schema.EmojiCode.red_flag
)
+ discord.send_new_report_message(message=message, label_text=text_labels.text, user_id=self.user_id)
+
# update existing record for repeated updates (same user no task associated)
existing_text_label = self.fetch_non_task_text_labels(message_id, self.user_id)
if existing_text_label is not None:
diff --git a/backend/oasst_backend/utils/discord.py b/backend/oasst_backend/utils/discord.py
new file mode 100644
index 0000000000..8b950ec4e1
--- /dev/null
+++ b/backend/oasst_backend/utils/discord.py
@@ -0,0 +1,48 @@
+from uuid import UUID
+
+import requests
+from loguru import logger
+from oasst_backend.config import settings
+from oasst_backend.models.message import Message
+
+ROOT_ENDPOINT = "https://discord.com/api/v10"
+
+
+def send_new_report_message(message: Message, label_text: str, user_id: UUID) -> None:
+ if settings.DISCORD_API_KEY is None or settings.DISCORD_CHANNEL_ID is None:
+ return
+
+ try:
+ logger.debug("Sending flagged message to Discord")
+ message_text = message.text[:500] + "..." if len(message.text) > 500 else message.text
+ label_text = label_text[:4096] # 4096 is the max length of discord embed description
+ message_content_embed = {
+ "title": "Message content",
+ "description": f"{message_text}",
+ "color": 0x3498DB, # Blue
+ "footer": {
+ "text": f"Role: {message.role.upper()}\t Lang: {message.lang.upper()}\t 👍{message.emojis.get('+1') or 0} 👎{message.emojis.get('-1') or 0} 🚩{message.emojis.get('red_flag') or 0}"
+ },
+ }
+ label_text_embed = {
+ "title": "Report content",
+ "description": f"{label_text}",
+ "color": 0xE74C3C, # Red
+ "author": {
+ "name": f"User ID: {user_id}",
+ "url": f"https://open-assistant.io/admin/manage_user/{user_id}",
+ },
+ }
+ res = requests.post(
+ f"{ROOT_ENDPOINT}/channels/{settings.DISCORD_CHANNEL_ID}/messages",
+ headers={
+ "authorization": f"Bot {settings.DISCORD_API_KEY}",
+ },
+ json={
+ "content": f"New flagged message https://open-assistant.io/messages/{message.id}",
+ "embeds": [message_content_embed, label_text_embed],
+ },
+ )
+ res.raise_for_status()
+ except Exception as e:
+ logger.exception(f"Failed to send flagged message. error: {e}")
diff --git a/backend/requirements.txt b/backend/requirements.txt
index f5b2d8b0fb..a788038733 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -15,6 +15,7 @@ pydantic[email]==1.10.4
python-dotenv==0.21.0
python-jose[cryptography]==3.3.0
redis
+requests
scipy==1.8.1
SQLAlchemy==1.4.41
sqlmodel==0.0.8
| Send a notification to Discord so the mod team can quickly take action. This is a temporal workaround for https://github.com/LAION-AI/Open-Assistant/issues/968. Also we don't need a UI for it.

| https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/2641 | 2023-04-17T03:15:36Z | 2023-05-05T20:26:38Z | 2023-05-05T20:26:38Z | 2023-05-05T20:26:39Z | 1,491 | LAION-AI/Open-Assistant | 37,820 |
Fix API img2img not accepting bare base64 strings | diff --git a/modules/api/api.py b/modules/api/api.py
index 7a567be386b..efcedbba2c9 100644
--- a/modules/api/api.py
+++ b/modules/api/api.py
@@ -3,7 +3,8 @@
import time
import uvicorn
from threading import Lock
-from gradio.processing_utils import encode_pil_to_base64, decode_base64_to_file, decode_base64_to_image
+from io import BytesIO
+from gradio.processing_utils import decode_base64_to_file
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from secrets import compare_digest
@@ -13,7 +14,7 @@
from modules.api.models import *
from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img, process_images
from modules.extras import run_extras, run_pnginfo
-from PIL import PngImagePlugin
+from PIL import PngImagePlugin,Image
from modules.sd_models import checkpoints_list
from modules.realesrgan_model import get_realesrgan_models
from typing import List
@@ -40,6 +41,10 @@ def setUpscalers(req: dict):
reqDict.pop('upscaler_2')
return reqDict
+def decode_base64_to_image(encoding):
+ if encoding.startswith("data:image/"):
+ encoding = encoding.split(";")[1].split(",")[1]
+ return Image.open(BytesIO(base64.b64decode(encoding)))
def encode_pil_to_base64(image):
with io.BytesIO() as output_bytes:
| #4510 | https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/4977 | 2022-11-23T09:46:25Z | 2022-11-27T12:54:39Z | 2022-11-27T12:54:39Z | 2022-11-27T12:54:40Z | 352 | AUTOMATIC1111/stable-diffusion-webui | 40,591 |
chore(deps): bump prismjs from 1.19.0 to 1.21.0 in /website | diff --git a/website/package-lock.json b/website/package-lock.json
index 0a108d5cb..07c5267e9 100644
--- a/website/package-lock.json
+++ b/website/package-lock.json
@@ -7004,9 +7004,9 @@
"dev": true
},
"prismjs": {
- "version": "1.20.0",
- "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.20.0.tgz",
- "integrity": "sha512-AEDjSrVNkynnw6A+B1DsFkd6AVdTnp+/WoUixFRULlCLZVRZlVQMVWio/16jv7G1FscUxQxOQhWwApgbnxr6kQ==",
+ "version": "1.21.0",
+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.21.0.tgz",
+ "integrity": "sha512-uGdSIu1nk3kej2iZsLyDoJ7e9bnPzIgY0naW/HdknGj61zScaprVEVGHrPoXqI+M9sP0NDnTK2jpkvmldpuqDw==",
"dev": true,
"requires": {
"clipboard": "^2.0.0"
diff --git a/website/yarn.lock b/website/yarn.lock
index e54860de8..cbfadbd6a 100644
--- a/website/yarn.lock
+++ b/website/yarn.lock
@@ -5136,9 +5136,9 @@ prepend-http@^2.0.0:
integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=
prismjs@^1.17.1:
- version "1.19.0"
- resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.19.0.tgz#713afbd45c3baca4b321569f2df39e17e729d4dc"
- integrity sha512-IVFtbW9mCWm9eOIaEkNyo2Vl4NnEifis2GQ7/MLRG5TQe6t+4Sj9J5QWI9i3v+SS43uZBlCAOn+zYTVYQcPXJw==
+ version "1.21.0"
+ resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.21.0.tgz#36c086ec36b45319ec4218ee164c110f9fc015a3"
+ integrity sha512-uGdSIu1nk3kej2iZsLyDoJ7e9bnPzIgY0naW/HdknGj61zScaprVEVGHrPoXqI+M9sP0NDnTK2jpkvmldpuqDw==
optionalDependencies:
clipboard "^2.0.0"
| Bumps [prismjs](https://github.com/PrismJS/prism) from 1.19.0 to 1.21.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/PrismJS/prism/releases">prismjs's releases</a>.</em></p>
<blockquote>
<h2>v1.21.0</h2>
<p>Release 1.21.0</p>
<h2>v1.20.0</h2>
<p>Release 1.20.0</p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/PrismJS/prism/blob/master/CHANGELOG.md">prismjs's changelog</a>.</em></p>
<blockquote>
<h2>1.21.0 (2020-08-06)</h2>
<h3>New components</h3>
<ul>
<li><strong>.ignore</strong> & <strong>.gitignore</strong> & <strong>.hgignore</strong> & <strong>.npmignore</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2481">#2481</a>) <a href="https://github.com/PrismJS/prism/commit/3fcce6fe"><code>3fcce6fe</code></a></li>
<li><strong>Agda</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2430">#2430</a>) <a href="https://github.com/PrismJS/prism/commit/3a127c7d"><code>3a127c7d</code></a></li>
<li><strong>AL</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2300">#2300</a>) <a href="https://github.com/PrismJS/prism/commit/de21eb64"><code>de21eb64</code></a></li>
<li><strong>Cypher</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2459">#2459</a>) <a href="https://github.com/PrismJS/prism/commit/398e2943"><code>398e2943</code></a></li>
<li><strong>Dhall</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2473">#2473</a>) <a href="https://github.com/PrismJS/prism/commit/649e51e5"><code>649e51e5</code></a></li>
<li><strong>EditorConfig</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2471">#2471</a>) <a href="https://github.com/PrismJS/prism/commit/ed8fff91"><code>ed8fff91</code></a></li>
<li><strong>HLSL</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2318">#2318</a>) <a href="https://github.com/PrismJS/prism/commit/87a5c7ae"><code>87a5c7ae</code></a></li>
<li><strong>JS stack trace</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2418">#2418</a>) <a href="https://github.com/PrismJS/prism/commit/ae0327b3"><code>ae0327b3</code></a></li>
<li><strong>PeopleCode</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2302">#2302</a>) <a href="https://github.com/PrismJS/prism/commit/bd4d8165"><code>bd4d8165</code></a></li>
<li><strong>PureBasic</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2369">#2369</a>) <a href="https://github.com/PrismJS/prism/commit/d0c1c70d"><code>d0c1c70d</code></a></li>
<li><strong>Racket</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2315">#2315</a>) <a href="https://github.com/PrismJS/prism/commit/053016ef"><code>053016ef</code></a></li>
<li><strong>Smali</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2419">#2419</a>) <a href="https://github.com/PrismJS/prism/commit/22eb5cad"><code>22eb5cad</code></a></li>
<li><strong>Structured Text (IEC 61131-3)</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2311">#2311</a>) <a href="https://github.com/PrismJS/prism/commit/8704cdfb"><code>8704cdfb</code></a></li>
<li><strong>UnrealScript</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2305">#2305</a>) <a href="https://github.com/PrismJS/prism/commit/1093ceb3"><code>1093ceb3</code></a></li>
<li><strong>WarpScript</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2307">#2307</a>) <a href="https://github.com/PrismJS/prism/commit/cde5b0fa"><code>cde5b0fa</code></a></li>
<li><strong>XML doc (.net)</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2340">#2340</a>) <a href="https://github.com/PrismJS/prism/commit/caec5e30"><code>caec5e30</code></a></li>
<li><strong>YANG</strong> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2467">#2467</a>) <a href="https://github.com/PrismJS/prism/commit/ed1df1e1"><code>ed1df1e1</code></a></li>
</ul>
<h3>Updated components</h3>
<ul>
<li>Markup & JSON: Added new aliases (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2390">#2390</a>) <a href="https://github.com/PrismJS/prism/commit/9782cfe6"><code>9782cfe6</code></a></li>
<li>Fixed several cases of exponential backtracking (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2268">#2268</a>) <a href="https://github.com/PrismJS/prism/commit/7a554b5f"><code>7a554b5f</code></a></li>
<li><strong>APL</strong>
<ul>
<li>Added <code>⍥</code> (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2409">#2409</a>) <a href="https://github.com/PrismJS/prism/commit/0255cb6a"><code>0255cb6a</code></a></li>
</ul>
</li>
<li><strong>AutoHotkey</strong>
<ul>
<li>Added missing <code>format</code> built-in (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2450">#2450</a>) <a href="https://github.com/PrismJS/prism/commit/7c66cfc4"><code>7c66cfc4</code></a></li>
<li>Improved comments and other improvements (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2412">#2412</a>) <a href="https://github.com/PrismJS/prism/commit/ddf3cc62"><code>ddf3cc62</code></a></li>
<li>Added missing definitions (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2400">#2400</a>) <a href="https://github.com/PrismJS/prism/commit/4fe03676"><code>4fe03676</code></a></li>
</ul>
</li>
<li><strong>Bash</strong>
<ul>
<li>Added <code>composer</code> command (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2298">#2298</a>) <a href="https://github.com/PrismJS/prism/commit/044dd271"><code>044dd271</code></a></li>
</ul>
</li>
<li><strong>Batch</strong>
<ul>
<li>Fix escaped double quote (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2485">#2485</a>) <a href="https://github.com/PrismJS/prism/commit/f0f8210c"><code>f0f8210c</code></a></li>
</ul>
</li>
<li><strong>C</strong>
<ul>
<li>Improved macros and expressions (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2440">#2440</a>) <a href="https://github.com/PrismJS/prism/commit/8a72fa6f"><code>8a72fa6f</code></a></li>
<li>Improved macros (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2320">#2320</a>) <a href="https://github.com/PrismJS/prism/commit/fdcf7ed2"><code>fdcf7ed2</code></a></li>
</ul>
</li>
<li><strong>C#</strong>
<ul>
<li>Improved pattern matching (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2411">#2411</a>) <a href="https://github.com/PrismJS/prism/commit/7f341fc1"><code>7f341fc1</code></a></li>
<li>Fixed adjacent string interpolations (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2402">#2402</a>) <a href="https://github.com/PrismJS/prism/commit/2a2e79ed"><code>2a2e79ed</code></a></li>
</ul>
</li>
<li><strong>C++</strong>
<ul>
<li>Added support for default comparison operator (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2426">#2426</a>) <a href="https://github.com/PrismJS/prism/commit/8e9d161c"><code>8e9d161c</code></a></li>
<li>Improved class name detection (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2348">#2348</a>) <a href="https://github.com/PrismJS/prism/commit/e3fe9040"><code>e3fe9040</code></a></li>
<li>Fixed <code>enum class</code> class names (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2342">#2342</a>) <a href="https://github.com/PrismJS/prism/commit/30b4e254"><code>30b4e254</code></a></li>
</ul>
</li>
<li><strong>Content-Security-Policy</strong>
<ul>
<li>Fixed directives (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2461">#2461</a>) <a href="https://github.com/PrismJS/prism/commit/537a9e80"><code>537a9e80</code></a></li>
</ul>
</li>
<li><strong>CSS</strong>
<ul>
<li>Improved url and added keywords (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2432">#2432</a>) <a href="https://github.com/PrismJS/prism/commit/964de5a1"><code>964de5a1</code></a></li>
</ul>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/PrismJS/prism/commit/187c8a607ee70c7914682870156faa31ed01f001"><code>187c8a6</code></a> 1.21.0</li>
<li><a href="https://github.com/PrismJS/prism/commit/bf4f323391d546d4b2e1a388f05c512a27491e9c"><code>bf4f323</code></a> Changelog for v1.21.0 (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2507">#2507</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/8bba4880202ef6bd7a1e379fe9aebe69dd75f7be"><code>8bba488</code></a> Previewers: Fixed XSS (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2506">#2506</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/158caf52343e59a66c2351ff1d83648efe871e33"><code>158caf5</code></a> JSON: Greedy comments (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2479">#2479</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/f0f8210c1a9745c064d49bfb985544c654986b24"><code>f0f8210</code></a> Batch: Fix escaped double quote (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2485">#2485</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/649e51e56250a81dc0b0c4f5b3a4ea23e1c21834"><code>649e51e</code></a> Added support for Dhall (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2473">#2473</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/453079bf96746e0c44f90cb7cd90fcae9a5f94cc"><code>453079b</code></a> Line Numbers: Fixed class name on website</li>
<li><a href="https://github.com/PrismJS/prism/commit/a0efa40bde420ac3923947be611ebe6b3f077dce"><code>a0efa40</code></a> Fixed Treeview page (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2484">#2484</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/78161d607fe7d493831ff19759aac951330134a1"><code>78161d6</code></a> VB: Added VBA alias (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2469">#2469</a>)</li>
<li><a href="https://github.com/PrismJS/prism/commit/ed1df1e1208401a8b84330ecc39689fa37d0e9f6"><code>ed1df1e</code></a> Added support for YANG (<a href="https://github-redirect.dependabot.com/PrismJS/prism/issues/2467">#2467</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/PrismJS/prism/compare/v1.19.0...v1.21.0">compare view</a></li>
</ul>
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
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/mingrammer/diagrams/network/alerts).
</details> | https://api.github.com/repos/mingrammer/diagrams/pulls/247 | 2020-08-07T23:56:18Z | 2020-08-11T04:02:29Z | 2020-08-11T04:02:29Z | 2020-08-11T04:02:34Z | 720 | mingrammer/diagrams | 52,694 |
Update io-write-flow-file.py example with option | diff --git a/examples/addons/io-write-flow-file.py b/examples/addons/io-write-flow-file.py
index d956d5f85f..76fcbb46e5 100644
--- a/examples/addons/io-write-flow-file.py
+++ b/examples/addons/io-write-flow-file.py
@@ -8,8 +8,8 @@
to multiple files in parallel.
"""
+import os
import random
-import sys
from typing import BinaryIO
from mitmproxy import http
@@ -17,8 +17,11 @@
class Writer:
- def __init__(self, path: str) -> None:
- self.f: BinaryIO = open(path, "wb")
+ def __init__(self) -> None:
+ # We are using an environment variable to keep the example as simple as possible,
+ # consider implementing this as a mitmproxy option instead.
+ filename = os.getenv("MITMPROXY_OUTFILE", "out.mitm")
+ self.f: BinaryIO = open(filename, "wb")
self.w = io.FlowWriter(self.f)
def response(self, flow: http.HTTPFlow) -> None:
@@ -29,4 +32,4 @@ def done(self):
self.f.close()
-addons = [Writer(sys.argv[1])]
+addons = [Writer()]
| #### Description
Update example addon as described in https://github.com/mitmproxy/mitmproxy/issues/6445
#### Checklist
- [x] I have updated tests where applicable.
| https://api.github.com/repos/mitmproxy/mitmproxy/pulls/6464 | 2023-11-06T15:42:21Z | 2024-03-06T21:18:43Z | 2024-03-06T21:18:43Z | 2024-03-06T21:18:43Z | 284 | mitmproxy/mitmproxy | 28,349 |
Add support for custom stepfunctions lambda endpoint (#2296) | diff --git a/README.md b/README.md
index b0b40cd3df33e..bc535da7bd414 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,8 @@ You can pass the following environment variables to LocalStack:
* `KINESIS_LATENCY`: Integer value (default: `500`) or `0` (to disable), causing the Kinesis API to delay returning a response in order to mimick latency from a live AWS call.
* `DYNAMODB_ERROR_PROBABILITY`: Decimal value between 0.0 (default) and 1.0 to randomly
inject `ProvisionedThroughputExceededException` errors into DynamoDB API responses.
+* `STEPFUNCTIONS_LAMBDA_ENDPOINT`: URL to use as the lambda service endpoint in step functions.
+ By default this is the localstack lambda endpoint.
* `LAMBDA_EXECUTOR`: Method to use for executing Lambda functions. Possible values are:
- `local`: run Lambda functions in a temporary directory on the local machine
- `docker`: run each function invocation in a separate Docker container
diff --git a/localstack/config.py b/localstack/config.py
index ee66e106719d7..0f9fd72a65ba6 100644
--- a/localstack/config.py
+++ b/localstack/config.py
@@ -119,6 +119,9 @@
# Whether to skip downloading additional infrastructure components (e.g., custom Elasticsearch versions)
SKIP_INFRA_DOWNLOADS = os.environ.get('SKIP_INFRA_DOWNLOADS', '').strip()
+# Stepfunctions lambda endpoint override
+STEPFUNCTIONS_LAMBDA_ENDPOINT = os.environ.get('STEPFUNCTIONS_LAMBDA_ENDPOINT', '').strip()
+
def has_docker():
try:
@@ -159,7 +162,7 @@ def is_linux():
'USE_SSL', 'DEBUG', 'KINESIS_ERROR_PROBABILITY', 'DYNAMODB_ERROR_PROBABILITY', 'PORT_WEB_UI',
'START_WEB', 'DOCKER_BRIDGE_IP', 'DEFAULT_REGION', 'LAMBDA_JAVA_OPTS', 'LOCALSTACK_API_KEY',
'LAMBDA_CONTAINER_REGISTRY', 'TEST_AWS_ACCOUNT_ID', 'DISABLE_EVENTS', 'EDGE_PORT',
- 'EDGE_PORT_HTTP', 'SKIP_INFRA_DOWNLOADS']
+ 'EDGE_PORT_HTTP', 'SKIP_INFRA_DOWNLOADS', 'STEPFUNCTIONS_LAMBDA_ENDPOINT']
for key, value in six.iteritems(DEFAULT_SERVICE_PORTS):
clean_key = key.upper().replace('-', '_')
diff --git a/localstack/services/stepfunctions/stepfunctions_starter.py b/localstack/services/stepfunctions/stepfunctions_starter.py
index 3f7f158b88b13..1f46bb4908c75 100644
--- a/localstack/services/stepfunctions/stepfunctions_starter.py
+++ b/localstack/services/stepfunctions/stepfunctions_starter.py
@@ -12,7 +12,7 @@
def get_command():
- lambda_endpoint = aws_stack.get_local_service_url('lambda')
+ lambda_endpoint = config.STEPFUNCTIONS_LAMBDA_ENDPOINT or aws_stack.get_local_service_url('lambda')
dynamodb_endpoint = aws_stack.get_local_service_url('dynamodb')
sns_endpoint = aws_stack.get_local_service_url('sns')
sqs_endpoint = aws_stack.get_local_service_url('sqs')
| This allows setting the lambda endpoint used for executing step functions to be different
to the localstack lambda endpoint.
This is useful for integration with eg. SAM or just the lambci docker images.
--
Note: I can't see any existing tests for similar environment variable/config code. If there is somewhere appropriate I should be adding tests then please let me know and I'll update!
Resolves #2296 | https://api.github.com/repos/localstack/localstack/pulls/2302 | 2020-04-16T09:35:41Z | 2020-04-16T19:00:31Z | 2020-04-16T19:00:30Z | 2020-04-19T16:17:20Z | 721 | localstack/localstack | 28,873 |
Update Docugami Cookbook | diff --git a/cookbook/docugami_xml_kg_rag.ipynb b/cookbook/docugami_xml_kg_rag.ipynb
index 43383a47493f67..388c28534b30b4 100644
--- a/cookbook/docugami_xml_kg_rag.ipynb
+++ b/cookbook/docugami_xml_kg_rag.ipynb
@@ -63,7 +63,7 @@
"1. Create an access token via the Developer Playground for your workspace. [Detailed instructions](https://help.docugami.com/home/docugami-api).\n",
"1. Add your documents (PDF \\[scanned or digital\\], DOC or DOCX) to Docugami for processing. There are two ways to do this:\n",
" 1. Use the simple Docugami web experience. [Detailed instructions](https://help.docugami.com/home/adding-documents).\n",
- " 1. Use the [Docugami API](https://api-docs.docugami.com), specifically the [documents](https://api-docs.docugami.com/#tag/documents/operation/upload-document) endpoint. Code samples are available for [python](../upload_file/) and [JavaScript](../../js/upload-file/) or you can use the [docugami](https://pypi.org/project/docugami/) python library.\n",
+ " 1. Use the [Docugami API](https://api-docs.docugami.com), specifically the [documents](https://api-docs.docugami.com/#tag/documents/operation/upload-document) endpoint. You can also use the [docugami python library](https://pypi.org/project/docugami/) as a convenient wrapper.\n",
"\n",
"Once your documents are in Docugami, they are processed and organized into sets of similar documents, e.g. NDAs, Lease Agreements, and Service Agreements. Docugami is not limited to any particular types of documents, and the clusters created depend on your particular documents. You can [change the docset assignments](https://help.docugami.com/home/working-with-the-doc-sets-view) later if you wish. You can monitor file status in the simple Docugami webapp, or use a [webhook](https://api-docs.docugami.com/#tag/webhooks) to be informed when your documents are done processing.\n",
"\n",
@@ -916,6 +916,20 @@
"source": [
"llama2_chain.invoke(\"What was the learning rate for LLaMA2?\")"
]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "94826165",
+ "metadata": {},
+ "source": [
+ "## Docugami KG-RAG Template\n",
+ "\n",
+ "Docugami also provides a [langchain template](https://github.com/docugami/langchain-template-docugami-kg-rag) that you can integrate into your langchain projects.\n",
+ "\n",
+ "Here's a walkthrough of how you can do this.\n",
+ "\n",
+ "[](https://www.youtube.com/watch?v=xOHOmL1NFMg)\n"
+ ]
}
],
"metadata": {
| **Description:** Update the information in the Docugami cookbook. Fix broken links and add information on our kg-rag template. | https://api.github.com/repos/langchain-ai/langchain/pulls/14626 | 2023-12-12T22:35:10Z | 2023-12-12T23:21:23Z | 2023-12-12T23:21:23Z | 2023-12-12T23:21:23Z | 756 | langchain-ai/langchain | 43,183 |
various pep-8 cleanups; remove unsused imports; remove unused variables | diff --git a/test_requests.py b/test_requests.py
index 0866fccbb3..283353b919 100755
--- a/test_requests.py
+++ b/test_requests.py
@@ -19,10 +19,10 @@
Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)
from requests.cookies import cookiejar_from_dict, morsel_to_cookie
from requests.exceptions import InvalidURL, MissingSchema
-from requests.models import PreparedRequest, Response
+from requests.models import PreparedRequest
from requests.structures import CaseInsensitiveDict
from requests.sessions import SessionRedirectMixin
-from requests.models import PreparedRequest, urlencode
+from requests.models import urlencode
from requests.hooks import default_hooks
try:
@@ -153,7 +153,7 @@ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):
def test_set_cookie_on_301(self):
s = requests.session()
url = httpbin('cookies/set?foo=bar')
- r = s.get(url)
+ s.get(url)
assert s.cookies['foo'] == 'bar'
def test_cookie_sent_on_redirect(self):
@@ -213,7 +213,7 @@ def test_generic_cookiejar_works(self):
def test_param_cookiejar_works(self):
cj = cookielib.CookieJar()
- cookiejar_from_dict({'foo' : 'bar'}, cj)
+ cookiejar_from_dict({'foo': 'bar'}, cj)
s = requests.session()
r = s.get(httpbin('cookies'), cookies=cj)
# Make sure the cookie was sent
@@ -393,7 +393,7 @@ def test_POSTBIN_GET_POST_FILES(self):
assert post4.status_code == 200
with pytest.raises(ValueError):
- requests.post(url, files = ['bad file data'])
+ requests.post(url, files=['bad file data'])
def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):
@@ -404,14 +404,15 @@ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):
assert post1.status_code == 200
with open('requirements.txt') as f:
- post2 = requests.post(url, data={'some': 'data'}, files={'some': f})
+ post2 = requests.post(url,
+ data={'some': 'data'}, files={'some': f})
assert post2.status_code == 200
post4 = requests.post(url, data='[{"some": "json"}]')
assert post4.status_code == 200
with pytest.raises(ValueError):
- requests.post(url, files = ['bad file data'])
+ requests.post(url, files=['bad file data'])
def test_conflicting_post_params(self):
url = httpbin('post')
@@ -444,7 +445,10 @@ def test_unicode_get(self):
requests.get(httpbin('ø'), params={'foo': 'foo'})
def test_unicode_header_name(self):
- requests.put(httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode.
+ requests.put(
+ httpbin('put'),
+ headers={str('Content-Type'): 'application/octet-stream'},
+ data='\xff') # compat.str is unicode.
def test_pyopenssl_redirect(self):
requests.get('https://httpbin.org/status/301')
@@ -457,30 +461,30 @@ def test_urlencoded_get_query_multivalued_param(self):
def test_different_encodings_dont_break_post(self):
r = requests.post(httpbin('post'),
- data={'stuff': json.dumps({'a': 123})},
- params={'blah': 'asdf1234'},
- files={'file': ('test_requests.py', open(__file__, 'rb'))})
+ data={'stuff': json.dumps({'a': 123})},
+ params={'blah': 'asdf1234'},
+ files={'file': ('test_requests.py', open(__file__, 'rb'))})
assert r.status_code == 200
def test_unicode_multipart_post(self):
r = requests.post(httpbin('post'),
- data={'stuff': u('ëlïxr')},
- files={'file': ('test_requests.py', open(__file__, 'rb'))})
+ data={'stuff': u('ëlïxr')},
+ files={'file': ('test_requests.py', open(__file__, 'rb'))})
assert r.status_code == 200
r = requests.post(httpbin('post'),
- data={'stuff': u('ëlïxr').encode('utf-8')},
- files={'file': ('test_requests.py', open(__file__, 'rb'))})
+ data={'stuff': u('ëlïxr').encode('utf-8')},
+ files={'file': ('test_requests.py', open(__file__, 'rb'))})
assert r.status_code == 200
r = requests.post(httpbin('post'),
- data={'stuff': 'elixr'},
- files={'file': ('test_requests.py', open(__file__, 'rb'))})
+ data={'stuff': 'elixr'},
+ files={'file': ('test_requests.py', open(__file__, 'rb'))})
assert r.status_code == 200
r = requests.post(httpbin('post'),
- data={'stuff': 'elixr'.encode('utf-8')},
- files={'file': ('test_requests.py', open(__file__, 'rb'))})
+ data={'stuff': 'elixr'.encode('utf-8')},
+ files={'file': ('test_requests.py', open(__file__, 'rb'))})
assert r.status_code == 200
def test_unicode_multipart_post_fieldnames(self):
@@ -496,15 +500,17 @@ def test_unicode_multipart_post_fieldnames(self):
def test_unicode_method_name(self):
files = {'file': open('test_requests.py', 'rb')}
- r = requests.request(method=u('POST'), url=httpbin('post'), files=files)
+ r = requests.request(
+ method=u('POST'), url=httpbin('post'), files=files)
assert r.status_code == 200
def test_custom_content_type(self):
- r = requests.post(httpbin('post'),
- data={'stuff': json.dumps({'a': 123})},
- files={'file1': ('test_requests.py', open(__file__, 'rb')),
- 'file2': ('test_requests', open(__file__, 'rb'),
- 'text/py-content-type')})
+ r = requests.post(
+ httpbin('post'),
+ data={'stuff': json.dumps({'a': 123})},
+ files={'file1': ('test_requests.py', open(__file__, 'rb')),
+ 'file2': ('test_requests', open(__file__, 'rb'),
+ 'text/py-content-type')})
assert r.status_code == 200
assert b"text/py-content-type" in r.request.body
@@ -563,7 +569,8 @@ def __call__(self, r):
prep = s.prepare_request(req)
resp = s.send(prep)
- assert resp.json()['headers']['Dummy-Auth-Test'] == 'dummy-auth-test-ok'
+ assert resp.json()['headers'][
+ 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'
def test_links(self):
r = requests.Response()
@@ -694,7 +701,6 @@ def test_cookie_as_dict_items(self):
# make sure one can use items multiple times
assert list(items) == list(items)
-
def test_time_elapsed_blank(self):
r = requests.get(httpbin('get'))
td = r.elapsed
@@ -862,7 +868,6 @@ def test_params_are_merged_case_sensitive(self):
r = s.get(httpbin('get'), params={'FOO': 'bar'})
assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}
-
def test_long_authinfo_in_url(self):
url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(
'E8A3BE87-9E3F-4620-8858-95478E385B5B',
@@ -1017,7 +1022,7 @@ def test_precedence(self):
class TestCaseInsensitiveDict(unittest.TestCase):
def test_mapping_init(self):
- cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
+ cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})
assert len(cid) == 2
assert 'foo' in cid
assert 'bar' in cid
@@ -1091,7 +1096,7 @@ def test_update(self):
cid['spam'] = 'blueval'
cid.update({'sPam': 'notblueval'})
assert cid['spam'] == 'notblueval'
- cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
+ cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})
cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})
assert len(cid) == 2
assert cid['foo'] == 'anotherfoo'
@@ -1161,20 +1166,24 @@ def test_super_len_io_streams(self):
from requests.utils import super_len
assert super_len(StringIO.StringIO()) == 0
- assert super_len(StringIO.StringIO('with so much drama in the LBC')) == 29
+ assert super_len(
+ StringIO.StringIO('with so much drama in the LBC')) == 29
assert super_len(BytesIO()) == 0
- assert super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40
+ assert super_len(
+ BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40
try:
import cStringIO
except ImportError:
pass
else:
- assert super_len(cStringIO.StringIO('but some how, some way...')) == 25
+ assert super_len(
+ cStringIO.StringIO('but some how, some way...')) == 25
def test_get_environ_proxies_ip_ranges(self):
- """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """
+ """Ensures that IP addresses are correctly matches with ranges
+ in no_proxy variable."""
from requests.utils import get_environ_proxies
os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"
assert get_environ_proxies('http://192.168.0.1:5000/') == {}
@@ -1185,10 +1194,12 @@ def test_get_environ_proxies_ip_ranges(self):
assert get_environ_proxies('http://192.168.1.1/') != {}
def test_get_environ_proxies(self):
- """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """
+ """Ensures that IP addresses are correctly matches with ranges
+ in no_proxy variable."""
from requests.utils import get_environ_proxies
os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"
- assert get_environ_proxies('http://localhost.localdomain:5000/v1.0/') == {}
+ assert get_environ_proxies(
+ 'http://localhost.localdomain:5000/v1.0/') == {}
assert get_environ_proxies('http://www.requests.com/') != {}
def test_is_ipv4_address(self):
@@ -1214,12 +1225,15 @@ def test_address_in_network(self):
assert not address_in_network('172.16.0.1', '192.168.1.0/24')
def test_get_auth_from_url(self):
- """ Ensures that username and password in well-encoded URI as per RFC 3986 are correclty extracted """
+ """Ensures that username and password in well-encoded URI as per
+ RFC 3986 are correclty extracted."""
from requests.utils import get_auth_from_url
from requests.compat import quote
percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "
url_address = "request.com/url.html#test"
- url = "http://" + quote(percent_encoding_test_chars, '') + ':' + quote(percent_encoding_test_chars, '') + '@' + url_address
+ url = "http://" + quote(
+ percent_encoding_test_chars, '') + ':' + quote(
+ percent_encoding_test_chars, '') + '@' + url_address
(username, password) = get_auth_from_url(url)
assert username == percent_encoding_test_chars
assert password == percent_encoding_test_chars
@@ -1286,7 +1300,7 @@ def test_max_age_invalid_str(self):
class TestTimeout:
def test_stream_timeout(self):
try:
- r = requests.get('https://httpbin.org/delay/10', timeout=5.0)
+ requests.get('https://httpbin.org/delay/10', timeout=5.0)
except requests.exceptions.Timeout as e:
assert 'Read timed out' in e.args[0].args[0]
@@ -1353,10 +1367,10 @@ def test_requests_are_updated_each_time(self):
@pytest.fixture
def list_of_tuples():
return [
- (('a', 'b'), ('c', 'd')),
- (('c', 'd'), ('a', 'b')),
- (('a', 'b'), ('c', 'd'), ('e', 'f')),
- ]
+ (('a', 'b'), ('c', 'd')),
+ (('c', 'd'), ('a', 'b')),
+ (('a', 'b'), ('c', 'd'), ('e', 'f')),
+ ]
def test_data_argument_accepts_tuples(list_of_tuples):
@@ -1374,14 +1388,17 @@ def test_data_argument_accepts_tuples(list_of_tuples):
)
assert p.body == urlencode(data)
+
def assert_copy(p, p_copy):
for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):
assert getattr(p, attr) == getattr(p_copy, attr)
+
def test_prepared_request_empty_copy():
p = PreparedRequest()
assert_copy(p, p.copy())
+
def test_prepared_request_no_cookies_copy():
p = PreparedRequest()
p.prepare(
@@ -1392,6 +1409,7 @@ def test_prepared_request_no_cookies_copy():
)
assert_copy(p, p.copy())
+
def test_prepared_request_complete_copy():
p = PreparedRequest()
p.prepare(
| A number of PEP-8 related cleanups. Also removing unused imports and unused variables.
| https://api.github.com/repos/psf/requests/pulls/2088 | 2014-06-10T13:11:22Z | 2014-06-10T16:02:21Z | 2014-06-10T16:02:21Z | 2021-09-08T23:11:07Z | 3,269 | psf/requests | 32,717 |
Bump pino-pretty from 10.0.0 to 10.2.0 in /website | diff --git a/website/package-lock.json b/website/package-lock.json
index 77ebdc66b4..098f492c7f 100644
--- a/website/package-lock.json
+++ b/website/package-lock.json
@@ -99,7 +99,7 @@
"msw": "^1.2.1",
"msw-storybook-addon": "^1.8.0",
"path-browserify": "^1.0.1",
- "pino-pretty": "^10.0.0",
+ "pino-pretty": "^10.2.0",
"prettier": "^2.8.8",
"prisma": "^4.14.0",
"storybook": "^7.0.9",
@@ -26914,9 +26914,9 @@
}
},
"node_modules/pino-pretty": {
- "version": "10.0.0",
- "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.0.0.tgz",
- "integrity": "sha512-zKFjYXBzLaLTEAN1ayKpHXtL5UeRQC7R3lvhKe7fWs7hIVEjKGG/qIXwQt9HmeUp71ogUd/YcW+LmMwRp4KT6Q==",
+ "version": "10.2.0",
+ "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.0.tgz",
+ "integrity": "sha512-tRvpyEmGtc2D+Lr3FulIZ+R1baggQ4S3xD2Ar93KixFEDx6SEAUP3W5aYuEw1C73d6ROrNcB2IXLteW8itlwhA==",
"dev": true,
"dependencies": {
"colorette": "^2.0.7",
diff --git a/website/package.json b/website/package.json
index d5487970ba..adef15105d 100644
--- a/website/package.json
+++ b/website/package.json
@@ -120,7 +120,7 @@
"msw": "^1.2.1",
"msw-storybook-addon": "^1.8.0",
"path-browserify": "^1.0.1",
- "pino-pretty": "^10.0.0",
+ "pino-pretty": "^10.2.0",
"prettier": "^2.8.8",
"prisma": "^4.14.0",
"storybook": "^7.0.9",
| Bumps [pino-pretty](https://github.com/pinojs/pino-pretty) from 10.0.0 to 10.2.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/pinojs/pino-pretty/releases">pino-pretty's releases</a>.</em></p>
<blockquote>
<h2>v10.2.0</h2>
<h2>What's Changed</h2>
<ul>
<li>Remove coveralls by <a href="https://github.com/jsumners"><code>@jsumners</code></a> in <a href="https://redirect.github.com/pinojs/pino-pretty/pull/443">pinojs/pino-pretty#443</a></li>
<li>Add support for messageFormat strings containing conditionals by <a href="https://github.com/timlohse1104"><code>@timlohse1104</code></a> in <a href="https://redirect.github.com/pinojs/pino-pretty/pull/442">pinojs/pino-pretty#442</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/timlohse1104"><code>@timlohse1104</code></a> made their first contribution in <a href="https://redirect.github.com/pinojs/pino-pretty/pull/442">pinojs/pino-pretty#442</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/pinojs/pino-pretty/compare/v10.1.0...v10.2.0">https://github.com/pinojs/pino-pretty/compare/v10.1.0...v10.2.0</a></p>
<h2>v10.1.0</h2>
<h2>What's Changed</h2>
<ul>
<li>Add customColors to typescript definition for PrettyOptions by <a href="https://github.com/Hufschmidt"><code>@Hufschmidt</code></a> in <a href="https://redirect.github.com/pinojs/pino-pretty/pull/440">pinojs/pino-pretty#440</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/Hufschmidt"><code>@Hufschmidt</code></a> made their first contribution in <a href="https://redirect.github.com/pinojs/pino-pretty/pull/440">pinojs/pino-pretty#440</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/pinojs/pino-pretty/compare/v10.0.1...v10.1.0">https://github.com/pinojs/pino-pretty/compare/v10.0.1...v10.1.0</a></p>
<h2>v10.0.1</h2>
<p><strong>Full Changelog</strong>: <a href="https://github.com/pinojs/pino-pretty/compare/v9.4.1...v10.0.1">https://github.com/pinojs/pino-pretty/compare/v9.4.1...v10.0.1</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/pinojs/pino-pretty/commit/fa386a964cce7d7c5cbeb4ce5bb8d28785001acd"><code>fa386a9</code></a> v10.2.0</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/ff7b2384398f4c808f2cc6271e1f2726ee973340"><code>ff7b238</code></a> Add support for messageFormat strings containing conditionals (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/442">#442</a>)</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/6e66abc78439c611c861a7fe7538817659b3a37b"><code>6e66abc</code></a> Remove coveralls (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/443">#443</a>)</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/0084b84689a1cdd1e96aa7f0bd09c935250404b1"><code>0084b84</code></a> Bumped v10.1.0</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/d195503072ef80dc289c666698c83beb356c7fd2"><code>d195503</code></a> Add customColors to typescript definition for PrettyOptions (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/440">#440</a>)</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/e510233be8c0b6068e9e279fc1ecc66e5dde08e7"><code>e510233</code></a> v10.0.1</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/42fb57e096b57c95a6fbddbb1eb3588bdfdeee05"><code>42fb57e</code></a> v9.4.1</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/c32de7384b5b63896fafda5cf0e2f44186d36634"><code>c32de73</code></a> fix: adds support for printing number and boolean messageKey value type (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/434">#434</a>)</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/5d64b471a1102f643657bfad0d5bad4dd7701760"><code>5d64b47</code></a> Bump coverallsapp/github-action from 2.1.2 to 2.2.0 (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/435">#435</a>)</li>
<li><a href="https://github.com/pinojs/pino-pretty/commit/bf973c749b8516998e8aeab3dac39591db314586"><code>bf973c7</code></a> Bump <code>@types/node</code> from 18.16.5 to 20.1.0 (<a href="https://redirect.github.com/pinojs/pino-pretty/issues/425">#425</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/pinojs/pino-pretty/compare/v10.0.0...v10.2.0">compare view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details> | https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/3622 | 2023-07-31T18:15:24Z | 2023-08-01T02:42:15Z | 2023-08-01T02:42:15Z | 2023-08-01T02:42:16Z | 613 | LAION-AI/Open-Assistant | 37,011 |
Comment out empty envars in user config. | diff --git a/webui-user.sh b/webui-user.sh
index 36166df9321..b7a1b607c61 100644
--- a/webui-user.sh
+++ b/webui-user.sh
@@ -16,7 +16,7 @@ export COMMANDLINE_ARGS=()
python_cmd="python3"
# git executable
-export GIT=""
+#export GIT=""
# python3 venv without trailing slash (defaults to ${install_dir}/${clone_dir}/venv)
venv_dir="venv"
@@ -25,16 +25,16 @@ venv_dir="venv"
export TORCH_COMMAND=(python3 -m pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113)
# Requirements file to use for stable-diffusion-webui
-export REQS_FILE=""
+#export REQS_FILE=""
# Fixed git repos
-export K_DIFFUSION_PACKAGE=""
-export GFPGAN_PACKAGE=""
+#export K_DIFFUSION_PACKAGE=""
+#export GFPGAN_PACKAGE=""
# Fixed git commits
-export STABLE_DIFFUSION_COMMIT_HASH=""
-export TAMING_TRANSFORMERS_COMMIT_HASH=""
-export CODEFORMER_COMMIT_HASH=""
-export BLIP_COMMIT_HASH=""
+#export STABLE_DIFFUSION_COMMIT_HASH=""
+#export TAMING_TRANSFORMERS_COMMIT_HASH=""
+#export CODEFORMER_COMMIT_HASH=""
+#export BLIP_COMMIT_HASH=""
-###########################################
\ No newline at end of file
+###########################################
| Setting empty envars causes the `os.environ.get('ENVAR', "some default")` pattern in launch.py to ignore it's fallback value. | https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/492 | 2022-09-15T06:33:20Z | 2022-09-15T11:53:26Z | 2022-09-15T11:53:26Z | 2022-09-15T11:53:26Z | 311 | AUTOMATIC1111/stable-diffusion-webui | 40,129 |
Run at 4:00AM UTC not 0:04AM UTC. | diff --git a/.azure-pipelines/advanced.yml b/.azure-pipelines/advanced.yml
index afcf16db4d2..9832c068408 100644
--- a/.azure-pipelines/advanced.yml
+++ b/.azure-pipelines/advanced.yml
@@ -7,7 +7,7 @@ pr:
- '*.x'
# This pipeline is also nightly run on master
schedules:
- - cron: "4 0 * * *"
+ - cron: "0 4 * * *"
displayName: Nightly build
branches:
include:
| Fixes [cron syntax](https://docs.microsoft.com/en-us/azure/devops/pipelines/build/triggers?view=azure-devops&tabs=yaml#supported-cron-syntax) to get the behavior I had in mind in https://github.com/certbot/certbot/pull/7377#discussion_r331295897. | https://api.github.com/repos/certbot/certbot/pulls/7460 | 2019-10-21T20:39:53Z | 2019-10-21T21:42:51Z | 2019-10-21T21:42:51Z | 2019-10-21T21:42:54Z | 127 | certbot/certbot | 1,671 |
Map optimizer to correct device after loading from checkpoint. | diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py
index 251f0dd4bc70e..25c0baeb14662 100644
--- a/src/transformers/trainer.py
+++ b/src/transformers/trainer.py
@@ -331,7 +331,9 @@ def train(self, model_path: Optional[str] = None):
and os.path.isfile(os.path.join(model_path, "scheduler.pt"))
):
# Load in optimizer and scheduler states
- optimizer.load_state_dict(torch.load(os.path.join(model_path, "optimizer.pt")))
+ optimizer.load_state_dict(
+ torch.load(os.path.join(model_path, "optimizer.pt"), map_location=self.args.device)
+ )
scheduler.load_state_dict(torch.load(os.path.join(model_path, "scheduler.pt")))
model = self.model
| Loading from `optimizer.pt` causes `optimizer` to be mapped to the same device as the saved `optimizer.pt`. In most cases it's `cuda:0`(saved by local master), which puts all optimizers on
gpu0, causing OOM more easily in multi-gpu training.
Might fix issues like [#3730](https://github.com/huggingface/transformers/issues/3730). | https://api.github.com/repos/huggingface/transformers/pulls/4403 | 2020-05-16T18:48:42Z | 2020-05-19T03:16:06Z | 2020-05-19T03:16:06Z | 2020-05-19T03:16:12Z | 184 | huggingface/transformers | 12,194 |
Assignment to env var in Jupyter Notebook doesn't round-trip | diff --git a/CHANGES.md b/CHANGES.md
index 94d1c69259..d81c1fd4fc 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -6,6 +6,7 @@
- Fixed Python 3.10 support on platforms without ProcessPoolExecutor (#2631)
- Fixed `match` statements with open sequence subjects, like `match a, b:` (#2639)
+- Fixed assignment to environment variables in Jupyter Notebooks (#2642)
## 21.11b1
diff --git a/src/black/handle_ipynb_magics.py b/src/black/handle_ipynb_magics.py
index 2fe6739209..5807dac14d 100644
--- a/src/black/handle_ipynb_magics.py
+++ b/src/black/handle_ipynb_magics.py
@@ -403,20 +403,28 @@ def visit_Assign(self, node: ast.Assign) -> None:
For example,
black_version = !black --version
+ env = %env var
- would have been transformed to
+ would have been (respectively) transformed to
black_version = get_ipython().getoutput('black --version')
+ env = get_ipython().run_line_magic('env', 'var')
- and we look for instances of the latter.
+ and we look for instances of any of the latter.
"""
- if (
- isinstance(node.value, ast.Call)
- and _is_ipython_magic(node.value.func)
- and node.value.func.attr == "getoutput"
- ):
- (arg,) = _get_str_args(node.value.args)
- src = f"!{arg}"
+ if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func):
+ args = _get_str_args(node.value.args)
+ if node.value.func.attr == "getoutput":
+ src = f"!{args[0]}"
+ elif node.value.func.attr == "run_line_magic":
+ src = f"%{args[0]}"
+ if args[1]:
+ src += f" {args[1]}"
+ else:
+ raise AssertionError(
+ "Unexpected IPython magic {node.value.func.attr!r} found. "
+ "Please report a bug on https://github.com/psf/black/issues."
+ ) from None
self.magics[node.value.lineno].append(
OffsetAndMagic(node.value.col_offset, src)
)
@@ -451,7 +459,6 @@ def visit_Expr(self, node: ast.Expr) -> None:
else:
src = f"%{args[0]}"
if args[1]:
- assert src is not None
src += f" {args[1]}"
elif node.value.func.attr == "system":
src = f"!{args[0]}"
diff --git a/tests/test_ipynb.py b/tests/test_ipynb.py
index ba460074e9..5ecdf00b7b 100644
--- a/tests/test_ipynb.py
+++ b/tests/test_ipynb.py
@@ -90,6 +90,10 @@ def test_cell_magic_noop() -> None:
id="Line magic with argument",
),
pytest.param("%time\n'foo'", '%time\n"foo"', id="Line magic without argument"),
+ pytest.param(
+ "env = %env var", "env = %env var", id="Assignment to environment variable"
+ ),
+ pytest.param("env = %env", "env = %env", id="Assignment to magic"),
),
)
def test_magic(src: str, expected: str) -> None:
| <!-- 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. -->
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
<!-- 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 -->
closes #2641 | https://api.github.com/repos/psf/black/pulls/2642 | 2021-11-25T08:42:53Z | 2021-11-26T16:14:57Z | 2021-11-26T16:14:57Z | 2021-11-26T17:37:22Z | 815 | psf/black | 23,687 |
standarizes close_spider to use signals | diff --git a/scrapy/contrib/closespider.py b/scrapy/contrib/closespider.py
index 0a3d54596bf..a5df5e8a7cb 100644
--- a/scrapy/contrib/closespider.py
+++ b/scrapy/contrib/closespider.py
@@ -7,9 +7,8 @@
from collections import defaultdict
from twisted.internet import reactor
-from twisted.python import log as txlog
-from scrapy import signals, log
+from scrapy import signals
class CloseSpider(object):
@@ -27,7 +26,7 @@ def __init__(self, crawler):
self.counter = defaultdict(int)
if self.close_on.get('errorcount'):
- txlog.addObserver(self.catch_log)
+ crawler.signals.connect(self.error_count, signal=signals.spider_error)
if self.close_on.get('pagecount'):
crawler.signals.connect(self.page_count, signal=signals.response_received)
if self.close_on.get('timeout'):
@@ -40,13 +39,10 @@ def __init__(self, crawler):
def from_crawler(cls, crawler):
return cls(crawler)
- def catch_log(self, event):
- if event.get('logLevel') == log.ERROR:
- spider = event.get('spider')
- if spider:
- self.counter['errorcount'] += 1
- if self.counter['errorcount'] == self.close_on['errorcount']:
- self.crawler.engine.close_spider(spider, 'closespider_errorcount')
+ def error_count(self, failure, response, spider):
+ self.counter['errorcount'] += 1
+ if self.counter['errorcount'] == self.close_on['errorcount']:
+ self.crawler.engine.close_spider(spider, 'closespider_errorcount')
def page_count(self, response, request, spider):
self.counter['pagecount'] += 1
| also this fix the problem of running multiple spiders in a same process, because the log is one and shared.
| https://api.github.com/repos/scrapy/scrapy/pulls/316 | 2013-05-31T18:56:40Z | 2013-05-31T19:20:58Z | 2013-05-31T19:20:58Z | 2013-05-31T19:20:58Z | 421 | scrapy/scrapy | 34,479 |
Mazda: use bus 0 to fingerprint | diff --git a/selfdrive/car/mazda/values.py b/selfdrive/car/mazda/values.py
index c95ae162f9f11f..b43ab3df66bb52 100644
--- a/selfdrive/car/mazda/values.py
+++ b/selfdrive/car/mazda/values.py
@@ -67,16 +67,11 @@ class Buttons:
FW_QUERY_CONFIG = FwQueryConfig(
requests=[
- Request(
- [StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST],
- [StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE],
- ),
- # Log responses on powertrain bus
+ # TODO: check data to ensure ABS does not skip ISO-TP frames on bus 0
Request(
[StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST],
[StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE],
bus=0,
- logging=True,
),
],
)
diff --git a/selfdrive/car/tests/test_fw_fingerprint.py b/selfdrive/car/tests/test_fw_fingerprint.py
index 620fa256911b9b..f2de3ab7702c95 100755
--- a/selfdrive/car/tests/test_fw_fingerprint.py
+++ b/selfdrive/car/tests/test_fw_fingerprint.py
@@ -246,7 +246,7 @@ def fake_get_ecu_addrs(*_, timeout):
@pytest.mark.timeout(60)
def test_fw_query_timing(self):
- total_ref_time = 6.9
+ total_ref_time = 6.8
brand_ref_times = {
1: {
'gm': 0.5,
@@ -255,7 +255,7 @@ def test_fw_query_timing(self):
'ford': 0.1,
'honda': 0.55,
'hyundai': 0.65,
- 'mazda': 0.2,
+ 'mazda': 0.1,
'nissan': 0.8,
'subaru': 0.45,
'tesla': 0.2,
| Closes https://github.com/commaai/openpilot/issues/25756
Our two un-dashcammed Mazda platforms get everything back checking a few dongles! Will check more in a sec
~I believe we lose the engine on the dashcammed platforms, so I'm switchig the OBD query to logging only~ We do not, according to the data. Removing | https://api.github.com/repos/commaai/openpilot/pulls/31261 | 2024-02-01T04:29:37Z | 2024-02-01T08:28:01Z | 2024-02-01T08:28:01Z | 2024-02-01T08:28:02Z | 458 | commaai/openpilot | 9,312 |
change default router to pydantic | diff --git a/llama_index/llm_predictor/base.py b/llama_index/llm_predictor/base.py
index 1d164c58a3249..32e02bf27d733 100644
--- a/llama_index/llm_predictor/base.py
+++ b/llama_index/llm_predictor/base.py
@@ -28,6 +28,11 @@ class BaseLLMPredictor(Protocol):
callback_manager: CallbackManager
+ @property
+ @abstractmethod
+ def llm(self) -> LLM:
+ """Get LLM."""
+
@property
@abstractmethod
def metadata(self) -> LLMMetadata:
diff --git a/llama_index/llm_predictor/mock.py b/llama_index/llm_predictor/mock.py
index a9e8f458a2612..1bf80fadc46be 100644
--- a/llama_index/llm_predictor/mock.py
+++ b/llama_index/llm_predictor/mock.py
@@ -6,7 +6,7 @@
from llama_index.callbacks.schema import CBEventType, EventPayload
from llama_index.constants import DEFAULT_NUM_OUTPUTS
from llama_index.llm_predictor.base import BaseLLMPredictor
-from llama_index.llms.base import LLMMetadata
+from llama_index.llms.base import LLMMetadata, LLM
from llama_index.prompts.base import Prompt
from llama_index.prompts.prompt_type import PromptType
from llama_index.token_counter.utils import (
@@ -95,6 +95,10 @@ def __init__(self, max_tokens: int = DEFAULT_NUM_OUTPUTS) -> None:
def metadata(self) -> LLMMetadata:
return LLMMetadata()
+ @property
+ def llm(self) -> LLM:
+ raise NotImplementedError("MockLLMPredictor does not have an LLM model.")
+
def _log_start(self, prompt: Prompt, prompt_args: dict) -> str:
"""Log start of an LLM event."""
llm_payload = prompt_args.copy()
diff --git a/llama_index/llm_predictor/vellum/predictor.py b/llama_index/llm_predictor/vellum/predictor.py
index b8d407e13c816..6d38e43d1a5c2 100644
--- a/llama_index/llm_predictor/vellum/predictor.py
+++ b/llama_index/llm_predictor/vellum/predictor.py
@@ -5,7 +5,7 @@
from llama_index import Prompt
from llama_index.callbacks import CallbackManager
from llama_index.callbacks.schema import CBEventType, EventPayload
-from llama_index.llm_predictor.base import BaseLLMPredictor, LLMMetadata
+from llama_index.llm_predictor.base import BaseLLMPredictor, LLMMetadata, LLM
from llama_index.llm_predictor.vellum.exceptions import VellumGenerateException
from llama_index.llm_predictor.vellum.prompt_registry import VellumPromptRegistry
from llama_index.llm_predictor.vellum.types import (
@@ -45,6 +45,11 @@ def metadata(self) -> LLMMetadata:
# deployment. This is not currently possible, so we use default values.
return LLMMetadata()
+ @property
+ def llm(self) -> LLM:
+ """Get the LLM."""
+ raise NotImplementedError("Vellum does not expose the LLM.")
+
def predict(self, prompt: Prompt, **prompt_args: Any) -> str:
"""Predict the answer to a query."""
diff --git a/llama_index/query_engine/router_query_engine.py b/llama_index/query_engine/router_query_engine.py
index 807d97119bdcf..774033d5d7ab1 100644
--- a/llama_index/query_engine/router_query_engine.py
+++ b/llama_index/query_engine/router_query_engine.py
@@ -12,6 +12,10 @@
from llama_index.response.schema import RESPONSE_TYPE, Response, StreamingResponse
from llama_index.response_synthesizers import TreeSummarize
from llama_index.selectors.llm_selectors import LLMMultiSelector, LLMSingleSelector
+from llama_index.selectors.pydantic_selectors import (
+ PydanticMultiSelector,
+ PydanticSingleSelector,
+)
from llama_index.selectors.types import BaseSelector
from llama_index.schema import BaseNode
from llama_index.tools.query_engine import QueryEngineTool
@@ -100,10 +104,26 @@ def from_defaults(
summarizer: Optional[TreeSummarize] = None,
select_multi: bool = False,
) -> "RouterQueryEngine":
+ service_context = service_context or ServiceContext.from_defaults()
+
if selector is None and select_multi:
- selector = LLMMultiSelector.from_defaults(service_context=service_context)
+ try:
+ selector = PydanticMultiSelector.from_defaults(
+ llm=service_context.llm_predictor.llm # type: ignore
+ )
+ except ValueError:
+ selector = LLMMultiSelector.from_defaults(
+ service_context=service_context
+ )
elif selector is None and not select_multi:
- selector = LLMSingleSelector.from_defaults(service_context=service_context)
+ try:
+ selector = PydanticSingleSelector.from_defaults(
+ llm=service_context.llm_predictor.llm # type: ignore
+ )
+ except ValueError:
+ selector = LLMSingleSelector.from_defaults(
+ service_context=service_context
+ )
assert selector is not None
| # Description
Changes the router query engine to default to pydantic when possible.
## Type of Change
- [x] Bug fix (non-breaking change which fixes an issue)
# How Has This Been Tested?
- [x] tested in a notebook
- [x] I stared at the code and made sure it makes sense
| https://api.github.com/repos/run-llama/llama_index/pulls/7154 | 2023-08-04T14:26:47Z | 2023-08-04T15:10:30Z | 2023-08-04T15:10:30Z | 2023-08-04T15:10:31Z | 1,228 | run-llama/llama_index | 6,250 |
ZeRO-Offload: Integration code fixes | diff --git a/deepspeed/ops/adam/cpu_adam.py b/deepspeed/ops/adam/cpu_adam.py
index d51e2126cda2..76d8d323f6f5 100755
--- a/deepspeed/ops/adam/cpu_adam.py
+++ b/deepspeed/ops/adam/cpu_adam.py
@@ -12,14 +12,14 @@ class DeepSpeedCPUAdam(torch.optim.Optimizer):
def __init__(self,
model_params,
lr=1e-3,
- bettas=(0.9,
- 0.999),
+ betas=(0.9,
+ 0.999),
eps=1e-8,
weight_decay=0,
amsgrad=False):
default_args = dict(lr=lr,
- betas=bettas,
+ betas=betas,
eps=eps,
weight_decay=weight_decay,
amsgrad=amsgrad)
@@ -30,7 +30,7 @@ def __init__(self,
global ds_opt_adam
ds_opt_adam = importlib.import_module('deepspeed.ops.adam.cpu_adam_op')
- ds_opt_adam.create_adam(self.opt_id, lr, bettas[0], bettas[1], eps, weight_decay)
+ ds_opt_adam.create_adam(self.opt_id, lr, betas[0], betas[1], eps, weight_decay)
def __setstate__(self, state):
super(DeepSpeedCPUAdam, self).__setstate__(state)
@@ -54,6 +54,7 @@ def step(self, closure=None, fp16_param_groups=None):
state = self.state[p]
# State initialization
if len(state) == 0:
+ print(f'group {group_id} param {param_id} = {p.numel()}')
state['step'] = 0
# gradient momentums
state['exp_avg'] = torch.zeros_like(p.data, device='cpu')
diff --git a/deepspeed/runtime/zero/stage2.py b/deepspeed/runtime/zero/stage2.py
index 9ed9c07df054..d39c17f37161 100755
--- a/deepspeed/runtime/zero/stage2.py
+++ b/deepspeed/runtime/zero/stage2.py
@@ -15,6 +15,7 @@
from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler
from deepspeed.runtime.utils import see_memory_usage, is_model_parallel_parameter
from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION_GRADIENTS
+
from deepspeed.utils import logger
#Toggle this to true to enable correctness test
#with gradient partitioning and without
@@ -155,6 +156,7 @@ def __init__(self,
self.overlap_comm = overlap_comm or cpu_offload
self.cpu_offload = cpu_offload
+
self.device = torch.cuda.current_device() if not self.cpu_offload else 'cpu'
self.dp_process_group = dp_process_group
@@ -1405,17 +1407,22 @@ def step(self, closure=None):
self.unscale_and_clip_grads(single_partition_grad_groups, norm_groups)
#torch.set_num_threads(12)
timers('optimizer_step').start()
- #self.optimizer.step(fp16_param_groups=self.parallel_partitioned_fp16_groups)
- self.optimizer.step()
- #get rid of the fp32 gradients. Not needed anymore
- if not self.cpu_offload:
+ if self.cpu_offload:
+ # self.optimizer.step(fp16_param_groups=self.parallel_partitioned_fp16_groups)
+ self.optimizer.step()
+ for fp16_partitions, fp32_partition in zip(self.parallel_partitioned_fp16_groups, self.single_partition_of_fp32_groups):
+ fp16_partitions[partition_id].data.copy_(fp32_partition.data)
+ else:
+ self.optimizer.step()
+ #get rid of the fp32 gradients. Not needed anymore
for group in self.single_partition_of_fp32_groups:
group.grad = None
- for fp16_partitions, fp32_partition in zip(self.parallel_partitioned_fp16_groups, self.single_partition_of_fp32_groups):
- fp16_partitions[partition_id].data.copy_(fp32_partition.data)
+ for fp16_partitions, fp32_partition in zip(self.parallel_partitioned_fp16_groups, self.single_partition_of_fp32_groups):
+ fp16_partitions[partition_id].data.copy_(fp32_partition.data)
timers('optimizer_step').stop()
+ timers.log(names=['optimizer_step'])
if self.cpu_offload:
self.reset_cpu_buffers()
diff --git a/deepspeed/runtime/zero/utils.py b/deepspeed/runtime/zero/utils.py
index ba7cf8e87ebe..e51ad7c1eca1 100755
--- a/deepspeed/runtime/zero/utils.py
+++ b/deepspeed/runtime/zero/utils.py
@@ -2,6 +2,7 @@
import torch.distributed as dist
import apex
from deepspeed.utils import logger
+from deepspeed.ops.adam import DeepSpeedCPUAdam
def _initialize_parameter_parallel_groups(parameter_parallel_size=None):
@@ -22,8 +23,15 @@ def _initialize_parameter_parallel_groups(parameter_parallel_size=None):
return my_group
-ZERO_SUPPORTED_OPTIMIZERS = [torch.optim.Adam, apex.optimizers.FusedAdam]
+ZERO_SUPPORTED_OPTIMIZERS = [
+ torch.optim.Adam,
+ apex.optimizers.FusedAdam,
+ DeepSpeedCPUAdam
+]
def is_zero_supported_optimizer(optimizer):
+ print(
+ f'Checking ZeRO support for optimizer={optimizer.__class__.__name__} type={type(optimizer)}'
+ )
return type(optimizer) in ZERO_SUPPORTED_OPTIMIZERS
diff --git a/tests/model/Megatron_GPT2/run_func_test.py b/tests/model/Megatron_GPT2/run_func_test.py
index a61b0e9ba85b..552314a0d037 100755
--- a/tests/model/Megatron_GPT2/run_func_test.py
+++ b/tests/model/Megatron_GPT2/run_func_test.py
@@ -19,7 +19,7 @@
def grep_loss_from_file(file_name):
loss = 0.0
-
+ print(f'grepping {file_name}')
with open(file_name, 'r') as f:
lines = f.readlines()
line_filter = "validation loss at the end of training for test data | LM loss:"
@@ -455,7 +455,7 @@ def run_partition_activations_test(self, test_config, r_tol):
baseline_prefix += test_config["json"][0:-5]
baseline_deepspeed_config = True
- test_config["other_args"] = cpu_optimizer_flag
+ test_config["other_args"] = f"\"{cpu_optimizer_flag}\""
base_file = self.gen_output_name(test_config,
baseline_prefix,
baseline_config=baseline_deepspeed_config)
@@ -565,7 +565,7 @@ def suite():
suite.addTest(GPT2FuncTestCase('test_mp4_gpu4_node1_zero2_cpu_optimizer'))
# Baseline = Megatron + Torch.Optim.Adam
- # Test = Megatron + Torch.Optim.Adam + ZeRO-Offload
+ # Test = Megatron + DeepSpeedAdam + ZeRO-Offload
suite.addTest(GPT2FuncTestCase('test_mp1_gpu1_node1_zero2_offload'))
suite.addTest(GPT2FuncTestCase('test_mp1_gpu2_node1_zero2_offload'))
suite.addTest(GPT2FuncTestCase('test_mp2_gpu4_node1_zero2_offload'))
diff --git a/tests/model/run_sanity_check.py b/tests/model/run_sanity_check.py
index b7d12ba18f07..21c3bc5d9d43 100755
--- a/tests/model/run_sanity_check.py
+++ b/tests/model/run_sanity_check.py
@@ -30,7 +30,7 @@ def pytest_hack(runner_result):
def test_megatron():
- runner = unittest.TextTestRunner(failfast=True)
+ runner = unittest.TextTestRunner(failfast=False)
pytest_hack(runner.run(Megatron_GPT2.suite()))
diff --git a/tests/perf/adam_test.py b/tests/perf/adam_test.py
index 89b70e96e7ac..0f29cab4662e 100755
--- a/tests/perf/adam_test.py
+++ b/tests/perf/adam_test.py
@@ -3,7 +3,7 @@
import time
device = 'cpu'
-model_size = 1 * 1024 ** 3
+model_size = 1 * 1024**3
group_size = [model_size, 274432]
param = [torch.nn.Parameter(torch.ones(size, device=device)) for size in group_size]
diff --git a/tests/unit/test_checkpointing.py b/tests/unit/test_checkpointing.py
index 4ce0d36284e0..07a8f643d134 100755
--- a/tests/unit/test_checkpointing.py
+++ b/tests/unit/test_checkpointing.py
@@ -235,21 +235,24 @@ def _test_checkpoint_fused_optimizer(args, model, hidden_dim, load_optimizer_sta
load_optimizer_states=False)
-@pytest.mark.parametrize('zero_stage, use_cpu_offload',
+@pytest.mark.parametrize('zero_stage, use_cpu_offload, adam_optimizer',
[
(1,
- False),
+ False,
+ 'Adam'),
(2,
- False),
+ False,
+ 'Adam'),
(2,
- True),
+ True,
+ 'deepspeed_adam'),
])
-def test_checkpoint_zero_optimizer(tmpdir, zero_stage, use_cpu_offload):
+def test_checkpoint_zero_optimizer(tmpdir, zero_stage, use_cpu_offload, adam_optimizer):
config_dict = {
"train_batch_size": 2,
"steps_per_print": 1,
"optimizer": {
- "type": "Adam",
+ "type": adam_optimizer,
"params": {
"lr": 0.00015,
"betas": [0.8,
@@ -285,21 +288,27 @@ def _test_checkpoint_zero_optimizer(args, model, hidden_dim, load_optimizer_stat
load_optimizer_states=True)
-@pytest.mark.parametrize('zero_stage, use_cpu_offload',
+@pytest.mark.parametrize('zero_stage, use_cpu_offload, adam_optimizer',
[
(1,
- False),
+ False,
+ "Adam"),
(2,
- False),
+ False,
+ "Adam"),
(2,
- True),
+ True,
+ 'deepspeed_adam'),
])
-def test_checkpoint_zero_no_optimizer(tmpdir, zero_stage, use_cpu_offload):
+def test_checkpoint_zero_no_optimizer(tmpdir,
+ zero_stage,
+ use_cpu_offload,
+ adam_optimizer):
config_dict = {
"train_batch_size": 2,
"steps_per_print": 1,
"optimizer": {
- "type": "Adam",
+ "type": adam_optimizer,
"params": {
"lr": 0.00015,
"betas": [0.8,
@@ -338,23 +347,27 @@ def _test_checkpoint_zero_no_optimizer(args,
load_optimizer_states=False)
-@pytest.mark.parametrize('zero_stage, use_cpu_offload',
+@pytest.mark.parametrize('zero_stage, use_cpu_offload, adam_optimizer',
[
(0,
- False),
+ False,
+ 'Adam'),
(1,
- False),
+ False,
+ 'Adam'),
(2,
- False),
+ False,
+ 'Adam'),
(2,
- True),
+ True,
+ 'deepspeed_adam'),
])
-def test_checkpoint_lr_scheduler(tmpdir, zero_stage, use_cpu_offload):
+def test_checkpoint_lr_scheduler(tmpdir, zero_stage, use_cpu_offload, adam_optimizer):
config_dict = {
"train_batch_size": 2,
"steps_per_print": 1,
"optimizer": {
- "type": "Adam",
+ "type": adam_optimizer,
"params": {
"lr": 0.00015,
"betas": [0.8,
@@ -405,23 +418,27 @@ def _test_checkpoint_lr_scheduler(args,
load_lr_scheduler_states=True)
-@pytest.mark.parametrize('zero_stage, use_cpu_offload',
+@pytest.mark.parametrize('zero_stage, use_cpu_offload, adam_optimizer',
[
(0,
- False),
+ False,
+ 'Adam'),
(1,
- False),
+ False,
+ 'Adam'),
(2,
- False),
+ False,
+ 'Adam'),
(2,
- True),
+ True,
+ 'deepspeed_adam'),
])
-def test_checkpoint_no_lr_scheduler(tmpdir, zero_stage, use_cpu_offload):
+def test_checkpoint_no_lr_scheduler(tmpdir, zero_stage, use_cpu_offload, adam_optimizer):
config_dict = {
"train_batch_size": 2,
"steps_per_print": 1,
"optimizer": {
- "type": "Adam",
+ "type": adam_optimizer,
"params": {
"lr": 1e-5
}
| ZeRO-Offload: Integration code fixes | https://api.github.com/repos/microsoft/DeepSpeed/pulls/370 | 2020-09-06T05:41:52Z | 2020-09-06T05:46:24Z | 2020-09-06T05:46:24Z | 2020-09-06T05:46:24Z | 2,943 | microsoft/DeepSpeed | 10,387 |
[keras/models] Standardise docstring usage of "Default to" | diff --git a/keras/models/cloning.py b/keras/models/cloning.py
index b490777fd81..6c71fde3299 100644
--- a/keras/models/cloning.py
+++ b/keras/models/cloning.py
@@ -474,12 +474,13 @@ def clone_model(model, input_tensors=None, clone_function=None):
model (except `InputLayer` instances). It takes as argument the
layer instance to be cloned, and returns the corresponding layer
instance to be used in the model copy. If unspecified, this callable
- defaults to the following serialization/deserialization function:
+ becomes the following serialization/deserialization function:
`lambda layer: layer.__class__.from_config(layer.get_config())`.
By passing a custom callable, you can customize your copy of the
model, e.g. by wrapping certain layers of interest (you might want
to replace all `LSTM` instances with equivalent
`Bidirectional(LSTM(...))` instances, for example).
+ Defaults to `None`.
Returns:
An instance of `Model` reproducing the behavior
diff --git a/keras/models/sharpness_aware_minimization.py b/keras/models/sharpness_aware_minimization.py
index 33e01cd59e0..543b767966e 100644
--- a/keras/models/sharpness_aware_minimization.py
+++ b/keras/models/sharpness_aware_minimization.py
@@ -41,11 +41,11 @@ class SharpnessAwareMinimization(Model):
Args:
model: `tf.keras.Model` instance. The inner model that does the
forward-backward pass.
- rho: float, defaults to 0.05. The gradients scaling factor.
- num_batch_splits: int, defaults to None. The number of mini batches to
+ rho: float. The gradients scaling factor. Defaults to `0.05`.
+ num_batch_splits: int. The number of mini batches to
split into from each data batch. If None, batches are not split into
- sub-batches.
- name: string, defaults to None. The name of the SAM model.
+ sub-batches. Defaults to `None`.
+ name: string. The name of the SAM model. Defaults to `None`.
Reference:
[Pierre Foret et al., 2020](https://arxiv.org/abs/2010.01412)
| This is one of many PRs. Discussion + request to split into multiple PRs @ #17748 | https://api.github.com/repos/keras-team/keras/pulls/17974 | 2023-04-13T01:18:36Z | 2023-05-05T18:24:09Z | 2023-05-05T18:24:09Z | 2023-05-05T18:24:10Z | 540 | keras-team/keras | 47,405 |
Cabana: fix the binaryview is not updated correctly | diff --git a/tools/cabana/binaryview.cc b/tools/cabana/binaryview.cc
index bc64edbfebbff0..aa256b4ce1b218 100644
--- a/tools/cabana/binaryview.cc
+++ b/tools/cabana/binaryview.cc
@@ -202,7 +202,7 @@ void BinaryViewModel::updateState() {
}
}
- for (int i = 0; i < row_count; ++i) {
+ for (int i = 0; i < row_count * column_count; ++i) {
if (i >= prev_items.size() || prev_items[i].val != items[i].val) {
auto idx = index(i / column_count, i % column_count);
emit dataChanged(idx, idx);
| Sorry I was so careless! that I forgot to multiply the column_count. I should do more testing before sending pull request. | https://api.github.com/repos/commaai/openpilot/pulls/26731 | 2022-12-08T19:34:21Z | 2022-12-08T19:54:23Z | 2022-12-08T19:54:23Z | 2022-12-08T19:55:26Z | 175 | commaai/openpilot | 9,250 |
Delete untested, broken Model2LSTM | diff --git a/src/transformers/modeling_encoder_decoder.py b/src/transformers/modeling_encoder_decoder.py
index 7f1a71f2f24ed..4c5603b217096 100644
--- a/src/transformers/modeling_encoder_decoder.py
+++ b/src/transformers/modeling_encoder_decoder.py
@@ -18,7 +18,6 @@
import logging
import os
-import torch
from torch import nn
from .modeling_auto import AutoModel, AutoModelWithLMHead
@@ -294,21 +293,3 @@ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
)
return model
-
-
-class Model2LSTM(PreTrainedEncoderDecoder):
- @classmethod
- def from_pretrained(cls, *args, **kwargs):
- if kwargs.get("decoder_model", None) is None:
- # We will create a randomly initilized LSTM model as decoder
- if "decoder_config" not in kwargs:
- raise ValueError(
- "To load an LSTM in Encoder-Decoder model, please supply either: "
- " - a torch.nn.LSTM model as `decoder_model` parameter (`decoder_model=lstm_model`), or"
- " - a dictionary of configuration parameters that will be used to initialize a"
- " torch.nn.LSTM model as `decoder_config` keyword argument. "
- " E.g. `decoder_config={'input_size': 768, 'hidden_size': 768, 'num_layers': 2}`"
- )
- kwargs["decoder_model"] = torch.nn.LSTM(kwargs.pop("decoder_config"))
- model = super().from_pretrained(*args, **kwargs)
- return model
| If you need it back `git checkout c36416e5` | https://api.github.com/repos/huggingface/transformers/pulls/2968 | 2020-02-22T20:26:56Z | 2020-02-23T16:28:49Z | 2020-02-23T16:28:49Z | 2020-02-23T16:28:49Z | 380 | huggingface/transformers | 12,014 |
Remove tls-sni challenge in standalone plugin | diff --git a/certbot/plugins/standalone.py b/certbot/plugins/standalone.py
index 16f872a3f43..207eff0b6ca 100644
--- a/certbot/plugins/standalone.py
+++ b/certbot/plugins/standalone.py
@@ -6,7 +6,7 @@
# https://github.com/python/typeshed/blob/master/stdlib/2and3/socket.pyi
from socket import errno as socket_errors # type: ignore
-import OpenSSL
+import OpenSSL # pylint: disable=unused-import
import six
import zope.interface
@@ -55,25 +55,21 @@ def run(self, port, challenge_type, listenaddr=""):
:param int port: Port to run the server on.
:param challenge_type: Subclass of `acme.challenges.Challenge`,
- either `acme.challenge.HTTP01` or `acme.challenges.TLSSNI01`.
+ currently only `acme.challenge.HTTP01`.
:param str listenaddr: (optional) The address to listen on. Defaults to all addrs.
:returns: DualNetworkedServers instance.
:rtype: ACMEServerMixin
"""
- assert challenge_type in (challenges.TLSSNI01, challenges.HTTP01)
+ assert challenge_type == challenges.HTTP01
if port in self._instances:
return self._instances[port]
address = (listenaddr, port)
try:
- if challenge_type is challenges.TLSSNI01:
- servers = acme_standalone.TLSSNI01DualNetworkedServers(
- address, self.certs) # type: acme_standalone.BaseDualNetworkedServers
- else: # challenges.HTTP01
- servers = acme_standalone.HTTP01DualNetworkedServers(
- address, self.http_01_resources)
+ servers = acme_standalone.HTTP01DualNetworkedServers(
+ address, self.http_01_resources)
except socket.error as error:
raise errors.StandaloneBindError(error, port)
@@ -96,8 +92,6 @@ def stop(self, port):
for sockname in instance.getsocknames():
logger.debug("Stopping server at %s:%d...",
*sockname[:2])
- # Not calling server_close causes problems when renewing multiple
- # certs with `certbot renew` using TLSSNI01 and PyOpenSSL 0.13
instance.shutdown_and_server_close()
del self._instances[port]
@@ -114,7 +108,7 @@ def running(self):
return self._instances.copy()
-SUPPORTED_CHALLENGES = [challenges.HTTP01, challenges.TLSSNI01] \
+SUPPORTED_CHALLENGES = [challenges.HTTP01] \
# type: List[Type[challenges.KeyAuthorizationChallenge]]
@@ -132,8 +126,6 @@ def __call__(self, parser, namespace, values, option_string=None):
def _convert_and_validate(self, data):
"""Validate the value of supported challenges provided by the user.
- References to "dvsni" are automatically converted to "tls-sni-01".
-
:param str data: comma delimited list of challenge types
:returns: validated and converted list of challenge types
@@ -141,15 +133,6 @@ def _convert_and_validate(self, data):
"""
challs = data.split(",")
-
- # tls-sni-01 was dvsni during private beta
- if "dvsni" in challs:
- logger.info(
- "Updating legacy standalone_supported_challenges value")
- challs = [challenges.TLSSNI01.typ if chall == "dvsni" else chall
- for chall in challs]
- data = ",".join(challs)
-
unrecognized = [name for name in challs
if name not in challenges.Challenge.TYPES]
@@ -177,7 +160,7 @@ class Authenticator(common.Plugin):
"""Standalone Authenticator.
This authenticator creates its own ephemeral TCP listener on the
- necessary port in order to respond to incoming tls-sni-01 and http-01
+ necessary port in order to respond to incoming http-01
challenges from the certificate authority. Therefore, it does not
rely on any existing server program.
"""
@@ -187,10 +170,6 @@ class Authenticator(common.Plugin):
def __init__(self, *args, **kwargs):
super(Authenticator, self).__init__(*args, **kwargs)
- # one self-signed key for all tls-sni-01 certificates
- self.key = OpenSSL.crypto.PKey()
- self.key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
-
self.served = collections.defaultdict(set) # type: ServedType
# Stuff below is shared across threads (i.e. servers read
@@ -219,9 +198,8 @@ def supported_challenges(self):
def more_info(self): # pylint: disable=missing-docstring
return("This authenticator creates its own ephemeral TCP listener "
"on the necessary port in order to respond to incoming "
- "tls-sni-01 and http-01 challenges from the certificate "
- "authority. Therefore, it does not rely on any existing "
- "server program.")
+ "http-01 challenges from the certificate authority. Therefore, "
+ "it does not rely on any existing server program.")
def prepare(self): # pylint: disable=missing-docstring
pass
@@ -241,10 +219,7 @@ def _try_perform_single(self, achall):
_handle_perform_error(error)
def _perform_single(self, achall):
- if isinstance(achall.chall, challenges.HTTP01):
- servers, response = self._perform_http_01(achall)
- else: # tls-sni-01
- servers, response = self._perform_tls_sni_01(achall)
+ servers, response = self._perform_http_01(achall)
self.served[servers].add(achall)
return response
@@ -258,14 +233,6 @@ def _perform_http_01(self, achall):
self.http_01_resources.add(resource)
return servers, response
- def _perform_tls_sni_01(self, achall):
- port = self.config.tls_sni_01_port
- addr = self.config.tls_sni_01_address
- servers = self.servers.run(port, challenges.TLSSNI01, listenaddr=addr)
- response, (cert, _) = achall.response_and_validation(cert_key=self.key)
- self.certs[response.z_domain] = (self.key, cert)
- return servers, response
-
def cleanup(self, achalls): # pylint: disable=missing-docstring
# reduce self.served and close servers if no challenges are served
for unused_servers, server_achalls in self.served.items():
diff --git a/certbot/plugins/standalone_test.py b/certbot/plugins/standalone_test.py
index 9b741fc6fac..db4dbeb3bb9 100644
--- a/certbot/plugins/standalone_test.py
+++ b/certbot/plugins/standalone_test.py
@@ -44,9 +44,6 @@ def _test_run_stop(self, challenge_type):
self.mgr.stop(port=port)
self.assertEqual(self.mgr.running(), {})
- def test_run_stop_tls_sni_01(self):
- self._test_run_stop(challenges.TLSSNI01)
-
def test_run_stop_http_01(self):
self._test_run_stop(challenges.HTTP01)
@@ -98,10 +95,7 @@ def setUp(self):
self.parser.add_argument(self.flag, action=SupportedChallengesAction)
def test_correct(self):
- self.assertEqual("tls-sni-01", self._call("tls-sni-01"))
self.assertEqual("http-01", self._call("http-01"))
- self.assertEqual("tls-sni-01,http-01", self._call("tls-sni-01,http-01"))
- self.assertEqual("http-01,tls-sni-01", self._call("http-01,tls-sni-01"))
def test_unrecognized(self):
assert "foo" not in challenges.Challenge.TYPES
@@ -110,11 +104,6 @@ def test_unrecognized(self):
def test_not_subset(self):
self.assertRaises(SystemExit, self._call, "dns")
- def test_dvsni(self):
- self.assertEqual("tls-sni-01", self._call("dvsni"))
- self.assertEqual("http-01,tls-sni-01", self._call("http-01,dvsni"))
- self.assertEqual("tls-sni-01,http-01", self._call("dvsni,http-01"))
-
def get_open_port():
"""Gets an open port number from the OS."""
@@ -132,31 +121,31 @@ def setUp(self):
from certbot.plugins.standalone import Authenticator
self.config = mock.MagicMock(
- tls_sni_01_port=get_open_port(), http01_port=get_open_port(),
- standalone_supported_challenges="tls-sni-01,http-01")
+ http01_port=get_open_port(),
+ standalone_supported_challenges="http-01")
self.auth = Authenticator(self.config, name="standalone")
self.auth.servers = mock.MagicMock()
def test_supported_challenges(self):
self.assertEqual(self.auth.supported_challenges,
- [challenges.TLSSNI01, challenges.HTTP01])
+ [challenges.HTTP01])
def test_supported_challenges_configured(self):
- self.config.standalone_supported_challenges = "tls-sni-01"
+ self.config.standalone_supported_challenges = "http-01"
self.assertEqual(self.auth.supported_challenges,
- [challenges.TLSSNI01])
+ [challenges.HTTP01])
def test_more_info(self):
self.assertTrue(isinstance(self.auth.more_info(), six.string_types))
def test_get_chall_pref(self):
self.assertEqual(self.auth.get_chall_pref(domain=None),
- [challenges.TLSSNI01, challenges.HTTP01])
+ [challenges.HTTP01])
def test_get_chall_pref_configured(self):
- self.config.standalone_supported_challenges = "tls-sni-01"
+ self.config.standalone_supported_challenges = "http-01"
self.assertEqual(self.auth.get_chall_pref(domain=None),
- [challenges.TLSSNI01])
+ [challenges.HTTP01])
def test_perform(self):
achalls = self._get_achalls()
@@ -212,10 +201,8 @@ def _get_achalls(cls):
key = jose.JWK.load(test_util.load_vector('rsa512_key.pem'))
http_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
challb=acme_util.HTTP01_P, domain=domain, account_key=key)
- tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
- challb=acme_util.TLSSNI01_P, domain=domain, account_key=key)
- return [http_01, tls_sni_01]
+ return [http_01]
def test_cleanup(self):
self.auth.servers.running.return_value = {
@@ -243,5 +230,6 @@ def test_cleanup(self):
"server1": set(), "server2": set([])})
self.auth.servers.stop.assert_called_with(2)
+
if __name__ == "__main__":
unittest.main() # pragma: no cover
| This PR is a part of the tls-sni-01 removal plan described in #6849.
It removes the capability to make tls-sni-01 challenges in the standalone plugin. | https://api.github.com/repos/certbot/certbot/pulls/6856 | 2019-03-13T23:37:31Z | 2019-03-14T23:30:18Z | 2019-03-14T23:30:18Z | 2019-03-18T16:26:51Z | 2,578 | certbot/certbot | 2,785 |
Deprecate Python 2 formatting support | diff --git a/CHANGES.md b/CHANGES.md
index 4c04eccde48..9990d8cf459 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -10,6 +10,7 @@
- Bumped typed-ast version minimum to 1.4.3 for 3.10 compatiblity (#2519)
- Fixed a Python 3.10 compatibility issue where the loop argument was still being passed
even though it has been removed (#2580)
+- Deprecate Python 2 formatting support (#2523)
### _Blackd_
diff --git a/docs/faq.md b/docs/faq.md
index 9fe53922b6d..77f9df51fd4 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -74,13 +74,17 @@ disabled-by-default counterpart W504. E203 should be disabled while changes are
## Does Black support Python 2?
+```{warning}
+Python 2 support has been deprecated since 21.10b0.
+
+This support will be dropped in the first stable release, expected for January 2022.
+See [The Black Code Style](the_black_code_style/index.rst) for details.
+```
+
For formatting, yes! [Install](getting_started.md#installation) with the `python2` extra
to format Python 2 files too! In terms of running _Black_ though, Python 3.6 or newer is
required.
-Note that this support will be dropped in the first stable release, expected for
-January 2022. See [The Black Code Style](the_black_code_style/index.rst) for details.
-
## Why does my linter or typechecker complain after I format my code?
Some linters and other tools use magical comments (e.g., `# noqa`, `# type: ignore`) to
diff --git a/src/black/__init__.py b/src/black/__init__.py
index c503c1a55f7..831cda934a8 100644
--- a/src/black/__init__.py
+++ b/src/black/__init__.py
@@ -1061,6 +1061,15 @@ def f(
versions = mode.target_versions
else:
versions = detect_target_versions(src_node)
+
+ # TODO: fully drop support and this code hopefully in January 2022 :D
+ if TargetVersion.PY27 in mode.target_versions or versions == {TargetVersion.PY27}:
+ msg = (
+ "DEPRECATION: Python 2 support will be removed in the first stable release"
+ "expected in January 2022."
+ )
+ err(msg, fg="yellow", bold=True)
+
normalize_fmt_off(src_node)
lines = LineGenerator(
mode=mode,
@@ -1103,7 +1112,7 @@ def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
return tiow.read(), encoding, newline
-def get_features_used(node: Node) -> Set[Feature]:
+def get_features_used(node: Node) -> Set[Feature]: # noqa: C901
"""Return a set of (relatively) new Python features used in this file.
Currently looking for:
@@ -1113,6 +1122,7 @@ def get_features_used(node: Node) -> Set[Feature]:
- positional only arguments in function signatures and lambdas;
- assignment expression;
- relaxed decorator syntax;
+ - print / exec statements;
"""
features: Set[Feature] = set()
for n in node.pre_order():
@@ -1161,6 +1171,11 @@ def get_features_used(node: Node) -> Set[Feature]:
if argch.type in STARS:
features.add(feature)
+ elif n.type == token.PRINT_STMT:
+ features.add(Feature.PRINT_STMT)
+ elif n.type == token.EXEC_STMT:
+ features.add(Feature.EXEC_STMT)
+
return features
diff --git a/src/black/mode.py b/src/black/mode.py
index 0b7624eaf8a..374c47a42eb 100644
--- a/src/black/mode.py
+++ b/src/black/mode.py
@@ -41,9 +41,17 @@ class Feature(Enum):
RELAXED_DECORATORS = 10
FORCE_OPTIONAL_PARENTHESES = 50
+ # temporary for Python 2 deprecation
+ PRINT_STMT = 200
+ EXEC_STMT = 201
+
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
- TargetVersion.PY27: {Feature.ASYNC_IDENTIFIERS},
+ TargetVersion.PY27: {
+ Feature.ASYNC_IDENTIFIERS,
+ Feature.PRINT_STMT,
+ Feature.EXEC_STMT,
+ },
TargetVersion.PY33: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
TargetVersion.PY34: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
TargetVersion.PY35: {
diff --git a/src/blib2to3/pgen2/token.py b/src/blib2to3/pgen2/token.py
index 1e0dec9c714..349ba8023a2 100644
--- a/src/blib2to3/pgen2/token.py
+++ b/src/blib2to3/pgen2/token.py
@@ -74,6 +74,9 @@
COLONEQUAL: Final = 59
N_TOKENS: Final = 60
NT_OFFSET: Final = 256
+# temporary for Python 2 deprecation
+PRINT_STMT: Final = 316
+EXEC_STMT: Final = 288
# --end constants--
tok_name: Final[Dict[int, str]] = {}
diff --git a/tests/test_black.py b/tests/test_black.py
index 5647a00e48b..b96a5438557 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -1401,14 +1401,14 @@ def test_docstring_reformat_for_py27(self) -> None:
)
expected = 'def foo():\n """Testing\n Testing"""\n print "Foo"\n'
- result = CliRunner().invoke(
+ result = BlackRunner().invoke(
black.main,
["-", "-q", "--target-version=py27"],
input=BytesIO(source),
)
self.assertEqual(result.exit_code, 0)
- actual = result.output
+ actual = result.stdout
self.assertFormatEqual(actual, expected)
@staticmethod
@@ -2017,6 +2017,21 @@ def test_get_sources_with_stdin_filename_and_force_exclude(self) -> None:
)
+@pytest.mark.parametrize("explicit", [True, False], ids=["explicit", "autodetection"])
+def test_python_2_deprecation_with_target_version(explicit: bool) -> None:
+ args = [
+ "--config",
+ str(THIS_DIR / "empty.toml"),
+ str(DATA_DIR / "python2.py"),
+ "--check",
+ ]
+ if explicit:
+ args.append("--target-version=py27")
+ with cache_dir():
+ result = BlackRunner().invoke(black.main, args)
+ assert "DEPRECATION: Python 2 support will be removed" in result.stderr
+
+
with open(black.__file__, "r", encoding="utf-8") as _bf:
black_source_lines = _bf.readlines()
| ### Description
It's 2021. See also #2251.
### 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. -->
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation? | https://api.github.com/repos/psf/black/pulls/2523 | 2021-10-06T22:30:20Z | 2021-10-31T23:46:12Z | 2021-10-31T23:46:12Z | 2021-10-31T23:46:16Z | 1,665 | psf/black | 24,524 |
Parameterize initial state distributions for classic control envs. | diff --git a/gym/envs/classic_control/acrobot.py b/gym/envs/classic_control/acrobot.py
index 39c935706a7..0d05db7aa5b 100644
--- a/gym/envs/classic_control/acrobot.py
+++ b/gym/envs/classic_control/acrobot.py
@@ -23,6 +23,12 @@
from gym.utils.renderer import Renderer
+DEFAULT_LOW = -0.1
+DEFAULT_HIGH = 0.1
+LIMIT_LOW = -1.0
+LIMIT_HIGH = 1.0
+
+
class AcrobotEnv(core.Env):
"""
### Description
@@ -187,7 +193,21 @@ def reset(
options: Optional[dict] = None
):
super().reset(seed=seed)
- self.state = self.np_random.uniform(low=-0.1, high=0.1, size=(4,)).astype(
+ if options is None:
+ low = DEFAULT_LOW
+ high = DEFAULT_HIGH
+ else:
+ low = options.pop('low', DEFAULT_LOW)
+ high = options.pop('high', DEFAULT_HIGH)
+ # We expect only numerical inputs.
+ assert type(low) == int or float
+ assert type(high) == int or float
+ # Since the same boundaries are used for all observations, we set the
+ # limits according to the most restrictive (cos/sin): (-1., 1.).
+ low = max(low, LIMIT_LOW)
+ high = min(high, LIMIT_HIGH)
+ assert low < high
+ self.state = self.np_random.uniform(low=low, high=high, size=(4,)).astype(
np.float32
)
diff --git a/gym/envs/classic_control/cartpole.py b/gym/envs/classic_control/cartpole.py
index 0cf969c3319..5b7a14abb1c 100644
--- a/gym/envs/classic_control/cartpole.py
+++ b/gym/envs/classic_control/cartpole.py
@@ -14,6 +14,12 @@
from gym.utils.renderer import Renderer
+DEFAULT_LOW = -0.05
+DEFAULT_HIGH = 0.05
+LIMIT_LOW = -0.2
+LIMIT_HIGH = 0.2
+
+
class CartPoleEnv(gym.Env[np.ndarray, Union[int, np.ndarray]]):
"""
### Description
@@ -194,7 +200,23 @@ def reset(
options: Optional[dict] = None,
):
super().reset(seed=seed)
- self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))
+ if options is None:
+ low = DEFAULT_LOW
+ high = DEFAULT_HIGH
+ else:
+ low = options.pop('low', DEFAULT_LOW)
+ high = options.pop('high', DEFAULT_HIGH)
+ # We expect only numerical inputs.
+ assert type(low) == int or float
+ assert type(high) == int or float
+ # Since the same boundaries are used for all observations, we set the
+ # limits according to the most restrictive (pole angle). As per the
+ # documentation at the top of the file, we restrict them to be within
+ # (-.2, .2).
+ low = max(low, LIMIT_LOW)
+ high = min(high, LIMIT_HIGH)
+ assert low < high
+ self.state = self.np_random.uniform(low=low, high=high, size=(4,))
self.steps_beyond_done = None
self.renderer.reset()
self.renderer.render_step()
diff --git a/gym/envs/classic_control/continuous_mountain_car.py b/gym/envs/classic_control/continuous_mountain_car.py
index 2f8298cf9de..5506611feb7 100644
--- a/gym/envs/classic_control/continuous_mountain_car.py
+++ b/gym/envs/classic_control/continuous_mountain_car.py
@@ -24,6 +24,12 @@
from gym.utils.renderer import Renderer
+DEFAULT_LOW = -0.6
+DEFAULT_HIGH = -0.4
+LIMIT_LOW = -1.2
+LIMIT_HIGH = 0.6
+
+
class Continuous_MountainCarEnv(gym.Env):
"""
### Description
@@ -180,7 +186,20 @@ def reset(
options: Optional[dict] = None
):
super().reset(seed=seed)
- self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
+ if options is None:
+ low = DEFAULT_LOW
+ high = DEFAULT_HIGH
+ else:
+ low = options.pop('low', DEFAULT_LOW)
+ high = options.pop('high', DEFAULT_HIGH)
+ # We expect only numerical inputs.
+ assert type(low) == int or float
+ assert type(high) == int or float
+ # MountainCar expects states to be within -1.2 and 0.6.
+ low = max(low, LIMIT_LOW)
+ high = min(high, LIMIT_HIGH)
+ assert low < high
+ self.state = np.array([self.np_random.uniform(low=low, high=high), 0])
self.renderer.reset()
self.renderer.render_step()
if not return_info:
diff --git a/gym/envs/classic_control/mountain_car.py b/gym/envs/classic_control/mountain_car.py
index a2e3f52a0f4..3966079dec3 100644
--- a/gym/envs/classic_control/mountain_car.py
+++ b/gym/envs/classic_control/mountain_car.py
@@ -13,6 +13,12 @@
from gym.utils.renderer import Renderer
+DEFAULT_LOW = -0.6
+DEFAULT_HIGH = -0.4
+LIMIT_LOW = -1.2
+LIMIT_HIGH = 0.6
+
+
class MountainCarEnv(gym.Env):
"""
### Description
@@ -154,7 +160,20 @@ def reset(
options: Optional[dict] = None,
):
super().reset(seed=seed)
- self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
+ if options is None:
+ low = DEFAULT_LOW
+ high = DEFAULT_HIGH
+ else:
+ low = options.pop('low', DEFAULT_LOW)
+ high = options.pop('high', DEFAULT_HIGH)
+ # We expect only numerical inputs.
+ assert type(low) == int or float
+ assert type(high) == int or float
+ # MountainCar expects states to be within -1.2 and 0.6.
+ low = max(low, LIMIT_LOW)
+ high = min(high, LIMIT_HIGH)
+ assert low < high
+ self.state = np.array([self.np_random.uniform(low=low, high=high), 0])
self.renderer.reset()
self.renderer.render_step()
if not return_info:
diff --git a/gym/envs/classic_control/pendulum.py b/gym/envs/classic_control/pendulum.py
index 33547bb2d49..9ad99523dc2 100644
--- a/gym/envs/classic_control/pendulum.py
+++ b/gym/envs/classic_control/pendulum.py
@@ -11,6 +11,10 @@
from gym.utils.renderer import Renderer
+DEFAULT_X = np.pi
+DEFAULT_Y = 1.0
+
+
class PendulumEnv(gym.Env):
"""
### Description
@@ -142,8 +146,24 @@ def reset(
options: Optional[dict] = None
):
super().reset(seed=seed)
- high = np.array([np.pi, 1])
- self.state = self.np_random.uniform(low=-high, high=high)
+ if options is None:
+ high = np.array([np.pi, 1])
+ else:
+ x = options.pop('x', DEFAULT_X)
+ y = options.pop('y', DEFAULT_Y)
+ # We expect only numerical inputs.
+ assert type(x) == int or float
+ assert type(y) == int or float
+ # Since the same boundaries are used for all observations, we set the
+ # limits according to the most restrictive (sin/cos). Since these are
+ # the values that will be used for the `high` variable, we enforce them
+ # to be non-negative: (0., 1.).
+ x = max(0.0, min(1.0, x))
+ y = max(0.0, min(1.0, y))
+ assert x < y
+ high = np.array([x, y])
+ low = -high # We enforce symmetric limits.
+ self.state = self.np_random.uniform(low=low, high=high)
self.last_u = None
self.renderer.reset()
diff --git a/tests/envs/test_env_implementation.py b/tests/envs/test_env_implementation.py
index 844d422c12a..46752bec890 100644
--- a/tests/envs/test_env_implementation.py
+++ b/tests/envs/test_env_implementation.py
@@ -1,9 +1,11 @@
import pytest
+from typing import Optional
import gym
from gym.envs.box2d import BipedalWalker
from gym.envs.box2d.lunar_lander import demo_heuristic_lander
from gym.envs.toy_text.frozen_lake import generate_random_map
+import numpy as np
def test_lunar_lander_heuristics():
@@ -80,3 +82,34 @@ def test_frozenlake_dfs_map_generation(map_size: int):
if new_frozenlake[new_row][new_col] not in "#H":
frontier.append((new_row, new_col))
raise AssertionError("No path through the frozenlake was found.")
+
+
+@pytest.mark.parametrize("low_high", [None, (-1.0, 1.0), (0., 2.), (-2., 1.)])
+def test_customizable_resets(low_high: Optional[list]):
+ envs = {
+ 'acrobot': gym.make('Acrobot-v1'),
+ 'cartpole': gym.make('CartPole-v1'),
+ 'mountaincar': gym.make('MountainCar-v0'),
+ 'mountaincar_continuous': gym.make('MountainCarContinuous-v0'),
+ 'pendulum': gym.make('Pendulum-v1'),
+ }
+ for env in envs:
+ # For each environment, make sure we can reset and step without out-of-bound
+ # errors.
+ if low_high is None:
+ envs[env].reset()
+ else:
+ low, high = low_high
+ for i in range(15):
+ if env == 'pendulum':
+ # Pendulum is initialized a little differently, where we specify the
+ # x and y values for the upper limit (and lower limit is just the
+ # negative of it).
+ envs[env].reset(options={'x': low, 'y': high})
+ else:
+ envs[env].reset(options={'low': low, 'high': high})
+ assert np.all((envs[env].state >= low) & (envs[env].state <+ high))
+ if env.endswith('continuous') or env == 'pendulum':
+ envs[env].step([0])
+ else:
+ envs[env].step(0)
| # Description
This PR adds the ability for users to specify custom limits for the initial state distribution boundaries for classic control environments. Currently, they are hard-coded, but it can be useful for research to be able to set these to different values.
Motivating context: https://twitter.com/pcastr/status/1539368076700962817
Fixes # (issue)
## Type of change
- [ ] New feature (non-breaking change which adds functionality)
# 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
- [ ] 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/2921 | 2022-06-23T17:53:17Z | 2022-06-23T21:06:04Z | 2022-06-23T21:06:04Z | 2022-06-24T13:56:08Z | 2,578 | openai/gym | 5,273 |
Add missing COROLLA_TSS2 engine | diff --git a/selfdrive/car/toyota/values.py b/selfdrive/car/toyota/values.py
index 7d26ffd2e78df5..f4109abc368b46 100644
--- a/selfdrive/car/toyota/values.py
+++ b/selfdrive/car/toyota/values.py
@@ -1005,6 +1005,7 @@ def match_fw_to_car_fuzzy(live_fw_versions) -> Set[str]:
b'\x0230A10000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x0230A11000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x0230ZN4000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00',
+ b'\x0230ZN5000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x03312K7000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203402\x00\x00\x00\x00',
b'\x03312M3000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203402\x00\x00\x00\x00',
b'\x03312N6000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203202\x00\x00\x00\x00',
@@ -1060,6 +1061,7 @@ def match_fw_to_car_fuzzy(live_fw_versions) -> Set[str]:
b'\x01F152612B91\x00\x00\x00\x00\x00\x00',
b'\x01F15260A070\x00\x00\x00\x00\x00\x00',
b'\x01F152676250\x00\x00\x00\x00\x00\x00',
+ b'\x01F152602470\x00\x00\x00\x00\x00\x00',
b'F152612590\x00\x00\x00\x00\x00\x00',
b'F152612691\x00\x00\x00\x00\x00\x00',
b'F152612692\x00\x00\x00\x00\x00\x00',
| **Car**
Toyota corolla 2019
**Route**
dongle_id: c37e45e530eee601
route_name: c37e45e530eee601|2023-10-16--10-12-58
| https://api.github.com/repos/commaai/openpilot/pulls/30267 | 2023-10-17T08:04:16Z | 2023-10-17T08:10:52Z | 2023-10-17T08:10:52Z | 2023-10-17T08:10:52Z | 634 | commaai/openpilot | 9,160 |
the readme one-liner fails in practice | diff --git a/README.rst b/README.rst
index 610ce38f290..712eb3b225e 100644
--- a/README.rst
+++ b/README.rst
@@ -21,7 +21,7 @@ All you need to do is:
::
- user@www:~$ sudo letsencrypt www.example.org
+ user@www:~$ sudo letsencrypt -d www.example.org
**Encrypt ALL the things!**
| It's missing the required -d before the domain name.
| https://api.github.com/repos/certbot/certbot/pulls/277 | 2015-03-09T08:13:45Z | 2015-03-10T18:09:45Z | 2015-03-10T18:09:45Z | 2016-05-06T19:22:09Z | 107 | certbot/certbot | 2,034 |
Update 0.40.x Azure config | diff --git a/.azure-pipelines/advanced.yml b/.azure-pipelines/advanced.yml
index fe24a9ecb1d..44cdf5d544d 100644
--- a/.azure-pipelines/advanced.yml
+++ b/.azure-pipelines/advanced.yml
@@ -4,7 +4,6 @@ trigger:
- '*.x'
pr:
- test-*
- - '*.x'
# This pipeline is also nightly run on master
schedules:
- cron: "0 4 * * *"
diff --git a/.azure-pipelines/main.yml b/.azure-pipelines/main.yml
index be9eaf0b0da..d9609037eea 100644
--- a/.azure-pipelines/main.yml
+++ b/.azure-pipelines/main.yml
@@ -6,6 +6,7 @@ trigger:
pr:
- apache-parser-v2
- master
+ - '*.x'
jobs:
- template: templates/tests-suite.yml
| I hope this PR isn't needed, but I don't think it hurts since the changes are to unpackaged code and it could avoid some problems in the future.
Yesterday I noticed that we had configured our full/nightly test suite to run in Azure on PRs for point release branches, but we were requiring our normal test suite to run to make the PR mergeable on GitHub. I argued that the behavior we wanted was our normal test suite to run and this behavior was fixed in #7514, but now we have a problem:
1. If we update the branch protection rules to require our normal test suite to pass on Azure, only our nightly/full test suite will run on PRs for the 0.40.x branch because it doesn't have the updates to the Azure configuration file.
2. If we leave it unchanged to require only our nightly test suite, future point release branches will have this problem until we remember to update the branch protection rules.
Alternatively, I could try to set up separate rules for 0.40.x in GitHub, but that seems like overkill.
While the issue is fresh in our minds, I think it's worth merging this PR to avoid any headaches in the future. I've updated GitHub to require only the limited test suite to pass on PRs for point release branches as you can see here. | https://api.github.com/repos/certbot/certbot/pulls/7523 | 2019-11-06T20:21:08Z | 2019-11-06T21:00:44Z | 2019-11-06T21:00:44Z | 2019-11-06T21:00:47Z | 213 | certbot/certbot | 1,636 |
return empty dict if config file is empty | diff --git a/interpreter/terminal_interface/utils/get_config.py b/interpreter/terminal_interface/utils/get_config.py
index ceb897e70..c94e2e7ae 100644
--- a/interpreter/terminal_interface/utils/get_config.py
+++ b/interpreter/terminal_interface/utils/get_config.py
@@ -42,11 +42,25 @@ def get_config_path(path=user_config_path):
# Copying the file using shutil.copy
new_file = shutil.copy(default_config_path, path)
+ print("Copied the default config file to the user's directory because the user's config file was not found.")
+
return path
def get_config(path=user_config_path):
path = get_config_path(path)
+
+ config = None
with open(path, "r") as file:
- return yaml.safe_load(file)
+ config = yaml.safe_load(file)
+ if config is not None:
+ return config
+
+ if config is None:
+ # Deleting empty file because get_config_path copies the default if file is missing
+ os.remove(path)
+ path = get_config_path(path)
+ with open(path, "r") as file:
+ config = yaml.safe_load(file)
+ return config
| ### Describe the changes you have made:
`yaml.safe_load` returns `None` from the `get_config` function if the config file is empty. This change checks for `None` value and instead returns `{}` so `extend_config` call doesn't throw exception when config file is empty.
### Reference any relevant issue (Fixes #000)
https://github.com/KillianLucas/open-interpreter/issues/794
- [ ] I have performed a self-review of my code:
### I have tested the code on the following OS:
- [ ] Windows
- [x] MacOS
- [ ] Linux
### AI Language Model (if applicable)
- [ ] GPT4
- [ ] GPT3
- [ ] Llama 7B
- [ ] Llama 13B
- [ ] Llama 34B
- [ ] Huggingface model (Please specify which one)
| https://api.github.com/repos/OpenInterpreter/open-interpreter/pulls/811 | 2023-12-03T20:15:27Z | 2023-12-14T02:35:16Z | 2023-12-14T02:35:16Z | 2023-12-14T02:35:17Z | 272 | OpenInterpreter/open-interpreter | 40,860 |
Fixed typo in LOG_FORMAT description | diff --git a/docs/topics/settings.rst b/docs/topics/settings.rst
index 420e85d37b5..219509c1ebf 100644
--- a/docs/topics/settings.rst
+++ b/docs/topics/settings.rst
@@ -1090,7 +1090,7 @@ LOG_FORMAT
Default: ``'%(asctime)s [%(name)s] %(levelname)s: %(message)s'``
String for formatting log messages. Refer to the
-:ref:`Python logging documentation <logrecord-attributes>` for the qwhole
+:ref:`Python logging documentation <logrecord-attributes>` for the whole
list of available placeholders.
.. setting:: LOG_DATEFORMAT
| https://api.github.com/repos/scrapy/scrapy/pulls/5839 | 2023-03-02T09:16:35Z | 2023-03-02T09:19:41Z | 2023-03-02T09:19:41Z | 2023-03-02T09:19:46Z | 146 | scrapy/scrapy | 34,634 | |
add document style guidelines to contributing.md | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4ab7589fc..a268569c0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -40,12 +40,47 @@ to display, reproduce, perform, distribute and create derivative works of that m
## Pull requests
-We welcome pull requests for scoped changes to the guidelines--bug fixes in examples, clarifying ambiguous text, etc. Significant changes should
-first be discussed in the [Issues](https://github.com/isocpp/CppCoreGuidelines/issues) and the Issue number must be included in the pull
-request. Also please specify the rule number in your Issue and PR.
-Changes should be made in a child commit of a recent commit in the master branch. Also, if you are making many small changes please create
-separate PRs to minimize merge issues.
+We welcome pull requests for scoped changes to the guidelines--bug fixes in
+examples, clarifying ambiguous text, etc. Significant changes should first be
+discussed in the [Issues](https://github.com/isocpp/CppCoreGuidelines/issues)
+and the Issue number must be included in the pull request. For
+guideline-related changes, please specify the rule number in your Issue and/or
+Pull Request.
-Lastly, to avoid line ending issues, please set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration.
+Changes should be made in a child commit of a recent commit in the master
+branch. If you are making many small changes, please create separate PRs to
+minimize merge issues.
+### Document Style Guidelines
+
+Documents in this repository are written in an unspecific flavor of Markdown,
+which leaves some ambiguity for formatting text. We ask that pull requests
+maintain the following style guidelines, though we are aware that the document
+may not already be consistent.
+
+#### Indentation
+
+Code and nested text should use multiples of 4 spaces of indentation, and no
+tab characters, like so:
+
+ void func(const int x)
+ {
+ std::cout << x << std::endl;
+ }
+
+#### Code Blocks
+
+Please use 4-space indentation to trigger code parsing, rather than [fenced code blocks](https://help.github.com/articles/github-flavored-markdown/#fenced-code-blocks) or any other style, like so:
+
+ This is some document text, with an example below:
+
+ void func()
+ {
+ std::cout << "This is code." << std::endl;
+ }
+
+### Miscellaneous
+
+To avoid line-ending issues, please set `autocrlf = input` and `whitespace =
+cr-at-eol` in your git configuration.
| As discussed in #176, `CONTRIBUTING.md` could do with some standardization of markdown style, which should help maintain a consistent style throughout the guideline document.
I believe there is room for more in this section, for example:
- Whitespace at end of line
- Line length for text and code
This Pull Request addresses the points agreed on thus far, and re-writes some surrounding text to maintain the existing document style.
| https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/415 | 2015-11-30T22:02:15Z | 2015-12-01T00:08:14Z | 2015-12-01T00:08:14Z | 2015-12-02T19:35:30Z | 626 | isocpp/CppCoreGuidelines | 16,021 |
fix double emoji in `MessageTableEntry` component | diff --git a/website/src/components/Messages/MessageEmojiButton.tsx b/website/src/components/Messages/MessageEmojiButton.tsx
index 97230f759e..6191ada9c5 100644
--- a/website/src/components/Messages/MessageEmojiButton.tsx
+++ b/website/src/components/Messages/MessageEmojiButton.tsx
@@ -36,7 +36,6 @@ export const MessageEmojiButton = ({
return (
<BaseMessageEmojiButton onClick={onClick} isDisabled={isDisabled} emoji={EmojiIcon} checked={checked} sx={sx}>
- <EmojiIcon style={{ height: "1em" }} />
{showCount && <span style={{ marginInlineEnd: "0.25em" }}>{emoji.count}</span>}
</BaseMessageEmojiButton>
);
| https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/2513 | 2023-04-14T10:24:05Z | 2023-04-14T10:29:12Z | 2023-04-14T10:29:12Z | 2023-04-14T10:29:13Z | 178 | LAION-AI/Open-Assistant | 37,677 | |
✏ Update Hypercorn link, now pointing to GitHub | diff --git a/README.md b/README.md
index 590abf17ea55e..bc00d9ed9ab86 100644
--- a/README.md
+++ b/README.md
@@ -131,7 +131,7 @@ $ pip install fastapi
</div>
-You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
+You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
<div class="termy">
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index 24ce14e235e98..97ec0ffcff746 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -128,7 +128,7 @@ $ pip install fastapi
</div>
-You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
+You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
<div class="termy">
| Updated Uvicorn link from gitlab to github to reflect current hosting
https://gitlab.com/pgjones/hypercorn/-/commit/65e539a9dc762cb19f4907038fe6d490dac909ff | https://api.github.com/repos/tiangolo/fastapi/pulls/5346 | 2022-09-04T09:07:43Z | 2022-09-04T14:56:29Z | 2022-09-04T14:56:29Z | 2022-09-04T14:56:29Z | 443 | tiangolo/fastapi | 22,792 |
add source nodes to sub_q engine | diff --git a/llama_index/query_engine/sub_question_query_engine.py b/llama_index/query_engine/sub_question_query_engine.py
index ac5b87b6bec8f..7da20e2288852 100644
--- a/llama_index/query_engine/sub_question_query_engine.py
+++ b/llama_index/query_engine/sub_question_query_engine.py
@@ -3,7 +3,7 @@
from typing import List, Optional, Sequence, cast
from llama_index.async_utils import run_async_tasks
-from llama_index.bridge.pydantic import BaseModel
+from llama_index.bridge.pydantic import BaseModel, Field
from llama_index.callbacks.base import CallbackManager
from llama_index.callbacks.schema import CBEventType, EventPayload
from llama_index.indices.query.base import BaseQueryEngine
@@ -28,7 +28,7 @@ class SubQuestionAnswerPair(BaseModel):
sub_q: SubQuestion
answer: Optional[str] = None
- sources: Optional[List[NodeWithScore]] = None
+ sources: List[NodeWithScore] = Field(default_factory=list)
class SubQuestionQueryEngine(BaseQueryEngine):
@@ -148,9 +148,11 @@ def _query(self, query_bundle: QueryBundle) -> RESPONSE_TYPE:
nodes = [self._construct_node(pair) for pair in qa_pairs]
+ source_nodes = [node for qa_pair in qa_pairs for node in qa_pair.sources]
response = self._response_synthesizer.synthesize(
query=query_bundle,
nodes=nodes,
+ additional_source_nodes=source_nodes,
)
query_event.on_end(payload={EventPayload.RESPONSE: response})
@@ -183,9 +185,11 @@ async def _aquery(self, query_bundle: QueryBundle) -> RESPONSE_TYPE:
nodes = [self._construct_node(pair) for pair in qa_pairs]
+ source_nodes = [node for qa_pair in qa_pairs for node in qa_pair.sources]
response = await self._response_synthesizer.asynthesize(
query=query_bundle,
nodes=nodes,
+ additional_source_nodes=source_nodes,
)
query_event.on_end(payload={EventPayload.RESPONSE: response})
| # Description
Small change to propagate source nodes to the final response object in the sub-question query engine.
Fixes #7978
## Type of Change
- [x] New feature (non-breaking change which adds functionality)
# How Has This Been Tested?
- [x] I stared at the code and made sure it makes sense
| https://api.github.com/repos/run-llama/llama_index/pulls/7981 | 2023-10-05T17:39:02Z | 2023-10-05T23:54:11Z | 2023-10-05T23:54:11Z | 2023-10-05T23:54:12Z | 468 | run-llama/llama_index | 6,595 |
qtrade safeSymbol | diff --git a/js/qtrade.js b/js/qtrade.js
index 1b797ebc9db2..e2dcab61545c 100644
--- a/js/qtrade.js
+++ b/js/qtrade.js
@@ -400,21 +400,8 @@ module.exports = class qtrade extends Exchange {
// "last_change":1588533365354609
// }
//
- let symbol = undefined;
const marketId = this.safeString (ticker, 'id_hr');
- if (marketId !== undefined) {
- if (marketId in this.markets_by_id) {
- market = this.markets_by_id[marketId];
- } else {
- const [ baseId, quoteId ] = marketId.split ('_');
- const base = this.safeCurrencyCode (baseId);
- const quote = this.safeCurrencyCode (quoteId);
- symbol = quote + '/' + base;
- }
- }
- if ((symbol === undefined) && (market !== undefined)) {
- symbol = market['symbol'];
- }
+ const symbol = this.safeSymbol (marketId, market, '_');
const timestamp = this.safeIntegerProduct (ticker, 'last_change', 0.001);
const previous = this.safeFloat (ticker, 'day_open');
const last = this.safeFloat (ticker, 'last');
@@ -648,21 +635,8 @@ module.exports = class qtrade extends Exchange {
timestamp = this.parse8601 (this.safeString (trade, 'created_at'));
}
const side = this.safeString (trade, 'side');
- let symbol = undefined;
const marketId = this.safeString (trade, 'market_string');
- if (marketId !== undefined) {
- if (marketId in this.markets_by_id) {
- market = this.markets_by_id[marketId];
- } else {
- const [ baseId, quoteId ] = marketId.split ('_');
- const base = this.safeCurrencyCode (baseId);
- const quote = this.safeCurrencyCode (quoteId);
- symbol = quote + '/' + base;
- }
- }
- if ((symbol === undefined) && (market !== undefined)) {
- symbol = market['symbol'];
- }
+ const symbol = this.safeSymbol (marketId, market, '_');
let cost = this.safeFloat2 (trade, 'base_volume', 'base_amount');
const price = this.safeFloat (trade, 'price');
const amount = this.safeFloat2 (trade, 'market_amount', 'amount');
@@ -885,21 +859,8 @@ module.exports = class qtrade extends Exchange {
} else {
status = 'closed';
}
- let symbol = undefined;
const marketId = this.safeString (order, 'market_string');
- if (marketId !== undefined) {
- if (marketId in this.markets_by_id) {
- market = this.markets_by_id[marketId];
- } else {
- const [ baseId, quoteId ] = marketId.split ('_');
- const base = this.safeCurrencyCode (baseId);
- const quote = this.safeCurrencyCode (quoteId);
- symbol = base + '/' + quote;
- }
- }
- if ((symbol === undefined) && (market !== undefined)) {
- symbol = market['symbol'];
- }
+ const symbol = this.safeSymbol (marketId, market, '_');
const rawTrades = this.safeValue (order, 'trades', []);
const parsedTrades = this.parseTrades (rawTrades, market, undefined, undefined, {
'order': id,
| https://api.github.com/repos/ccxt/ccxt/pulls/7702 | 2020-10-06T15:14:45Z | 2020-10-07T06:39:17Z | 2020-10-07T06:39:17Z | 2021-03-11T13:48:06Z | 810 | ccxt/ccxt | 13,358 | |
Update RedPajama 7B Chat | diff --git a/README.md b/README.md
index d73d586f47..0ef2dfd1c1 100644
--- a/README.md
+++ b/README.md
@@ -122,6 +122,7 @@ The following models are tested:
- [StabilityAI/stablelm-tuned-alpha-7b](https://huggingface.co/stabilityai/stablelm-tuned-alpha-7b)
- [THUDM/chatglm-6b](https://huggingface.co/THUDM/chatglm-6b)
- [timdettmers/guanaco-33b-merged](https://huggingface.co/timdettmers/guanaco-33b-merged)
+- [togethercomputer/RedPajama-INCITE-7B-Chat](https://huggingface.co/togethercomputer/RedPajama-INCITE-7B-Chat)
- [WizardLM/WizardLM-13B-V1.0](https://huggingface.co/WizardLM/WizardLM-13B-V1.0)
Help us [add more](https://github.com/lm-sys/FastChat/blob/main/docs/arena.md#how-to-add-a-new-model).
diff --git a/fastchat/model/model_registry.py b/fastchat/model/model_registry.py
index fe9da72cd5..4a0cf7c5a7 100644
--- a/fastchat/model/model_registry.py
+++ b/fastchat/model/model_registry.py
@@ -163,3 +163,9 @@ def get_model_info(name: str) -> ModelInfo:
"https://huggingface.co/openaccess-ai-collective/manticore-13b-chat-pyg",
"A chatbot fine-tuned from LlaMa across several CoT and chat datasets.",
)
+register_model_info(
+ ["redpajama-incite-7b-chat"],
+ "RedPajama-INCITE-7B-Chat",
+ "https://huggingface.co/togethercomputer/RedPajama-INCITE-7B-Chat",
+ "A chatbot fine-tuned from RedPajama-INCITE-7B-Base by Together",
+)
| <!-- Thank you for your contribution! -->
## Why are these changes needed?
Together has recently released the v1 model, and we might want to update the model information accordingly.
Model card: https://huggingface.co/togethercomputer/RedPajama-INCITE-7B-Chat
Release blog: https://www.together.xyz/blog/redpajama-7b
The redpajama adapter has already been added through #1319. Therefore, the only updates required would be to the model link and register.
I run this cmd and it works out-of-the-box.
```bash
python3 -m fastchat.serve.cli --model-path togethercomputer/RedPajama-INCITE-7B-Chat --debug
```
Please let me know if there are any other actions that need to be taken.
## Related issue number (if applicable)
NA
## Checks
- [x] I've run `format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed.
- [ ] I've made sure the relevant tests are passing (if applicable).
| https://api.github.com/repos/lm-sys/FastChat/pulls/1665 | 2023-06-12T08:34:07Z | 2023-06-14T09:44:44Z | 2023-06-14T09:44:44Z | 2023-06-14T09:44:45Z | 477 | lm-sys/FastChat | 41,149 |
Add Blynk-cloud API | diff --git a/README.md b/README.md
index 0925bb0d7d..05749a420d 100644
--- a/README.md
+++ b/README.md
@@ -366,6 +366,7 @@ API | Description | Auth | HTTPS | CORS |
| [Base](https://www.base-api.io/) | Building quick backends | `apiKey` | Yes | Yes |
| [Bitbucket](https://developer.atlassian.com/bitbucket/api/2/reference/) | Bitbucket API | `OAuth` | Yes | Unknown |
| [Blitapp](https://blitapp.com/api/) | Schedule screenshots of web pages and sync them to your cloud | `apiKey` | Yes | Unknown |
+| [Blynk-Cloud](https://blynkapi.docs.apiary.io/#) | Control IoT Devices from Blynk IoT Cloud | `apiKey` | No | Unknown |
| [Bored](https://www.boredapi.com/) | Find random activities to fight boredom | No | Yes | Unknown |
| [Browshot](https://browshot.com/api/documentation) | Easily make screenshots of web pages in any screen size, as any device | `apiKey` | Yes | Yes |
| [CDNJS](https://api.cdnjs.com/libraries/jquery) | Library info on CDNJS | No | 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> | https://api.github.com/repos/public-apis/public-apis/pulls/2231 | 2021-10-04T09:37:39Z | 2021-10-08T04:49:00Z | 2021-10-08T04:49:00Z | 2021-10-08T04:49:01Z | 291 | public-apis/public-apis | 35,365 |
Add timeout while searching for git diffs in LLMs response | diff --git a/gpt_engineer/core/chat_to_files.py b/gpt_engineer/core/chat_to_files.py
index 7fd5097844..12590c051a 100644
--- a/gpt_engineer/core/chat_to_files.py
+++ b/gpt_engineer/core/chat_to_files.py
@@ -26,6 +26,8 @@
from typing import Dict, Tuple
+from regex import regex
+
from gpt_engineer.core.diff import ADD, REMOVE, RETAIN, Diff, Hunk
from gpt_engineer.core.files_dict import FilesDict, file_to_lines_dict
@@ -134,17 +136,20 @@ def parse_diffs(diff_string: str) -> dict:
- dict: A dictionary of Diff objects keyed by filename.
"""
# Regex to match individual diff blocks
- diff_block_pattern = re.compile(
+ diff_block_pattern = regex.compile(
r"```.*?\n\s*?--- .*?\n\s*?\+\+\+ .*?\n(?:@@ .*? @@\n(?:[-+ ].*?\n)*?)*?```",
re.DOTALL,
)
diffs = {}
- for block in diff_block_pattern.finditer(diff_string):
- diff_block = block.group()
-
- # Parse individual diff blocks and update the diffs dictionary
- diffs.update(parse_diff_block(diff_block))
+ try:
+ for block in diff_block_pattern.finditer(diff_string, timeout=1):
+ diff_block = block.group()
+
+ # Parse individual diff blocks and update the diffs dictionary
+ diffs.update(parse_diff_block(diff_block))
+ except TimeoutError:
+ print("gpt-engineer timed out while parsing git diff")
if not diffs:
print(
diff --git a/poetry.lock b/poetry.lock
index fc3603f758..f28ce55140 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -4272,4 +4272,4 @@ test = []
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.13"
-content-hash = "b5e12ad6250bdc25ba945bdfe8d67c216127dacefbb3977def0546061f5be3df"
+content-hash = "455d13a418ad9dcba9e59303a5d6396b5081e87bbe9bc3e59cfce6c6ae435fff"
diff --git a/pyproject.toml b/pyproject.toml
index 8e70d18939..bc96694a7c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,6 +32,7 @@ langchain_openai = "*"
toml = ">=0.10.2"
pyperclip = "^1.8.2"
langchain-anthropic = "^0.1.1"
+regex = "^2023.12.25"
[tool.poetry.group.dev.dependencies]
pytest = ">=7.3.1"
| - Add `regex` dependency | https://api.github.com/repos/gpt-engineer-org/gpt-engineer/pulls/1067 | 2024-03-17T16:21:23Z | 2024-03-18T07:46:02Z | 2024-03-18T07:46:02Z | 2024-03-18T07:46:02Z | 672 | gpt-engineer-org/gpt-engineer | 33,285 |
Security Fix for Remote Code Execution - huntr.dev | diff --git a/hackingtool.py b/hackingtool.py
index 57019057..284874bf 100644
--- a/hackingtool.py
+++ b/hackingtool.py
@@ -2,6 +2,7 @@
# -*- coding: UTF-8 -*-
# Version 1.1.0
import os
+import subprocess
import sys
import webbrowser
import socket
@@ -246,7 +247,7 @@ def dracnmap(self):
def ports(self):
self.clear_scr()
target = input('Select a Target IP: ')
- os.system(f"sudo nmap -O -Pn {target}")
+ subprocess.run(["sudo", "nmap", "-O", "-Pn", f"{target}"])
input('\nPress Enter to back...')
self.info()
@@ -378,7 +379,8 @@ def striker(self):
if choice == "2":
site = input("Enter Site Name (example.com) >> ")
- os.system(f"cd Striker && sudo python3 striker.py {site}")
+ os.system(f"cd Striker")
+ subprocess.run(["sudo", "python3", "striker.py", f"{site}"])
self.striker()
if choice == "99":
@@ -426,7 +428,7 @@ def portscanner(self):
if choice == "2":
ip = input("Enter Ip >> ")
- os.system(f"cd rang3r;sudo python rang3r.py --ip {ip}")
+ subprocess.run(["sudo", "python", "./rang3r/rang3r.py", "--ip", f"{ip}"])
self.portscanner()
if choice == "99":
@@ -1641,12 +1643,12 @@ def steganohide(self):
if choice_run == "1":
file_hide = input("Enter Filename you want to Embed (1.txt) >> ")
file_to_be_hide = input("Enter Cover Filename(test.jpeg) >> ")
- os.system(f"steghide embed -cf {file_to_be_hide} -ef {file_hide}")
+ subprocess.run(["steghide", "embed", "-cf", f"{file_to_be_hide}", "-ef", f"{file_hide}"])
self.steganohide()
if choice_run == "2":
from_file = input("Enter Filename From Extract Data >> ")
- os.system(f"steghide extract -sf {from_file}")
+ subprocess.run(["steghide", "extract", "-sf", f"{from_file}"])
self.steganohide()
if choice_run == '99':
@@ -1669,7 +1671,7 @@ def stegnocracker(self):
if choice == "2":
filename = input("Enter Filename:- ")
passfile = input("Enter Wordlist Filename:- ")
- os.system(f"stegcracker {filename} {passfile}")
+ subprocess.run(["stegcracker", f"{filename}", f"{passfile}"])
self.stegnocracker()
if choice == "99":
@@ -1917,7 +1919,8 @@ def instabrute(self):
if choice == "2":
name = input("Enter Username >> ")
wordlist = input("Enter wordword list >> ")
- os.system(f"cd instaBrute;sudo python instaBrute.py -u {name} -d {wordlist}")
+ os.system(f"cd instaBrute")
+ subprocess.run(["sudo", "python", "instaBrute.py", "-u", f"{name}", "-d", f"{wordlist}"])
self.instabrute()
if choice == "99":
@@ -1957,7 +1960,8 @@ def faceshell(self):
if choice == "2":
name = input("Enter Username >> ")
wordlist = input("Enter Wordlist >> ")
- os.system(f"cd Brute_Force;python3 Brute_Force.py -f {name} -l {wordlist}")
+ os.system("cd Brute_Force")
+ subprocess.run("python3", "Brute_Force.py", "-f", f"{name}", "-l", f"{wordlist}")
self.faceshell()
if choice == "99":
@@ -2376,7 +2380,8 @@ def sherlock(self):
if choice == "2":
name = input("Enter Username >> ")
- os.system(f"cd sherlock ;sudo python3 sherlock {name}")
+ os.system("cd sherlock")
+ subprocess.run(["sudo", "python3", "sherlock", f"{name}"])
self.sherlock()
if choice == "99":
@@ -2395,7 +2400,7 @@ def socialscan(self):
if choice == "2":
name = input("Enter Username or Emailid (if both then please space between email & username) >> ")
- os.system(f"sudo socialscan {name}")
+ subprocess.run(["sudo", "socialscan", f"{name}"])
self.socialscan()
if choice == "99":
@@ -2570,7 +2575,7 @@ def apk2gold(self):
if choice == "2":
uinput = input("Enter (.apk) File >> ")
- os.system("sudo apk2gold {0}".format(uinput))
+ subprocess.run(["sudo", "apk2gold", "{0}".format(uinput)])
if choice == "99":
self.reversetool()
@@ -2629,7 +2634,7 @@ def slowloris(self):
if choice == "2":
target_site = input("Enter Target Site:- ")
- os.system(f"slowloris {target_site}")
+ subprocess.run(["slowloris", f"{target_site}"])
self.slowloris()
if choice == "99":
@@ -2651,7 +2656,8 @@ def asyncrone(self):
source_port = input("Enter Source Port >> ")
target_ip = input("Enter Target IP >> ")
target_port = input("Enter Target port >> ")
- os.system(f"cd aSYNcrone;sudo ./aSYNcrone {source_port} {target_ip} {target_port} 1000")
+ os.system(f"cd aSYNcrone")
+ subprocess.run(["sudo", "./aSYNcrone", f"{source_port}", f"{target_ip}", f"{target_port}", "1000"])
self.asyncrone()
if choice == "99":
@@ -2922,7 +2928,8 @@ def xsscon(self):
if choice == "2":
website = input("Enter Website >> ")
- os.system(f"cd XSSCon;python3 xsscon.py -u {website}")
+ os.system("cd XSSCon")
+ subprocess.run(["python3", "xsscon.py", "-u", f"{website}"])
self.xsscon()
if choice == "99":
| https://huntr.dev/users/Mik317 has fixed the Remote Code Execution vulnerability 🔨. Mik317 has been awarded $25 for fixing the vulnerability through the huntr bug bounty program 💵. Think you could fix a vulnerability like this?
Get involved at https://huntr.dev/
Q | A
Version Affected | ALL
Bug Fix | YES
Original Pull Request | https://github.com/418sec/hackingtool/pull/1
Vulnerability README | https://github.com/418sec/huntr/blob/master/bounties/pip/hackingtool/1/README.md
### User Comments:
### 📊 Metadata *
_Please enter the direct URL for this bounty on huntr.dev. This is compulsory and will help us process your bounty submission quicker._
#### Bounty URL: https://www.huntr.dev/bounties/1-pip-hackingtool
### ⚙️ Description *
The issue consisted in a `arbitrary command injection` which was possible due to the usage of `os.system`, which was used to `execute` commands formatted with `user-supplied` inputs, without any check.
### 💻 Technical Description *
The issue has been fixed using the `subprocess.run()` method, which belongs to a native library (`subprocess`) and is similar to `execFile` in Node. It takes the `name` of the program and then all the `arguments` which contain `user supplied` input and makes sure not to evaluate them as `commands` even if bash characters like `||` or `;` are inserted as `input`, fixing the vulnerability.
**Reference: **
- https://supakeen.com/weblog/executing-commands-safely-from-python.html
### 🐛 Proof of Concept (PoC) *
1. `python3 hackingtool.py`
2. Choose option `01` --> `3`
3. Insert the option `Run` and when a `IP` is requested, insert the following: `evil.com || touch HACKED #`
4. A file named `HACKED` will be created
### 🔥 Proof of Fix (PoF) *
Same steps of above with the fixed version
### 👍 User Acceptance Testing (UAT)
`subprocess.run()` has the same functionality of `os.system()` and `real time` outputs are enabled by default, so nothing works wrong :smile: | https://api.github.com/repos/Z4nzu/hackingtool/pulls/78 | 2020-08-10T14:01:10Z | 2020-08-12T06:24:32Z | 2020-08-12T06:24:32Z | 2020-10-30T10:47:39Z | 1,533 | Z4nzu/hackingtool | 9,867 |
Decode URL to utf-8 before joining. | diff --git a/requests/models.py b/requests/models.py
index 1b143b0e16..4e747c8453 100644
--- a/requests/models.py
+++ b/requests/models.py
@@ -227,6 +227,8 @@ def build(resp):
# Facilitate non-RFC2616-compliant 'location' headers
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
if not urlparse(url).netloc:
+ if not isinstance(url, unicode):
+ url = url.decode('utf-8', 'ignore')
url = urljoin(r.url, url)
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
| To avoid UnicodeDecodeError's like on http://blip.fm/~1abvfu
Note: This doesn't have a test, which sucks, because for the life of me I can't seem to figure out how to trigger this error with httpbin. Maybe flask has better handling of UTF-8 characters than the server used at blip.fm and others? Really not sure.
Here's an ad-hoc test for you:
Before:
```
>>> import requests
>>> requests.head('http://blip.fm/~1abvfu', allow_redirects=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/api.py", line 73, in head
return request('head', url, **kwargs)
File "requests/api.py", line 39, in request
return s.request(method=method, url=url, **kwargs)
File "requests/sessions.py", line 200, in request
r.send(prefetch=prefetch)
File "requests/models.py", line 559, in send
self._build_response(r)
File "requests/models.py", line 232, in _build_response
url = urljoin(r.url, url)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urlparse.py", line 219, in urljoin
params, query, fragment))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urlparse.py", line 184, in urlunparse
return urlunsplit((scheme, netloc, url, query, fragment))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urlparse.py", line 190, in urlunsplit
url = '//' + (netloc or '') + url
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 62: ordinal not in range(128)
```
After:
```
>>> import requests
>>> requests.head('http://blip.fm/~1abvfu', allow_redirects=True)
<Response [200]>
```
| https://api.github.com/repos/psf/requests/pulls/461 | 2012-02-28T17:15:36Z | 2012-03-08T22:58:00Z | 2012-03-08T22:58:00Z | 2021-09-08T23:05:23Z | 175 | psf/requests | 33,014 |
R.1: Fix finally link | diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md
index 5b9a5ef65..77fe19781 100644
--- a/CppCoreGuidelines.md
+++ b/CppCoreGuidelines.md
@@ -8682,7 +8682,7 @@ What is `Port`? A handy wrapper that encapsulates the resource:
##### Note
-Where a resource is "ill-behaved" in that it isn't represented as a class with a destructor, wrap it in a class or use [`finally`](#S-gsl)
+Where a resource is "ill-behaved" in that it isn't represented as a class with a destructor, wrap it in a class or use [`finally`](#Re-finally)
**See also**: [RAII](#Rr-raii).
| https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1031 | 2017-09-18T16:53:24Z | 2017-09-18T18:06:41Z | 2017-09-18T18:06:41Z | 2017-09-18T18:06:47Z | 180 | isocpp/CppCoreGuidelines | 15,411 | |
Update certbot-auto modification checks | diff --git a/.azure-pipelines/templates/jobs/standard-tests-jobs.yml b/.azure-pipelines/templates/jobs/standard-tests-jobs.yml
index 62f22b22367..c949af44a9a 100644
--- a/.azure-pipelines/templates/jobs/standard-tests-jobs.yml
+++ b/.azure-pipelines/templates/jobs/standard-tests-jobs.yml
@@ -56,6 +56,8 @@ jobs:
apache-compat:
IMAGE_NAME: ubuntu-18.04
TOXENV: apache_compat
+ # le-modification can be moved to the extended test suite once
+ # https://github.com/certbot/certbot/issues/8742 is resolved.
le-modification:
IMAGE_NAME: ubuntu-18.04
TOXENV: modification
diff --git a/letsencrypt-auto-source/letsencrypt-auto b/letsencrypt-auto-source/letsencrypt-auto
index 9ddc7e0764e..c37c45596ef 100755
--- a/letsencrypt-auto-source/letsencrypt-auto
+++ b/letsencrypt-auto-source/letsencrypt-auto
@@ -31,7 +31,7 @@ if [ -z "$VENV_PATH" ]; then
fi
VENV_BIN="$VENV_PATH/bin"
BOOTSTRAP_VERSION_PATH="$VENV_PATH/certbot-auto-bootstrap-version.txt"
-LE_AUTO_VERSION="1.15.0.dev0"
+LE_AUTO_VERSION="1.14.0"
BASENAME=$(basename $0)
USAGE="Usage: $BASENAME [OPTIONS]
A self-updating wrapper script for the Certbot ACME client. When run, updates
diff --git a/tests/modification-check.py b/tests/modification-check.py
index 357b253509b..8f3ae126461 100755
--- a/tests/modification-check.py
+++ b/tests/modification-check.py
@@ -1,122 +1,58 @@
#!/usr/bin/env python
+"""Ensures there have been no changes to important certbot-auto files."""
-from __future__ import print_function
-
+import hashlib
import os
-import shutil
-import subprocess
-import sys
-import tempfile
-from urllib.request import urlretrieve
-def find_repo_path():
+# Relative to the root of the Certbot repo, these files are expected to exist
+# and have the SHA-256 hashes contained in this dictionary. These hashes were
+# taken from our v1.14.0 tag which was the last release we intended to make
+# changes to certbot-auto.
+#
+# certbot-auto, letsencrypt-auto, and letsencrypt-auto-source/certbot-auto.asc
+# can be removed from this dict after coordinating with tech ops to ensure we
+# get the behavior we want from https://dl.eff.org. See
+# https://github.com/certbot/certbot/issues/8742 for more info.
+#
+# Deleting letsencrypt-auto-source/letsencrypt-auto and
+# letsencrypt-auto-source/letsencrypt-auto.sig can be done once we're
+# comfortable breaking any certbot-auto scripts that haven't already updated to
+# the last version. See
+# https://opensource.eff.org/eff-open-source/pl/65geri7c4tr6iqunc1rpb3mpna for
+# more info.
+EXPECTED_FILES = {
+ 'certbot-auto':
+ 'b997e3608526650a08e36e682fc3bf0c29903c06fa5ba4cc49308c43832450c2',
+ 'letsencrypt-auto':
+ 'b997e3608526650a08e36e682fc3bf0c29903c06fa5ba4cc49308c43832450c2',
+ os.path.join('letsencrypt-auto-source', 'letsencrypt-auto'):
+ 'b997e3608526650a08e36e682fc3bf0c29903c06fa5ba4cc49308c43832450c2',
+ os.path.join('letsencrypt-auto-source', 'certbot-auto.asc'):
+ '0558ba7bd816732b38c092e8fedb6033dad01f263e290ec6b946263aaf6625a8',
+ os.path.join('letsencrypt-auto-source', 'letsencrypt-auto.sig'):
+ '61c036aabf75da350b0633da1b2bef0260303921ecda993455ea5e6d3af3b2fe',
+}
+
+
+def find_repo_root():
return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
-# We do not use filecmp.cmp to take advantage of universal newlines
-# handling in open() for Python 3.x and be insensitive to CRLF/LF when run on Windows.
-# As a consequence, this function will not work correctly if executed by Python 2.x on Windows.
-# But it will work correctly on Linux for any version, because every file tested will be LF.
-def compare_files(path_1, path_2):
- l1 = l2 = True
- with open(path_1, 'r') as f1, open(path_2, 'r') as f2:
- line = 1
- while l1 and l2:
- line += 1
- l1 = f1.readline()
- l2 = f2.readline()
- if l1 != l2:
- print('---')
- print((
- 'While comparing {0} (1) and {1} (2), a difference was found at line {2}:'
- .format(os.path.basename(path_1), os.path.basename(path_2), line)))
- print('(1): {0}'.format(repr(l1)))
- print('(2): {0}'.format(repr(l2)))
- print('---')
- return False
-
- return True
-
-def validate_scripts_content(repo_path, temp_cwd):
- errors = False
-
- if not compare_files(
- os.path.join(repo_path, 'certbot-auto'),
- os.path.join(repo_path, 'letsencrypt-auto')):
- print('Root certbot-auto and letsencrypt-auto differ.')
- errors = True
- else:
- shutil.copyfile(
- os.path.join(repo_path, 'certbot-auto'),
- os.path.join(temp_cwd, 'local-auto'))
- shutil.copy(os.path.normpath(os.path.join(
- repo_path,
- 'letsencrypt-auto-source/pieces/fetch.py')), temp_cwd)
- # Compare file against current version in the target branch
- branch = os.environ.get('TARGET_BRANCH', 'master')
- url = (
- 'https://raw.githubusercontent.com/certbot/certbot/{0}/certbot-auto'
- .format(branch))
- urlretrieve(url, os.path.join(temp_cwd, 'certbot-auto'))
+def sha256_hash(filename):
+ hash_object = hashlib.sha256()
+ with open(filename, 'rb') as f:
+ hash_object.update(f.read())
+ return hash_object.hexdigest()
- if compare_files(
- os.path.join(temp_cwd, 'certbot-auto'),
- os.path.join(temp_cwd, 'local-auto')):
- print('Root *-auto were unchanged')
- else:
- # Compare file against the latest released version
- latest_version = subprocess.check_output(
- [sys.executable, 'fetch.py', '--latest-version'], cwd=temp_cwd)
- subprocess.check_call(
- [sys.executable, 'fetch.py', '--le-auto-script',
- 'v{0}'.format(latest_version.decode().strip())], cwd=temp_cwd)
- if compare_files(
- os.path.join(temp_cwd, 'letsencrypt-auto'),
- os.path.join(temp_cwd, 'local-auto')):
- print('Root *-auto were updated to the latest version.')
- else:
- print('Root *-auto have unexpected changes.')
- errors = True
-
- return errors
def main():
- repo_path = find_repo_path()
- temp_cwd = tempfile.mkdtemp()
- errors = False
-
- try:
- errors = validate_scripts_content(repo_path, temp_cwd)
-
- shutil.copyfile(
- os.path.normpath(os.path.join(repo_path, 'letsencrypt-auto-source/letsencrypt-auto')),
- os.path.join(temp_cwd, 'original-lea')
- )
- subprocess.check_call([sys.executable, os.path.normpath(os.path.join(
- repo_path, 'letsencrypt-auto-source/build.py'))])
- shutil.copyfile(
- os.path.normpath(os.path.join(repo_path, 'letsencrypt-auto-source/letsencrypt-auto')),
- os.path.join(temp_cwd, 'build-lea')
- )
- shutil.copyfile(
- os.path.join(temp_cwd, 'original-lea'),
- os.path.normpath(os.path.join(repo_path, 'letsencrypt-auto-source/letsencrypt-auto'))
- )
-
- if not compare_files(
- os.path.join(temp_cwd, 'original-lea'),
- os.path.join(temp_cwd, 'build-lea')):
- print('Script letsencrypt-auto-source/letsencrypt-auto '
- 'doesn\'t match output of build.py.')
- errors = True
- else:
- print('Script letsencrypt-auto-source/letsencrypt-auto matches output of build.py.')
- finally:
- shutil.rmtree(temp_cwd)
+ repo_root = find_repo_root()
+ for filename, expected_hash in EXPECTED_FILES.items():
+ filepath = os.path.join(repo_root, filename)
+ assert sha256_hash(filepath) == expected_hash, f'unexpected changes to {filepath}'
+ print('All certbot-auto files have correct hashes.')
- return errors
if __name__ == '__main__':
- if main():
- sys.exit(1)
+ main()
diff --git a/tox.ini b/tox.ini
index ada7002daf1..90aecc1b3a6 100644
--- a/tox.ini
+++ b/tox.ini
@@ -4,7 +4,7 @@
[tox]
skipsdist = true
-envlist = modification,py3-cover,lint,mypy
+envlist = py3-cover,lint,mypy
[base]
# pip installs the requested packages in editable mode
@@ -182,12 +182,9 @@ commands =
{[base]pip_install} acme certbot certbot-apache certbot-nginx
python certbot-compatibility-test/nginx/roundtrip.py certbot-compatibility-test/nginx/nginx-roundtrip-testdata
-# This is a duplication of the command line in testenv:le_auto to
-# allow users to run the modification check by running `tox`
[testenv:modification]
commands =
python {toxinidir}/tests/modification-check.py
-passenv = TARGET_BRANCH
[testenv:apache_compat]
commands =
| Fixes https://github.com/certbot/certbot/issues/8743.
I deviated from that issue a bit in that I'm also checking for incorrect modifications to *-auto in the repo root and `letsencrypt-auto-source/certbot-auto.asc`. The script was previously checking *-auto in the repo root and probably should have also been checking `certbot-auto.asc`. I think it's worth continuing to check these files and run this test on all PRs until https://github.com/certbot/certbot/issues/8742 is resolved because I think https://dl.eff.org is pulling from Certbot's `master` branch.
Another noteworthy change in this PR is the modification tests will fail on Windows if you have `git` configured to automatically convert files to CRLF line endings. We ignored differences in line endings before, but I think we actually want to be checking that the files are byte for byte identical. If we accidentally commit the file with the wrong line endings, things will break. To make exact comparisons while making things less annoying for anyone running tests on Windows, I removed `modification` from the default list of `tox` environments. Since no one should be making changes to certbot-auto anymore and we're planning to delete the majority of the files in the near future, this seems like a decent compromise to me personally. | https://api.github.com/repos/certbot/certbot/pulls/8805 | 2021-04-23T23:15:30Z | 2021-04-26T20:50:11Z | 2021-04-26T20:50:11Z | 2021-04-26T20:50:12Z | 2,397 | certbot/certbot | 1,791 |
[6.i Support SERPER api] Integrate Serper API intop searchandsummarize Action | diff --git a/config/config.yaml b/config/config.yaml
index b0264e908..30168d81e 100644
--- a/config/config.yaml
+++ b/config/config.yaml
@@ -26,6 +26,8 @@ RPM: 10
#GOOGLE_API_KEY: "YOUR_API_KEY"
## Visit https://programmablesearchengine.google.com/controlpanel/create to get id.
#GOOGLE_CSE_ID: "YOUR_CSE_ID"
+## Visit https://serper.dev/ to get key.
+#SERPER_API_KEY: "YOUR_API_KEY"
#### for TTS
diff --git a/examples/search_with_specific_engine.py b/examples/search_with_specific_engine.py
new file mode 100644
index 000000000..81333bf83
--- /dev/null
+++ b/examples/search_with_specific_engine.py
@@ -0,0 +1,15 @@
+import asyncio
+from metagpt.config import Config
+from metagpt.roles import Searcher
+from metagpt.tools import SearchEngineType
+
+async def main():
+ # Serper API
+ await Searcher(engine = SearchEngineType.SERPER_GOOGLE).run("What are some good sun protection products?")
+ # Serper API
+ #await Searcher(engine = SearchEngineType.SERPAPI_GOOGLE).run("What are the best ski brands for skiers?")
+ # Google API
+ #await Searcher(engine = SearchEngineType.DIRECT_GOOGLE).run("What are the most interesting human facts?")
+
+if __name__ == '__main__':
+ asyncio.run(main())
diff --git a/metagpt/actions/search_and_summarize.py b/metagpt/actions/search_and_summarize.py
index 06ddc5daf..7dce790d2 100644
--- a/metagpt/actions/search_and_summarize.py
+++ b/metagpt/actions/search_and_summarize.py
@@ -110,10 +110,14 @@ def __init__(self, name="", context=None, llm=None, engine=None, search_func=Non
super().__init__(name, context, llm)
async def run(self, context: list[Message], system_text=SEARCH_AND_SUMMARIZE_SYSTEM) -> str:
- if not self.config.serpapi_api_key or 'YOUR_API_KEY' == self.config.serpapi_api_key:
- logger.warning('Configure SERPAPI_API_KEY to unlock full feature')
+ no_serpapi = not self.config.serpapi_api_key or 'YOUR_API_KEY' == self.config.serpapi_api_key
+ no_serper = not self.config.serper_api_key or 'YOUR_API_KEY' == self.config.serper_api_key
+ no_google= not self.config.google_api_key or 'YOUR_API_KEY' == self.config.google_api_key
+
+ if no_serpapi and no_google and no_serper:
+ logger.warning('Configure one of SERPAPI_API_KEY, SERPER_API_KEY, GOOGLE_API_KEY to unlock full feature')
return ""
-
+
query = context[-1].content
# logger.debug(query)
rsp = await self.search_engine.run(query)
diff --git a/metagpt/config.py b/metagpt/config.py
index 5c6693dd8..e60bc1927 100644
--- a/metagpt/config.py
+++ b/metagpt/config.py
@@ -55,6 +55,7 @@ def __init__(self, yaml_file=default_yaml_file):
self.deployment_id = self._get('DEPLOYMENT_ID')
self.serpapi_api_key = self._get('SERPAPI_API_KEY')
+ self.serper_api_key = self._get('SERPER_API_KEY')
self.google_api_key = self._get('GOOGLE_API_KEY')
self.google_cse_id = self._get('GOOGLE_CSE_ID')
self.search_engine = self._get('SEARCH_ENGINE', SearchEngineType.SERPAPI_GOOGLE)
diff --git a/metagpt/roles/seacher.py b/metagpt/roles/seacher.py
index 8e9f5c417..c4f3ffb56 100644
--- a/metagpt/roles/seacher.py
+++ b/metagpt/roles/seacher.py
@@ -5,17 +5,33 @@
@Author : alexanderwu
@File : seacher.py
"""
+from metagpt.logs import logger
+
from metagpt.roles import Role
-from metagpt.actions import SearchAndSummarize
+from metagpt.actions import SearchAndSummarize, ActionOutput
from metagpt.tools import SearchEngineType
-
+from metagpt.schema import Message
class Searcher(Role):
def __init__(self, name='Alice', profile='Smart Assistant', goal='Provide search services for users',
- constraints='Answer is rich and complete', **kwargs):
+ constraints='Answer is rich and complete', engine=SearchEngineType.SERPAPI_GOOGLE, **kwargs):
super().__init__(name, profile, goal, constraints, **kwargs)
- self._init_actions([SearchAndSummarize])
+ self._init_actions([SearchAndSummarize(engine = engine)])
def set_search_func(self, search_func):
action = SearchAndSummarize("", engine=SearchEngineType.CUSTOM_ENGINE, search_func=search_func)
self._init_actions([action])
+
+ async def _act_sp(self) -> Message:
+ logger.info(f"{self._setting}: ready to {self._rc.todo}")
+ response = await self._rc.todo.run(self._rc.memory.get(k=0))
+ # logger.info(response)
+ if isinstance(response, ActionOutput):
+ msg = Message(content=response.content, instruct_content=response.instruct_content,
+ role=self.profile, cause_by=type(self._rc.todo))
+ else:
+ msg = Message(content=response, role=self.profile, cause_by=type(self._rc.todo))
+ self._rc.memory.add(msg)
+
+ async def _act(self) -> Message:
+ return await self._act_sp()
\ No newline at end of file
diff --git a/metagpt/tools/__init__.py b/metagpt/tools/__init__.py
index f42d46457..46ee0a0a0 100644
--- a/metagpt/tools/__init__.py
+++ b/metagpt/tools/__init__.py
@@ -13,4 +13,5 @@
class SearchEngineType(Enum):
SERPAPI_GOOGLE = auto()
DIRECT_GOOGLE = auto()
+ SERPER_GOOGLE = auto()
CUSTOM_ENGINE = auto()
diff --git a/metagpt/tools/search_engine.py b/metagpt/tools/search_engine.py
index 83eab3fc0..5b9e1cd23 100644
--- a/metagpt/tools/search_engine.py
+++ b/metagpt/tools/search_engine.py
@@ -14,6 +14,7 @@
from metagpt.config import Config
from metagpt.tools.search_engine_serpapi import SerpAPIWrapper
+from metagpt.tools.search_engine_serper import SerperWrapper
config = Config()
from metagpt.tools import SearchEngineType
@@ -44,6 +45,12 @@ async def run(self, query, max_results=8):
rsp = await api.run(query)
elif self.engine == SearchEngineType.DIRECT_GOOGLE:
rsp = SearchEngine.run_google(query, max_results)
+ elif self.engine == SearchEngineType.SERPER_GOOGLE:
+ api = SerperWrapper()
+ if isinstance(query, list):
+ rsp = await api.run(query)
+ elif isinstance(query, str):
+ rsp = await api.run([query])
elif self.engine == SearchEngineType.CUSTOM_ENGINE:
rsp = self.run_func(query)
else:
diff --git a/metagpt/tools/search_engine_serper.py b/metagpt/tools/search_engine_serper.py
new file mode 100644
index 000000000..91a8afce9
--- /dev/null
+++ b/metagpt/tools/search_engine_serper.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@Time : 2023/5/23 18:27
+@Author : alexanderwu
+@File : search_engine_serpapi.py
+"""
+from typing import Any, Dict, Optional, Tuple
+from metagpt.logs import logger
+import aiohttp
+import json
+from pydantic import BaseModel, Field
+
+from metagpt.config import Config
+
+
+class SerperWrapper(BaseModel):
+ """Wrapper around SerpAPI.
+
+ To use, you should have the ``google-search-results`` python package installed,
+ and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass
+ `serpapi_api_key` as a named parameter to the constructor.
+ """
+
+ search_engine: Any #: :meta private:
+ payload: dict = Field(
+ default={
+ "page": 1,
+ "num": 10
+ }
+ )
+ config = Config()
+ serper_api_key: Optional[str] = config.serper_api_key
+ aiosession: Optional[aiohttp.ClientSession] = None
+
+ class Config:
+ arbitrary_types_allowed = True
+
+ async def run(self, query: str, **kwargs: Any) -> str:
+ """Run query through Serper and parse result async."""
+ return ";".join([self._process_response(res) for res in await self.results(query)])
+
+ async def results(self, queries: list[str]) -> dict:
+ """Use aiohttp to run query through Serper and return the results async."""
+
+ def construct_url_and_payload_and_headers() -> Tuple[str, Dict[str, str]]:
+ payloads = self.get_payloads(queries)
+ url = "https://google.serper.dev/search"
+ headers = self.get_headers()
+ return url, payloads, headers
+
+ url, payloads, headers = construct_url_and_payload_and_headers()
+ if not self.aiosession:
+ async with aiohttp.ClientSession() as session:
+ async with session.post(url, data=payloads, headers=headers) as response:
+ res = await response.json()
+
+ else:
+ async with self.aiosession.get.post(url, data=payloads, headers=headers) as response:
+ res = await response.json()
+
+ return res
+
+ def get_payloads(self, queries: list[str]) -> Dict[str, str]:
+ """Get payloads for Serper."""
+ payloads = []
+ for query in queries:
+ _payload = {
+ "q": query,
+ }
+ payloads.append({**self.payload, **_payload})
+ return json.dumps(payloads, sort_keys=True)
+
+ def get_headers(self) -> Dict[str, str]:
+ headers = {
+ 'X-API-KEY': self.serper_api_key,
+ 'Content-Type': 'application/json'
+ }
+ return headers
+
+ @staticmethod
+ def _process_response(res: dict) -> str:
+ """Process response from SerpAPI."""
+ # logger.debug(res)
+ focus = ['title', 'snippet', 'link']
+ def get_focused(x): return {i: j for i, j in x.items() if i in focus}
+
+ if "error" in res.keys():
+ raise ValueError(f"Got error from SerpAPI: {res['error']}")
+ if "answer_box" in res.keys() and "answer" in res["answer_box"].keys():
+ toret = res["answer_box"]["answer"]
+ elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys():
+ toret = res["answer_box"]["snippet"]
+ elif (
+ "answer_box" in res.keys()
+ and "snippet_highlighted_words" in res["answer_box"].keys()
+ ):
+ toret = res["answer_box"]["snippet_highlighted_words"][0]
+ elif (
+ "sports_results" in res.keys()
+ and "game_spotlight" in res["sports_results"].keys()
+ ):
+ toret = res["sports_results"]["game_spotlight"]
+ elif (
+ "knowledge_graph" in res.keys()
+ and "description" in res["knowledge_graph"].keys()
+ ):
+ toret = res["knowledge_graph"]["description"]
+ elif "snippet" in res["organic"][0].keys():
+ toret = res["organic"][0]["snippet"]
+ else:
+ toret = "No good search result found"
+
+ toret_l = []
+ if "answer_box" in res.keys() and "snippet" in res["answer_box"].keys():
+ toret_l += [get_focused(res["answer_box"])]
+ if res.get("organic"):
+ toret_l += [get_focused(i) for i in res.get("organic")]
+
+ return str(toret) + '\n' + str(toret_l)
| - Add new API Key field in config file
- Create wrapper class for Serper API
- update search engine with new engine type and Enum
- check for all API keys in searchandsummarize Action before skipping
<img width="1601" alt="Screen Shot 2023-07-16 at 10 58 47 PM" src="https://github.com/geekan/MetaGPT/assets/30305532/306c2d8f-ed1b-4da6-89d1-f376819d5d26">
| https://api.github.com/repos/geekan/MetaGPT/pulls/50 | 2023-07-17T02:58:57Z | 2023-07-17T05:56:53Z | 2023-07-17T05:56:53Z | 2023-07-17T05:56:53Z | 2,900 | geekan/MetaGPT | 16,789 |
Mac Tray: Remove Duplicated Import of "config" | diff --git a/launcher/mac_tray.py b/launcher/mac_tray.py
index ebee10ba84..af8c73db89 100644
--- a/launcher/mac_tray.py
+++ b/launcher/mac_tray.py
@@ -3,7 +3,6 @@
import os
import sys
-import config
current_path = os.path.dirname(os.path.abspath(__file__))
helper_path = os.path.join(current_path, os.pardir, 'data', 'launcher', 'helper')
| https://api.github.com/repos/XX-net/XX-Net/pulls/2826 | 2016-04-10T15:37:01Z | 2016-04-11T02:55:19Z | 2016-04-11T02:55:19Z | 2016-04-11T02:55:19Z | 109 | XX-net/XX-Net | 17,358 | |
test(js): Convert DeprecatedDropdownModal test to RTL | diff --git a/static/app/components/deprecatedDropdownMenu.spec.jsx b/static/app/components/deprecatedDropdownMenu.spec.jsx
deleted file mode 100644
index 93bca7c03d204..0000000000000
--- a/static/app/components/deprecatedDropdownMenu.spec.jsx
+++ /dev/null
@@ -1,243 +0,0 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
-
-import DeprecatedDropdownMenu from 'sentry/components/deprecatedDropdownMenu';
-
-jest.useFakeTimers();
-
-describe('dropdownMenuDeprecated', function () {
- let wrapper;
-
- beforeEach(function () {
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu>
- {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
- <span {...getRootProps({})}>
- <button {...getActorProps({})}>Open Dropdown</button>
- {isOpen && (
- <ul {...getMenuProps({})}>
- <li>Dropdown Menu Item 1</li>
- </ul>
- )}
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
- });
-
- it('renders', function () {
- expect(wrapper).toSnapshot();
- });
-
- it('can toggle dropdown menu with actor', function () {
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(true);
- expect(wrapper.find('ul')).toHaveLength(1);
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(false);
- expect(wrapper.find('ul')).toHaveLength(0);
- });
-
- it('closes dropdown when clicking on anything in menu', function () {
- wrapper.find('button').simulate('click');
- wrapper.find('li').simulate('click');
- expect(wrapper.state('isOpen')).toBe(false);
- expect(wrapper.find('ul')).toHaveLength(0);
- });
-
- it('closes dropdown when clicking outside of menu', async function () {
- wrapper.find('button').simulate('click');
- // Simulate click on document
- const event = document.createEvent('HTMLEvents');
- event.initEvent('click', false, true);
- document.body.dispatchEvent(event);
-
- jest.runAllTimers();
- await Promise.resolve();
- wrapper.update();
-
- expect(wrapper.find('ul')).toHaveLength(0);
- });
-
- it('closes dropdown when pressing escape', function () {
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(true);
- wrapper.simulate('keyDown', {key: 'Escape'});
- wrapper.find('button').simulate('keyDown', {key: 'Escape'});
- expect(wrapper.state('isOpen')).toBe(false);
- expect(wrapper.find('ul')).toHaveLength(0);
- });
-
- it('ignores "Escape" key if `closeOnEscape` is false', function () {
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu closeOnEscape={false}>
- {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
- <span {...getRootProps({})}>
- <button {...getActorProps({})}>Open Dropdown</button>
- {isOpen && (
- <ul {...getMenuProps({})}>
- <li>Dropdown Menu Item 1</li>
- </ul>
- )}
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
-
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(true);
- wrapper.find('button').simulate('keyDown', {key: 'Escape'});
- expect(wrapper.find('ul')).toHaveLength(1);
- expect(wrapper.state('isOpen')).toBe(true);
- });
-
- it('keeps dropdown open when clicking on anything in menu with `keepMenuOpen` prop', function () {
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu keepMenuOpen>
- {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
- <span {...getRootProps({})}>
- <button {...getActorProps({})}>Open Dropdown</button>
- {isOpen && (
- <ul {...getMenuProps({})}>
- <li>Dropdown Menu Item 1</li>
- </ul>
- )}
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
-
- wrapper.find('button').simulate('click');
- wrapper.find('li').simulate('click');
- expect(wrapper.state('isOpen')).toBe(true);
- expect(wrapper.find('ul')).toHaveLength(1);
- });
-
- it('render prop getters all extend props and call original onClick handlers', function () {
- const rootClick = jest.fn();
- const actorClick = jest.fn();
- const menuClick = jest.fn();
- const addSpy = jest.spyOn(document, 'addEventListener');
- const removeSpy = jest.spyOn(document, 'removeEventListener');
-
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu keepMenuOpen>
- {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
- <span
- {...getRootProps({
- className: 'root',
- onClick: rootClick,
- })}
- >
- <button
- {...getActorProps({
- className: 'actor',
- onClick: actorClick,
- })}
- >
- Open Dropdown
- </button>
- {isOpen && (
- <ul
- {...getMenuProps({
- className: 'menu',
- onClick: menuClick,
- })}
- >
- <li>Dropdown Menu Item 1</li>
- </ul>
- )}
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
-
- expect(wrapper.find('ul')).toHaveLength(0);
-
- wrapper.find('span').simulate('click');
- expect(rootClick).toHaveBeenCalled();
- wrapper.find('button').simulate('click');
- expect(actorClick).toHaveBeenCalled();
- wrapper.find('li').simulate('click');
- expect(menuClick).toHaveBeenCalled();
-
- // breaks in jest22
- // expect(wrapper).toSnapshot();
- expect(wrapper.find('ul')).toHaveLength(1);
- expect(document.addEventListener).toHaveBeenCalled();
-
- wrapper.unmount();
- expect(document.removeEventListener).toHaveBeenCalled();
-
- addSpy.mockRestore();
- removeSpy.mockRestore();
- });
-
- it('always rendered menus should attach document event listeners only when opened', function () {
- const addSpy = jest.spyOn(document, 'addEventListener');
- const removeSpy = jest.spyOn(document, 'removeEventListener');
-
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu alwaysRenderMenu>
- {({getRootProps, getActorProps, getMenuProps}) => (
- <span
- {...getRootProps({
- className: 'root',
- })}
- >
- <button
- {...getActorProps({
- className: 'actor',
- })}
- >
- Open Dropdown
- </button>
- <ul
- {...getMenuProps({
- className: 'menu',
- })}
- >
- <li>Dropdown Menu Item 1</li>
- </ul>
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
-
- // Make sure this is only called when menu is open
- expect(document.addEventListener).not.toHaveBeenCalled();
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(true);
- expect(document.addEventListener).toHaveBeenCalled();
-
- expect(document.removeEventListener).not.toHaveBeenCalled();
- wrapper.find('button').simulate('click');
- expect(wrapper.state('isOpen')).toBe(false);
- expect(document.removeEventListener).toHaveBeenCalled();
-
- addSpy.mockRestore();
- removeSpy.mockRestore();
- });
-
- it('does not close nested dropdown on actor clicks', function () {
- wrapper = mountWithTheme(
- <DeprecatedDropdownMenu isNestedDropdown>
- {({getRootProps, getActorProps, getMenuProps}) => (
- <span {...getRootProps({})}>
- <button {...getActorProps({})}>Open Dropdown</button>
- {
- <ul {...getMenuProps({})}>
- <li data-test-id="menu-item">Dropdown Menu Item 1</li>
- </ul>
- }
- </span>
- )}
- </DeprecatedDropdownMenu>
- );
- wrapper.find('button').simulate('mouseEnter');
- expect(wrapper.find('[data-test-id="menu-item"]')).toHaveLength(1);
-
- wrapper.find('button').simulate('click');
- // Should still be visible.
- expect(wrapper.find('[data-test-id="menu-item"]')).toHaveLength(1);
- });
-});
diff --git a/static/app/components/deprecatedDropdownMenu.spec.tsx b/static/app/components/deprecatedDropdownMenu.spec.tsx
new file mode 100644
index 0000000000000..e15da75be06f6
--- /dev/null
+++ b/static/app/components/deprecatedDropdownMenu.spec.tsx
@@ -0,0 +1,181 @@
+import type {ComponentProps} from 'react';
+
+import {
+ render,
+ screen,
+ userEvent,
+ waitForElementToBeRemoved,
+} from 'sentry-test/reactTestingLibrary';
+
+import DeprecatedDropdownMenu from 'sentry/components/deprecatedDropdownMenu';
+
+jest.useFakeTimers();
+
+describe('dropdownMenuDeprecated', function () {
+ const DeprecatedDropdownImplementation = (
+ props: Partial<ComponentProps<typeof DeprecatedDropdownMenu>> = {}
+ ) => {
+ return (
+ <DeprecatedDropdownMenu {...props}>
+ {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
+ <span {...getRootProps({})}>
+ <button {...getActorProps({})}>Open Dropdown</button>
+ {isOpen && (
+ <ul {...getMenuProps({})}>
+ <li>Dropdown Menu Item 1</li>
+ </ul>
+ )}
+ </span>
+ )}
+ </DeprecatedDropdownMenu>
+ );
+ };
+
+ it('renders', function () {
+ const {container} = render(<DeprecatedDropdownImplementation />);
+ expect(container).toSnapshot();
+ });
+
+ it('can toggle dropdown menu with actor', function () {
+ render(<DeprecatedDropdownImplementation />);
+
+ userEvent.click(screen.getByRole('button'));
+ expect(screen.getByRole('listbox')).toBeInTheDocument();
+ userEvent.click(screen.getByRole('button'));
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ });
+
+ it('closes dropdown when clicking on anything in menu', function () {
+ render(<DeprecatedDropdownImplementation />);
+ userEvent.click(screen.getByRole('button'));
+ userEvent.click(screen.getByRole('listitem'));
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ });
+
+ it('closes dropdown when clicking outside of menu', async function () {
+ render(
+ <div data-test-id="outside-element">
+ <DeprecatedDropdownImplementation />
+ </div>
+ );
+ userEvent.click(screen.getByRole('button'));
+ userEvent.click(screen.getByTestId('outside-element'));
+
+ await waitForElementToBeRemoved(() => screen.queryByRole('listbox'));
+ });
+
+ it('closes dropdown when pressing escape', function () {
+ render(<DeprecatedDropdownImplementation />);
+ userEvent.click(screen.getByRole('button'));
+
+ userEvent.keyboard('{Escape}');
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ });
+
+ it('ignores "Escape" key if `closeOnEscape` is false', function () {
+ render(<DeprecatedDropdownImplementation closeOnEscape={false} />);
+ userEvent.click(screen.getByRole('button'));
+
+ userEvent.keyboard('{Escape}');
+ expect(screen.getByRole('listbox')).toBeInTheDocument();
+ });
+
+ it('keeps dropdown open when clicking on anything in menu with `keepMenuOpen` prop', function () {
+ render(<DeprecatedDropdownImplementation keepMenuOpen />);
+ userEvent.click(screen.getByRole('button'));
+ userEvent.click(screen.getByRole('listitem'));
+
+ expect(screen.getByRole('listbox')).toBeInTheDocument();
+ });
+
+ it('render prop getters all extend props and call original onClick handlers', function () {
+ const rootClick = jest.fn();
+ const actorClick = jest.fn();
+ const menuClick = jest.fn();
+
+ render(
+ <DeprecatedDropdownMenu keepMenuOpen>
+ {({getRootProps, getActorProps, getMenuProps, isOpen}) => (
+ <span {...getRootProps({onClick: rootClick})} data-test-id="root">
+ <button {...getActorProps({onClick: actorClick})} data-test-id="actor">
+ Open Dropdown
+ </button>
+ {isOpen && (
+ <ul {...getMenuProps({onClick: menuClick})} data-test-id="menu">
+ <li>Dropdown Menu Item 1</li>
+ </ul>
+ )}
+ </span>
+ )}
+ </DeprecatedDropdownMenu>
+ );
+
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+
+ userEvent.click(screen.getByTestId('root'));
+ expect(rootClick).toHaveBeenCalled();
+
+ userEvent.click(screen.getByTestId('actor'));
+ expect(actorClick).toHaveBeenCalled();
+
+ userEvent.click(screen.getByTestId('menu'));
+ expect(menuClick).toHaveBeenCalled();
+
+ expect(screen.queryByRole('listbox')).toBeInTheDocument();
+ });
+
+ it('always rendered menus should attach document event listeners only when opened', function () {
+ const addSpy = jest.spyOn(document, 'addEventListener');
+ const removeSpy = jest.spyOn(document, 'removeEventListener');
+
+ render(
+ <DeprecatedDropdownMenu alwaysRenderMenu>
+ {({getRootProps, getActorProps, getMenuProps}) => (
+ <span {...getRootProps({className: 'root'})}>
+ <button {...getActorProps({className: 'actor'})}>Open Dropdown</button>
+ <ul {...getMenuProps({className: 'menu'})}>
+ <li>Dropdown Menu Item 1</li>
+ </ul>
+ </span>
+ )}
+ </DeprecatedDropdownMenu>
+ );
+
+ // Make sure this is only called when menu is open
+ expect(addSpy).not.toHaveBeenCalled();
+
+ userEvent.click(screen.getByRole('button'));
+ expect(addSpy).toHaveBeenCalled();
+ expect(removeSpy).not.toHaveBeenCalled();
+
+ userEvent.click(screen.getByRole('button'));
+ expect(removeSpy).toHaveBeenCalled();
+
+ addSpy.mockRestore();
+ removeSpy.mockRestore();
+ });
+
+ it('does not close nested dropdown on actor clicks', function () {
+ render(
+ <DeprecatedDropdownMenu isNestedDropdown>
+ {({getRootProps, getActorProps, getMenuProps}) => (
+ <span {...getRootProps({})}>
+ <button {...getActorProps({})}>Open Dropdown</button>
+ {
+ <ul {...getMenuProps({})}>
+ <li data-test-id="menu-item">Dropdown Menu Item 1</li>
+ </ul>
+ }
+ </span>
+ )}
+ </DeprecatedDropdownMenu>
+ );
+
+ userEvent.hover(screen.getByRole('button'));
+ expect(screen.getByTestId('menu-item')).toBeInTheDocument();
+
+ userEvent.click(screen.getByRole('button'));
+ // Should still be visible.
+ expect(screen.getByTestId('menu-item')).toBeInTheDocument();
+ });
+});
| https://api.github.com/repos/getsentry/sentry/pulls/39865 | 2022-10-10T16:04:05Z | 2022-10-12T17:15:09Z | 2022-10-12T17:15:09Z | 2022-10-28T00:02:38Z | 3,492 | getsentry/sentry | 44,710 | |
fix typo in RandomizedSearchCV docs | diff --git a/sklearn/model_selection/_search.py b/sklearn/model_selection/_search.py
index 0d0c15c54c468..b2345398aa92e 100644
--- a/sklearn/model_selection/_search.py
+++ b/sklearn/model_selection/_search.py
@@ -1075,7 +1075,7 @@ class RandomizedSearchCV(BaseSearchCV):
will be represented by a ``cv_results_`` dict of::
{
- 'param_kernel' : masked_array(data = ['rbf', rbf', 'rbf'],
+ 'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'],
mask = False),
'param_gamma' : masked_array(data = [0.1 0.2 0.3], mask = False),
'split0_test_score' : [0.8, 0.9, 0.7],
| <!--
Thanks for contributing a pull request! Please ensure you have taken a look at
the contribution guidelines: https://github.com/scikit-learn/scikit-learn/blob/master/CONTRIBUTING.md#Contributing-Pull-Requests
-->
#### Reference Issue
none
#### What does this implement/fix? Explain your changes.
Fixes a typo (missing ') in docs
#### Any other comments?
<!--
Please be aware that we are a loose team of volunteers so patience is
necessary; assistance handling other issues is very welcome. We value
all user contributions, no matter how minor they are. If we are slow to
review, either the pull request needs some benchmarking, tinkering,
convincing, etc. or more likely the reviewers are simply busy. In either
case, we ask for your understanding during the review process.
For more information, see our FAQ on this topic:
http://scikit-learn.org/dev/faq.html#why-is-my-pull-request-not-getting-any-attention.
Thanks for contributing!
-->
add missing ' in RandomizedSearchCV docs
| https://api.github.com/repos/scikit-learn/scikit-learn/pulls/7564 | 2016-10-03T17:33:51Z | 2016-10-03T20:18:49Z | 2016-10-03T20:18:49Z | 2016-10-03T20:18:49Z | 208 | scikit-learn/scikit-learn | 46,222 |
add tss2 highlander to tss2 long tune | diff --git a/selfdrive/car/toyota/interface.py b/selfdrive/car/toyota/interface.py
index 59022bf0f38ea9..755ba5248132a3 100755
--- a/selfdrive/car/toyota/interface.py
+++ b/selfdrive/car/toyota/interface.py
@@ -268,7 +268,8 @@ def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # py
if ret.enableGasInterceptor:
set_long_tune(ret.longitudinalTuning, LongTunes.PEDAL)
- elif candidate in [CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.RAV4_TSS2, CAR.RAV4H_TSS2, CAR.LEXUS_NX_TSS2]:
+ elif candidate in [CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.RAV4_TSS2, CAR.RAV4H_TSS2, CAR.LEXUS_NX_TSS2,
+ CAR.HIGHLANDER_TSS2, CAR.HIGHLANDERH_TSS2]:
set_long_tune(ret.longitudinalTuning, LongTunes.TSS2)
ret.stoppingDecelRate = 0.3 # reach stopping target smoothly
ret.startingAccelRate = 6.0 # release brakes fast
| <!-- Please copy and paste the relevant template -->
<!--- ***** Template: Car bug fix *****
**Description** [](A description of the bug and the fix. Also link any relevant issues.)
**Verification** [](Explain how you tested this bug fix.)
**Route**
Route: [a route with the bug fix]
-->
<!--- ***** Template: Bug fix *****
**Description** [](A description of the bug and the fix. Also link any relevant issues.)
**Verification** [](Explain how you tested this bug fix.)
-->
<!--- ***** Template: Car port *****
**Checklist**
- [ ] added to README
- [ ] test route added to [test_routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/test/test_routes.py)
- [ ] route with openpilot:
- [ ] route with stock system:
-->
<!--- ***** Template: Refactor *****
**Description** [](A description of the refactor, including the goals it accomplishes.)
**Verification** [](Explain how you tested the refactor for regressions.)
-->
| https://api.github.com/repos/commaai/openpilot/pulls/23107 | 2021-12-02T21:47:29Z | 2021-12-02T22:01:17Z | 2021-12-02T22:01:17Z | 2021-12-02T22:01:18Z | 304 | commaai/openpilot | 9,383 |
[ie/openrec] add referer for m3u8 (fix #6946) | diff --git a/yt_dlp/extractor/openrec.py b/yt_dlp/extractor/openrec.py
index 86dc9bb898c..82a81c6c261 100644
--- a/yt_dlp/extractor/openrec.py
+++ b/yt_dlp/extractor/openrec.py
@@ -12,6 +12,8 @@
class OpenRecBaseIE(InfoExtractor):
+ _M3U8_HEADERS = {'Referer': 'https://www.openrec.tv/'}
+
def _extract_pagestore(self, webpage, video_id):
return self._parse_json(
self._search_regex(r'(?m)window\.pageStore\s*=\s*(\{.+?\});$', webpage, 'window.pageStore'), video_id)
@@ -21,7 +23,7 @@ def _expand_media(self, video_id, media):
if not m3u8_url:
continue
yield from self._extract_m3u8_formats(
- m3u8_url, video_id, ext='mp4', m3u8_id=name)
+ m3u8_url, video_id, ext='mp4', m3u8_id=name, headers=self._M3U8_HEADERS)
def _extract_movie(self, webpage, video_id, name, is_live):
window_stores = self._extract_pagestore(webpage, video_id)
@@ -60,6 +62,7 @@ def _extract_movie(self, webpage, video_id, name, is_live):
'uploader_id': get_first(movie_stores, ('channel', 'user', 'id')),
'timestamp': int_or_none(get_first(movie_stores, ['publishedAt', 'time']), scale=1000) or unified_timestamp(get_first(movie_stores, 'publishedAt')),
'is_live': is_live,
+ 'http_headers': self._M3U8_HEADERS,
}
@@ -110,7 +113,7 @@ def _real_extract(self, url):
raise ExtractorError('Cannot extract title')
formats = self._extract_m3u8_formats(
- capture_data.get('source'), video_id, ext='mp4')
+ capture_data.get('source'), video_id, ext='mp4', headers=self._M3U8_HEADERS)
return {
'id': video_id,
@@ -121,6 +124,7 @@ def _real_extract(self, url):
'uploader': traverse_obj(movie_store, ('channel', 'name'), expected_type=compat_str),
'uploader_id': traverse_obj(movie_store, ('channel', 'id'), expected_type=compat_str),
'upload_date': unified_strdate(capture_data.get('createdAt')),
+ 'http_headers': self._M3U8_HEADERS,
}
| **IMPORTANT**: PRs without the template will be CLOSED
### Description of your *pull request* and other information
<!--
Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible
-->
Fixes #6946; add missing Referer header for all m3u8 requests since it is requested by the server since last year.
<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/9253 | 2024-02-20T18:01:16Z | 2024-02-21T03:46:55Z | 2024-02-21T03:46:55Z | 2024-02-21T03:46:55Z | 600 | yt-dlp/yt-dlp | 8,231 |
优化部署、安装相关文档 | diff --git a/deploy/cpp_infer/readme.md b/deploy/cpp_infer/readme.md
index 4183691510..6335530821 100644
--- a/deploy/cpp_infer/readme.md
+++ b/deploy/cpp_infer/readme.md
@@ -1,6 +1,8 @@
# 服务器端C++预测
-本教程将介绍在服务器端部署PaddleOCR超轻量中文检测、识别模型的详细步骤。
+本章节介绍PaddleOCR 模型的的C++部署方法,与之对应的python预测部署方式参考[文档](../../doc/doc_ch/inference.md)。
+C++在性能计算上优于python,因此,在大多数CPU、GPU部署场景,多采用C++的部署方式,本节将介绍如何在Linux\Windows (CPU\GPU)环境下配置C++环境并完成
+PaddleOCR模型部署。
## 1. 准备环境
diff --git a/deploy/cpp_infer/readme_en.md b/deploy/cpp_infer/readme_en.md
index 6bc49e9479..cfe18a286f 100644
--- a/deploy/cpp_infer/readme_en.md
+++ b/deploy/cpp_infer/readme_en.md
@@ -1,7 +1,9 @@
# Server-side C++ inference
-
-In this tutorial, we will introduce the detailed steps of deploying PaddleOCR ultra-lightweight Chinese detection and recognition models on the server side.
+This chapter introduces the C++ deployment method of the PaddleOCR model, and the corresponding python predictive deployment method refers to [document](../../doc/doc_ch/inference.md).
+C++ is better than python in terms of performance calculation. Therefore, in most CPU and GPU deployment scenarios, C++ deployment is mostly used.
+This section will introduce how to configure the C++ environment and complete it in the Linux\Windows (CPU\GPU) environment
+PaddleOCR model deployment.
## 1. Prepare the environment
diff --git a/doc/doc_ch/inference.md b/doc/doc_ch/inference.md
index f0a8983c4b..7968b355ea 100755
--- a/doc/doc_ch/inference.md
+++ b/doc/doc_ch/inference.md
@@ -2,10 +2,11 @@
# 基于Python预测引擎推理
inference 模型(`paddle.jit.save`保存的模型)
-一般是模型训练完成后保存的固化模型,多用于预测部署。训练过程中保存的模型是checkpoints模型,保存的是模型的参数,多用于恢复训练等。
-与checkpoints模型相比,inference 模型会额外保存模型的结构信息,在预测部署、加速推理上性能优越,灵活方便,适合与实际系统集成。
+一般是模型训练,把模型结构和模型参数保存在文件中的固化模型,多用于预测部署场景。
+训练过程中保存的模型是checkpoints模型,保存的只有模型的参数,多用于恢复训练等。
+与checkpoints模型相比,inference 模型会额外保存模型的结构信息,在预测部署、加速推理上性能优越,灵活方便,适合于实际系统集成。
-接下来首先介绍如何将训练的模型转换成inference模型,然后将依次介绍文本检测、文本角度分类器、文本识别以及三者串联基于预测引擎推理。
+接下来首先介绍如何将训练的模型转换成inference模型,然后将依次介绍文本检测、文本角度分类器、文本识别以及三者串联在CPU、GPU上的预测方法。
- [一、训练模型转inference模型](#训练模型转inference模型)
diff --git a/doc/doc_ch/installation.md b/doc/doc_ch/installation.md
index fce151eb9f..7e7523b999 100644
--- a/doc/doc_ch/installation.md
+++ b/doc/doc_ch/installation.md
@@ -30,7 +30,7 @@ sudo nvidia-docker run --name ppocr -v $PWD:/paddle --shm-size=64G --network=hos
sudo docker container exec -it ppocr /bin/bash
```
-**2. 安装PaddlePaddle Fluid v2.0**
+**2. 安装PaddlePaddle 2.0**
```
pip3 install --upgrade pip
diff --git a/doc/doc_en/inference_en.md b/doc/doc_en/inference_en.md
index 6b745619c9..aa3e0536cb 100755
--- a/doc/doc_en/inference_en.md
+++ b/doc/doc_en/inference_en.md
@@ -5,7 +5,8 @@ The inference model (the model saved by `paddle.jit.save`) is generally a solidi
The model saved during the training process is the checkpoints model, which saves the parameters of the model and is mostly used to resume training.
-Compared with the checkpoints model, the inference model will additionally save the structural information of the model. It has superior performance in predicting in deployment and accelerating inferencing, is flexible and convenient, and is suitable for integration with actual systems. For more details, please refer to the document [Classification Framework](https://github.com/PaddlePaddle/PaddleClas/blob/master/docs/zh_CN/extension/paddle_inference.md).
+Compared with the checkpoints model, the inference model will additionally save the structural information of the model. Therefore, it is easier to deploy because the model structure and model parameters are already solidified in the inference model file, and is suitable for integration with actual systems.
+For more details, please refer to the document [Classification Framework](https://github.com/PaddlePaddle/PaddleClas/blob/release%2F2.0/docs/zh_CN/extension/paddle_mobile_inference.md).
Next, we first introduce how to convert a trained model into an inference model, and then we will introduce text detection, text recognition, angle class, and the concatenation of them based on inference model.
diff --git a/doc/doc_en/installation_en.md b/doc/doc_en/installation_en.md
index 35c1881d12..dec384b2f2 100644
--- a/doc/doc_en/installation_en.md
+++ b/doc/doc_en/installation_en.md
@@ -33,7 +33,7 @@ You can also visit [DockerHub](https://hub.docker.com/r/paddlepaddle/paddle/tags
sudo docker container exec -it ppocr /bin/bash
```
-**2. Install PaddlePaddle Fluid v2.0**
+**2. Install PaddlePaddle 2.0**
```
pip3 install --upgrade pip
diff --git a/tools/infer/utility.py b/tools/infer/utility.py
index 4171a29bdd..a4a91efdd2 100755
--- a/tools/infer/utility.py
+++ b/tools/infer/utility.py
@@ -47,6 +47,7 @@ def str2bool(v):
parser.add_argument("--det_db_box_thresh", type=float, default=0.5)
parser.add_argument("--det_db_unclip_ratio", type=float, default=1.6)
parser.add_argument("--max_batch_size", type=int, default=10)
+ parser.add_argument("--use_dilation", type=bool, default=False)
# EAST parmas
parser.add_argument("--det_east_score_thresh", type=float, default=0.8)
parser.add_argument("--det_east_cover_thresh", type=float, default=0.1)
@@ -123,6 +124,8 @@ def create_predictor(args, mode, logger):
# cache 10 different shapes for mkldnn to avoid memory leak
config.set_mkldnn_cache_capacity(10)
config.enable_mkldnn()
+ # TODO LDOUBLEV: fix mkldnn bug when bach_size > 1
+ #config.set_mkldnn_op({'conv2d', 'depthwise_conv2d', 'pool2d', 'batch_norm'})
args.rec_batch_num = 1
# config.enable_memory_optim()
diff --git a/tools/program.py b/tools/program.py
index 6277d74758..ae6491768c 100755
--- a/tools/program.py
+++ b/tools/program.py
@@ -394,6 +394,7 @@ def preprocess(is_train=False):
logger = get_logger(name='root', log_file=log_file)
if config['Global']['use_visualdl']:
from visualdl import LogWriter
+ save_model_dir = config['Global']['save_model_dir']
vdl_writer_path = '{}/vdl/'.format(save_model_dir)
os.makedirs(vdl_writer_path, exist_ok=True)
vdl_writer = LogWriter(logdir=vdl_writer_path)
diff --git a/train.sh b/train.sh
index 8fe861a3d7..4225470cb9 100644
--- a/train.sh
+++ b/train.sh
@@ -1,2 +1,2 @@
# recommended paddle.__version__ == 2.0.0
-python3 -m paddle.distributed.launch --gpus '0,1,2,3,4,5,6,7' tools/train.py -c configs/rec/rec_mv3_none_bilstm_ctc.yml
+python3 -m paddle.distributed.launch --log_dir=./debug/ --gpus '0,1,2,3,4,5,6,7' tools/train.py -c configs/rec/rec_mv3_none_bilstm_ctc.yml
| att | https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/1920 | 2021-02-02T13:09:37Z | 2021-02-18T10:58:18Z | 2021-02-18T10:58:18Z | 2021-02-18T10:58:18Z | 2,123 | PaddlePaddle/PaddleOCR | 41,936 |
Added 'pagan' to Imagery | diff --git a/README.md b/README.md
index 76723b5aa..b10012082 100644
--- a/README.md
+++ b/README.md
@@ -320,6 +320,7 @@ Inspired by [awesome-php](https://github.com/ziadoz/awesome-php).
*Libraries for manipulating images.*
+* [pagan](https://github.com/daboth/pagan) - is avatar generator for absolute nerds.
* [pillow](https://github.com/python-pillow/Pillow) - Pillow is the friendly [PIL](http://www.pythonware.com/products/pil/) fork.
* [hmap](https://github.com/rossgoodwin/hmap) - Image histogram remapping.
* [imgSeek](https://sourceforge.net/projects/imgseek/) - A project for searching a collection of images using visual similarity.
| ## What is this Python project?
## What's the difference between this Python project and similar ones?
Remember those good old days when your own imagination was a big part of the computer gaming experience? All the limitations of the hardware forced you to fill the void left by poorly pixelated images by yourself. Well, pagan tries to give back some of those nostalgic feelings by providing identicons in an oldschool look that are inspired from retro roleplaying adventure games.
Each string input will be hashed and generates a unique avatar image. The purpose of pagan is to use it for generating a user image in any web application. It is is meant to replace default user images when creating new accounts or to enhance comment sections, e.g. visualizing the authors ip address or username.



##
Anyone who agrees with this pull request could vote for it by adding a :+1: to it, and usually, the maintainer will merge it when votes reach **20**.
| https://api.github.com/repos/vinta/awesome-python/pulls/733 | 2016-09-29T13:11:04Z | 2016-09-29T14:57:31Z | 2016-09-29T14:57:31Z | 2016-09-29T14:57:31Z | 188 | vinta/awesome-python | 26,900 |
qt cleanup | diff --git a/SConstruct b/SConstruct
index 1b863bebaed13f..b29f50aca8a07d 100644
--- a/SConstruct
+++ b/SConstruct
@@ -186,45 +186,6 @@ env = Environment(
]
)
-qt_env = None
-if arch in ["x86_64", "Darwin", "larch64"]:
- qt_env = env.Clone()
-
- if arch == "Darwin":
- qt_env['QTDIR'] = "/usr/local/opt/qt"
- QT_BASE = "/usr/local/opt/qt/"
- qt_dirs = [
- QT_BASE + "include/",
- QT_BASE + "include/QtWidgets",
- QT_BASE + "include/QtGui",
- QT_BASE + "include/QtCore",
- QT_BASE + "include/QtDBus",
- QT_BASE + "include/QtMultimedia",
- ]
- qt_env["LINKFLAGS"] += ["-F" + QT_BASE + "lib"]
- else:
- qt_env['QTDIR'] = "/usr"
- qt_dirs = [
- f"/usr/include/{real_arch}-linux-gnu/qt5",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtWidgets",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtGui",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtCore",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtDBus",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtMultimedia",
- f"/usr/include/{real_arch}-linux-gnu/qt5/QtGui/5.5.1/QtGui",
- ]
-
- qt_env.Tool('qt')
- qt_env['CPPPATH'] += qt_dirs
- qt_flags = [
- "-D_REENTRANT",
- "-DQT_NO_DEBUG",
- "-DQT_WIDGETS_LIB",
- "-DQT_GUI_LIB",
- "-DQT_CORE_LIB"
- ]
- qt_env['CXXFLAGS'] += qt_flags
-
if os.environ.get('SCONS_CACHE'):
cache_dir = '/tmp/scons_cache'
@@ -263,7 +224,7 @@ def abspath(x):
# still needed for apks
zmq = 'zmq'
-Export('env', 'qt_env', 'arch', 'zmq', 'SHARED', 'USE_WEBCAM', 'QCOM_REPLAY')
+Export('env', 'arch', 'real_arch', 'zmq', 'SHARED', 'USE_WEBCAM', 'QCOM_REPLAY')
# cereal and messaging are shared with the system
SConscript(['cereal/SConscript'])
diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript
index ad7c2d06fcbdf1..3475c4fcbe7a1a 100644
--- a/selfdrive/ui/SConscript
+++ b/selfdrive/ui/SConscript
@@ -1,4 +1,45 @@
-Import('env', 'qt_env', 'arch', 'common', 'messaging', 'gpucommon', 'visionipc', 'cereal')
+Import('env', 'arch', 'real_arch', 'common', 'messaging', 'gpucommon', 'visionipc', 'cereal')
+
+qt_env = None
+if arch in ["x86_64", "Darwin", "larch64"]:
+ qt_env = env.Clone()
+
+ if arch == "Darwin":
+ qt_env['QTDIR'] = "/usr/local/opt/qt"
+ QT_BASE = "/usr/local/opt/qt/"
+ qt_dirs = [
+ QT_BASE + "include/",
+ QT_BASE + "include/QtWidgets",
+ QT_BASE + "include/QtGui",
+ QT_BASE + "include/QtCore",
+ QT_BASE + "include/QtDBus",
+ QT_BASE + "include/QtMultimedia",
+ ]
+ qt_env["LINKFLAGS"] += ["-F" + QT_BASE + "lib"]
+ else:
+ qt_env['QTDIR'] = "/usr"
+ qt_dirs = [
+ f"/usr/include/{real_arch}-linux-gnu/qt5",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtWidgets",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtGui",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtCore",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtDBus",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtMultimedia",
+ f"/usr/include/{real_arch}-linux-gnu/qt5/QtGui/5.5.1/QtGui",
+ ]
+
+ qt_env.Tool('qt')
+ qt_env['CPPPATH'] += qt_dirs
+ qt_flags = [
+ "-D_REENTRANT",
+ "-DQT_NO_DEBUG",
+ "-DQT_WIDGETS_LIB",
+ "-DQT_GUI_LIB",
+ "-DQT_CORE_LIB"
+ ]
+ qt_env['CXXFLAGS'] += qt_flags
+
+
src = ['ui.cc', 'paint.cc', 'sidebar.cc', '#phonelibs/nanovg/nanovg.c']
libs = [common, 'zmq', 'capnp', 'kj', 'm', cereal, messaging, gpucommon, visionipc]
diff --git a/selfdrive/ui/qt/window.hpp b/selfdrive/ui/qt/window.hpp
index 8c82e6023952b8..62049a69fc7772 100644
--- a/selfdrive/ui/qt/window.hpp
+++ b/selfdrive/ui/qt/window.hpp
@@ -2,8 +2,6 @@
#include <QWidget>
#include <QTimer>
-#include <QLabel>
-#include <QGuiApplication>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QStackedLayout>
@@ -11,8 +9,7 @@
#include "qt/qt_sound.hpp"
#include "ui/ui.hpp"
-class MainWindow : public QWidget
-{
+class MainWindow : public QWidget {
Q_OBJECT
public:
@@ -33,8 +30,8 @@ const int vwp_w = 2160;
const int vwp_w = 1920;
#endif
const int vwp_h = 1080;
-class GLWindow : public QOpenGLWidget, protected QOpenGLFunctions
-{
+
+class GLWindow : public QOpenGLWidget, protected QOpenGLFunctions {
Q_OBJECT
public:
@@ -48,7 +45,6 @@ class GLWindow : public QOpenGLWidget, protected QOpenGLFunctions
void resizeGL(int w, int h) override;
void paintGL() override;
-
private:
QTimer * timer;
QTimer * backlight_timer;
@@ -57,7 +53,8 @@ class GLWindow : public QOpenGLWidget, protected QOpenGLFunctions
QtSound sound;
bool onroad = true;
- QLabel * label = NULL;
+
+ // TODO: this shouldn't be here
float brightness_b = 0;
float brightness_m = 0;
float smooth_brightness = 0;
| https://api.github.com/repos/commaai/openpilot/pulls/2476 | 2020-11-03T03:46:41Z | 2020-11-04T19:16:35Z | 2020-11-04T19:16:35Z | 2020-11-04T19:16:36Z | 1,583 | commaai/openpilot | 8,972 | |
pivoting: add english version of the article | diff --git a/Methodology and Resources/Network Pivoting Techniques.md b/Methodology and Resources/Network Pivoting Techniques.md
index e65d3a21e5..35db81816f 100644
--- a/Methodology and Resources/Network Pivoting Techniques.md
+++ b/Methodology and Resources/Network Pivoting Techniques.md
@@ -453,6 +453,6 @@ tar xvzf cloudflared-stable-linux-amd64.tgz
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
-* [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre Zanni](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/)
+* 🇫🇷 [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/)
* [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49)
-* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)
\ No newline at end of file
+* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)
| https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/507 | 2022-06-20T18:31:19Z | 2022-06-20T20:35:08Z | 2022-06-20T20:35:08Z | 2022-06-20T22:23:52Z | 510 | swisskyrepo/PayloadsAllTheThings | 8,581 | |
add unique_id to nodes hidden inputs | diff --git a/execution.py b/execution.py
index 3ca551db67..2b26a0f78c 100644
--- a/execution.py
+++ b/execution.py
@@ -10,7 +10,7 @@
import torch
import nodes
-def get_input_data(inputs, class_def, outputs={}, prompt={}, extra_data={}):
+def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
valid_inputs = class_def.INPUT_TYPES()
input_data_all = {}
for x in inputs:
@@ -34,6 +34,8 @@ def get_input_data(inputs, class_def, outputs={}, prompt={}, extra_data={}):
if h[x] == "EXTRA_PNGINFO":
if "extra_pnginfo" in extra_data:
input_data_all[x] = extra_data['extra_pnginfo']
+ if h[x] == "UNIQUE_ID":
+ input_data_all[x] = unique_id
return input_data_all
def recursive_execute(server, prompt, outputs, current_item, extra_data={}):
@@ -55,7 +57,7 @@ def recursive_execute(server, prompt, outputs, current_item, extra_data={}):
if input_unique_id not in outputs:
executed += recursive_execute(server, prompt, outputs, input_unique_id, extra_data)
- input_data_all = get_input_data(inputs, class_def, outputs, prompt, extra_data)
+ input_data_all = get_input_data(inputs, class_def, unique_id, outputs, prompt, extra_data)
if server.client_id is not None:
server.last_node_id = unique_id
server.send_sync("executing", { "node": unique_id }, server.client_id)
@@ -96,7 +98,7 @@ def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item
if unique_id in old_prompt and 'is_changed' in old_prompt[unique_id]:
is_changed_old = old_prompt[unique_id]['is_changed']
if 'is_changed' not in prompt[unique_id]:
- input_data_all = get_input_data(inputs, class_def, outputs)
+ input_data_all = get_input_data(inputs, class_def, unique_id, outputs)
if input_data_all is not None:
is_changed = class_def.IS_CHANGED(**input_data_all)
prompt[unique_id]['is_changed'] = is_changed
| https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/299 | 2023-03-28T06:57:32Z | 2023-03-28T20:51:51Z | 2023-03-28T20:51:51Z | 2023-03-28T20:51:51Z | 508 | comfyanonymous/ComfyUI | 17,987 | |
Add option `--skip-init` to db reset command | diff --git a/airflow/cli/cli_parser.py b/airflow/cli/cli_parser.py
index 8aeb759e8152a..0789b4ee88d82 100644
--- a/airflow/cli/cli_parser.py
+++ b/airflow/cli/cli_parser.py
@@ -559,6 +559,12 @@ def string_lower_type(val):
action="store_true",
default=False,
)
+ARG_DB_SKIP_INIT = Arg(
+ ("-s", "--skip-init"),
+ help="Only remove tables; do not perform db init.",
+ action="store_true",
+ default=False,
+)
# webserver
ARG_PORT = Arg(
@@ -1384,7 +1390,7 @@ class GroupCommand(NamedTuple):
name='reset',
help="Burn down and rebuild the metadata database",
func=lazy_load_command('airflow.cli.commands.db_command.resetdb'),
- args=(ARG_YES,),
+ args=(ARG_YES, ARG_DB_SKIP_INIT),
),
ActionCommand(
name='upgrade',
diff --git a/airflow/cli/commands/db_command.py b/airflow/cli/commands/db_command.py
index 4d96d2a7d3f96..c9201ad59ba80 100644
--- a/airflow/cli/commands/db_command.py
+++ b/airflow/cli/commands/db_command.py
@@ -39,10 +39,9 @@ def initdb(args):
def resetdb(args):
"""Resets the metadata database"""
print("DB: " + repr(settings.engine.url))
- if args.yes or input("This will drop existing tables if they exist. Proceed? (y/n)").upper() == "Y":
- db.resetdb()
- else:
- print("Cancelled")
+ if not (args.yes or input("This will drop existing tables if they exist. Proceed? (y/n)").upper() == "Y"):
+ raise SystemExit("Cancelled")
+ db.resetdb(skip_init=args.skip_init)
@cli_utils.action_cli(check_db=False)
diff --git a/airflow/utils/db.py b/airflow/utils/db.py
index f898cfefc74a6..c9b7ad09e579c 100644
--- a/airflow/utils/db.py
+++ b/airflow/utils/db.py
@@ -1265,7 +1265,7 @@ def upgradedb(
@provide_session
-def resetdb(session: Session = NEW_SESSION):
+def resetdb(session: Session = NEW_SESSION, skip_init: bool = False):
"""Clear out the database"""
if not settings.engine:
raise RuntimeError("The settings.engine must be set. This is a critical assertion")
@@ -1278,7 +1278,8 @@ def resetdb(session: Session = NEW_SESSION):
drop_flask_models(connection)
drop_airflow_moved_tables(session)
- initdb(session=session)
+ if not skip_init:
+ initdb(session=session)
@provide_session
diff --git a/tests/cli/commands/test_db_command.py b/tests/cli/commands/test_db_command.py
index 62b9079051426..125e5d7c3e28d 100644
--- a/tests/cli/commands/test_db_command.py
+++ b/tests/cli/commands/test_db_command.py
@@ -43,7 +43,12 @@ def test_cli_initdb(self, mock_initdb):
def test_cli_resetdb(self, mock_resetdb):
db_command.resetdb(self.parser.parse_args(['db', 'reset', '--yes']))
- mock_resetdb.assert_called_once_with()
+ mock_resetdb.assert_called_once_with(skip_init=False)
+
+ @mock.patch("airflow.cli.commands.db_command.db.resetdb")
+ def test_cli_resetdb_skip_init(self, mock_resetdb):
+ db_command.resetdb(self.parser.parse_args(['db', 'reset', '--yes', '--skip-init']))
+ mock_resetdb.assert_called_once_with(skip_init=True)
@mock.patch("airflow.cli.commands.db_command.db.check_migrations")
def test_cli_check_migrations(self, mock_wait_for_migrations):
diff --git a/tests/utils/test_db.py b/tests/utils/test_db.py
index 680955d8a5c33..187253cc76fd6 100644
--- a/tests/utils/test_db.py
+++ b/tests/utils/test_db.py
@@ -178,20 +178,28 @@ def test_downgrade_with_from(self, mock_om):
actual = mock_om.call_args[1]['revision']
assert actual == 'abc'
+ @pytest.mark.parametrize('skip_init', [False, True])
@mock.patch('airflow.utils.db.create_global_lock', new=MagicMock)
@mock.patch('airflow.utils.db.drop_airflow_models')
@mock.patch('airflow.utils.db.drop_flask_models')
+ @mock.patch('airflow.utils.db.drop_airflow_moved_tables')
@mock.patch('airflow.utils.db.initdb')
@mock.patch('airflow.settings.engine.connect')
def test_resetdb(
self,
mock_connect,
mock_init,
+ mock_drop_moved,
mock_drop_flask,
mock_drop_airflow,
+ skip_init,
):
session_mock = MagicMock()
- resetdb(session_mock)
+ resetdb(session_mock, skip_init=skip_init)
mock_drop_airflow.assert_called_once_with(mock_connect.return_value)
mock_drop_flask.assert_called_once_with(mock_connect.return_value)
- mock_init.assert_called_once_with(session=session_mock)
+ mock_drop_moved.assert_called_once_with(session_mock)
+ if skip_init:
+ mock_init.assert_not_called()
+ else:
+ mock_init.assert_called_once_with(session=session_mock)
| This is useful when doing testing, if we want to clear out the tables but no re-initialize the database, e.g. because we plan to only initialize it to a certain revision with `db upgrade --to-version`.
cc @blag | https://api.github.com/repos/apache/airflow/pulls/22989 | 2022-04-13T16:01:33Z | 2022-04-13T20:50:02Z | 2022-04-13T20:50:02Z | 2022-04-14T00:15:06Z | 1,241 | apache/airflow | 14,689 |
fixed import of werkzeug secure_filename | diff --git a/docs/quickstart.rst b/docs/quickstart.rst
index b28c10d67c..5ed7460f40 100644
--- a/docs/quickstart.rst
+++ b/docs/quickstart.rst
@@ -612,7 +612,7 @@ pass it through the :func:`~werkzeug.utils.secure_filename` function that
Werkzeug provides for you::
from flask import request
- from werkzeug import secure_filename
+ from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
| minor inconsistency in docs
| https://api.github.com/repos/pallets/flask/pulls/1461 | 2015-05-15T06:45:15Z | 2015-05-15T08:24:24Z | 2015-05-15T08:24:24Z | 2020-11-14T05:17:37Z | 134 | pallets/flask | 20,675 |
Update check_requirements() | diff --git a/utils/general.py b/utils/general.py
index 22119100575..3d7fd20c48d 100644
--- a/utils/general.py
+++ b/utils/general.py
@@ -427,7 +427,7 @@ def check_requirements(requirements=ROOT.parent / 'requirements.txt', exclude=()
n += 1
if s and install and AUTOINSTALL: # check environment variable
- LOGGER.info(f"{prefix} YOLOv8 requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...")
+ LOGGER.info(f"{prefix} YOLOv5 requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...")
try:
assert check_online(), 'AutoUpdate skipped (offline)'
LOGGER.info(subprocess.check_output(f'pip install {s} {cmds}', shell=True).decode())
| <!--
Thank you for submitting a YOLOv5 🚀 Pull Request! We want to make contributing to YOLOv5 as easy and transparent as possible. A few tips to get you started:
- Search existing YOLOv5 [PRs](https://github.com/ultralytics/yolov5/pull) to see if a similar PR already exists.
- Link this PR to a YOLOv5 [issue](https://github.com/ultralytics/yolov5/issues) to help us understand what bug fix or feature is being implemented.
- Provide before and after profiling/inference/training results to help us quantify the improvement your PR provides (if applicable).
Please see our ✅ [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) for more details.
Note that Copilot will summarize this PR below, do not modify the 'copilot:all' line.
-->
<!--
copilot:all
-->
### <samp>🤖 Generated by Copilot at d66d89d</samp>
### Summary
:pencil2::memo::bug:
<!--
1. :pencil2: - This emoji is often used to indicate a minor fix or improvement of text, such as typos, grammar, or formatting. In this case, the change corrected the name of the project in the log message, which is a textual fix.
2. :memo: - This emoji is often used to indicate a change or update to documentation, such as README files, comments, or docstrings. In this case, the change was part of a pull request that also improved the documentation of the project, so it could be seen as a documentation-related change.
3. :bug: - This emoji is often used to indicate a bug fix or a resolution of an issue. In this case, the change fixed an inconsistency between the name of the project and the name used in the log message, which could be considered a bug or an error.
-->
Fixed typos and inconsistencies in code and documentation. Updated `check_requirements` function in `utils/general.py` to use correct project name.
> _`check_requirements`_
> _Fixing typos everywhere_
> _Winter of cleanup_
### Walkthrough
* Fix typos and inconsistencies in project name, log messages, and comments ([link](https://github.com/ultralytics/yolov5/pull/11360/files?diff=unified&w=0#diff-dd425673dc44b64697acc887bb7abefec7ca7d92cf434d7ac9a6d69a8268f47aL430-R430), F0
## 🛠️ PR Summary
<sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub>
### 🌟 Summary
Updating logging information for auto-installing YOLOv5 requirements.
### 📊 Key Changes
- Corrected a log message that incorrectly referenced "YOLOv8" instead of "YOLOv5".
### 🎯 Purpose & Impact
- 🛠️ Enhances clarity in log outputs, ensuring that users are correctly informed about actions relating to YOLOv5.
- 💡 Prevents potential confusion about which version of the software the message pertains to, maintaining accuracy for users during auto-installation of requirements.
- 👥 Affects users installing YOLOv5 with missing dependencies, as they'll now receive the correct software version name in notifications. | https://api.github.com/repos/ultralytics/yolov5/pulls/11360 | 2023-04-14T12:46:58Z | 2023-04-14T12:47:08Z | 2023-04-14T12:47:08Z | 2024-01-19T02:13:25Z | 196 | ultralytics/yolov5 | 25,712 |
Remove duplicate normalize_data_format | diff --git a/keras/layers/pooling.py b/keras/layers/pooling.py
index 6346b75489e..6e569033e3e 100644
--- a/keras/layers/pooling.py
+++ b/keras/layers/pooling.py
@@ -121,7 +121,6 @@ class _Pooling2D(Layer):
def __init__(self, pool_size=(2, 2), strides=None, padding='valid',
data_format=None, **kwargs):
super(_Pooling2D, self).__init__(**kwargs)
- data_format = conv_utils.normalize_data_format(data_format)
if strides is None:
strides = pool_size
self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size')
| ### Summary
`normalize_data_format` was being called twice in `_Pooling2D`
### Related Issues
### 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)
- [y] 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/10645 | 2018-07-11T09:39:59Z | 2018-07-11T13:23:18Z | 2018-07-11T13:23:18Z | 2018-07-12T04:53:30Z | 175 | keras-team/keras | 47,233 |
ROADMAP.md | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index adc6e374b..290c2021c 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2,11 +2,9 @@
## Documentation
-- [x] Require documentation for PRs
+
- [ ] Work with Mintlify to translate docs. How does Mintlify let us translate our documentation automatically? I know there's a way.
- [ ] Better comments throughout the package (they're like docs for contributors)
-- [ ] Document the New Computer Update
-- [x] Make a migration guide for the New Computer Update (whats different in our new streaming structure (below) vs. [our old streaming structure](https://docs.openinterpreter.com/usage/python/streaming-response)) thanks ty!
- [ ] Show how to replace interpreter.llm so you can use a custom llm
- [ ] Show how to replace interpreter.computer or add to interpreter.computer.languages for like, e2b execution, remote execution, new programming languages, etc.
@@ -35,8 +33,6 @@
- [x] Has attributes `.supports_functions`, `.supports_vision`, and `.context_window`
- [ ] (Maybe) Allow for a custom embedding function (`interpreter.embed` or `computer.ai.embed`) which will let us do semantic search
- [ ] (Maybe) if a git is detected, switch to a mode that's good for developers, like showing nested file structure in dynamic system message, searching for relevant functions (use computer.files.search)
-- [x] Allow for custom languages (`interpreter.computer.languages.append(class_that_conforms_to_base_language)`)
- - [x] Make it so function calling dynamically uses the languages in interpreter.computer.languages
- [ ] Add a skill library, or maybe expose post processing on code, so we can save functions for later & semantically search docstrings. Keep this minimal!
- [ ] If `interpreter.skill_library == True`, we should add a decorator above all functions, then show OI how to search its skill library
- [ ] Use computer.files.search over a folder that decorator saves functions (and import statements to)
@@ -88,6 +84,11 @@
- [x] Duplicate [one of our hosted model's `.mdx` file](https://github.com/KillianLucas/open-interpreter/tree/main/docs/language-model-setup/hosted-models)
- [x] Swap out the information with information from LiteLLM
- [x] Repeat with other models
+ - [x] Allow for custom languages (`interpreter.computer.languages.append(class_that_conforms_to_base_language)`)
+ - [x] Make it so function calling dynamically uses the languages in interpreter.computer.languages
+ - [x] Make a migration guide for the New Computer Update (whats different in our new streaming structure (below) vs. [our old streaming structure](https://docs.openinterpreter.com/usage/python/streaming-response)) thanks ty!
+ - [x] Require documentation for PRs
+ - [x] Document the New Computer Update
# What's in our scope?
| ### Describe the changes you have made:
### Reference any relevant issues (e.g. "Fixes #000"):
### Pre-Submission Checklist (optional but appreciated):
- [ ] I have included relevant documentation updates (stored in /docs)
- [ ] I have read `docs/CONTRIBUTING.md`
- [ ] I have read `docs/ROADMAP.md`
### OS Tests (optional but appreciated):
- [ ] Tested on Windows
- [ ] Tested on MacOS
- [ ] Tested on Linux
| https://api.github.com/repos/OpenInterpreter/open-interpreter/pulls/1029 | 2024-02-21T22:02:15Z | 2024-02-25T17:21:55Z | 2024-02-25T17:21:55Z | 2024-02-25T17:21:55Z | 671 | OpenInterpreter/open-interpreter | 40,782 |
Fix pipeline logger.warning_once bug | diff --git a/src/transformers/pipelines/base.py b/src/transformers/pipelines/base.py
index 7225a6136e48a..35ee02cab7ba6 100644
--- a/src/transformers/pipelines/base.py
+++ b/src/transformers/pipelines/base.py
@@ -1181,7 +1181,6 @@ def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs):
logger.warning_once(
"You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a"
" dataset",
- UserWarning,
)
is_dataset = Dataset is not None and isinstance(inputs, Dataset)
| Fixes #30076 | https://api.github.com/repos/huggingface/transformers/pulls/30195 | 2024-04-11T17:20:48Z | 2024-04-12T08:34:45Z | 2024-04-12T08:34:45Z | 2024-04-12T08:34:49Z | 154 | huggingface/transformers | 12,090 |
10.15.0 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1183857f..8c9ecf60a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [10.15.0] - Unreleased
+## [10.15.0] - 2021-11-28
### Added
- Added dynamic_progress.py to examples
- Added ConsoleOptions.update_height
+- Fixed Padding not respecting height
### Changed
diff --git a/pyproject.toml b/pyproject.toml
index c3ed18ed8..4300beae9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,7 +2,7 @@
name = "rich"
homepage = "https://github.com/willmcgugan/rich"
documentation = "https://rich.readthedocs.io/en/latest/"
-version = "10.15.0-alpha3"
+version = "10.15.0"
description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
authors = ["Will McGugan <willmcgugan@gmail.com>"]
license = "MIT"
diff --git a/rich/text.py b/rich/text.py
index c49e152b6..288cb6d11 100644
--- a/rich/text.py
+++ b/rich/text.py
@@ -254,10 +254,10 @@ def from_ansi(
end: str = "\n",
tab_size: Optional[int] = 8,
) -> "Text":
- """Create a Text object from pre-formatted ANSI.
+ """Create a Text object from a string containing ANSI escape codes.
Args:
- text (str): A string containing ANSI color codes.
+ text (str): A string containing escape codes.
style (Union[str, Style], optional): Base style for text. Defaults to "".
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
@@ -267,14 +267,18 @@ def from_ansi(
"""
from .ansi import AnsiDecoder
- decoded_text = AnsiDecoder().decode_line(text)
- decoded_text.justify = justify
- decoded_text.overflow = overflow
- decoded_text.no_wrap = no_wrap
- decoded_text.end = end
- decoded_text.tab_size = tab_size
- decoded_text.stylize(style)
- return decoded_text
+ joiner = Text(
+ "\n",
+ justify=justify,
+ overflow=overflow,
+ no_wrap=no_wrap,
+ end=end,
+ tab_size=tab_size,
+ style=style,
+ )
+ decoder = AnsiDecoder()
+ result = joiner.join(line for line in decoder.decode(text))
+ return result
@classmethod
def styled(
diff --git a/tests/test_pretty.py b/tests/test_pretty.py
index d2e829963..ab83d930d 100644
--- a/tests/test_pretty.py
+++ b/tests/test_pretty.py
@@ -97,6 +97,7 @@ def test_small_width():
assert result == expected
+@skip_py36
def test_broken_repr():
class BrokenRepr:
def __repr__(self):
@@ -108,6 +109,7 @@ def __repr__(self):
assert result == expected
+@skip_py36
def test_broken_getattr():
class BrokenAttr:
def __getattr__(self, name):
diff --git a/tests/test_repr.py b/tests/test_repr.py
index c47b76b12..3c2f48a46 100644
--- a/tests/test_repr.py
+++ b/tests/test_repr.py
@@ -1,10 +1,22 @@
import pytest
+import sys
from typing import Optional
from rich.console import Console
import rich.repr
+skip_py36 = pytest.mark.skipif(
+ sys.version_info.minor == 6 and sys.version_info.major == 3,
+ reason="rendered differently on py3.6",
+)
+
+skip_py37 = pytest.mark.skipif(
+ sys.version_info.minor == 7 and sys.version_info.major == 3,
+ reason="rendered differently on py3.7",
+)
+
+
@rich.repr.auto
class Foo:
def __init__(self, foo: str, bar: Optional[int] = None, egg: int = 1):
@@ -59,13 +71,21 @@ def test_rich_repr() -> None:
assert (repr(Foo("hello", bar=3))) == "Foo('hello', 'hello', bar=3, egg=1)"
+@skip_py36
+@skip_py37
def test_rich_repr_positional_only() -> None:
- @rich.repr.auto
- class PosOnly:
- def __init__(self, foo, /):
- self.foo = 1
-
- p = PosOnly(1)
+ _locals = locals().copy()
+ exec(
+ """\
+@rich.repr.auto
+class PosOnly:
+ def __init__(self, foo, /):
+ self.foo = 1
+ """,
+ globals(),
+ _locals,
+ )
+ p = _locals["PosOnly"](1)
assert repr(p) == "PosOnly(1)"
diff --git a/tests/test_text.py b/tests/test_text.py
index 6eecb9ee7..63f128e52 100644
--- a/tests/test_text.py
+++ b/tests/test_text.py
@@ -97,11 +97,12 @@ def test_from_markup():
def test_from_ansi():
text = Text.from_ansi("Hello, \033[1mWorld!\033[0m")
- text2 = Text.from_ansi("Hello, \033[1mWorld!\033[0m", style="red")
assert str(text) == "Hello, World!"
assert text._spans == [Span(7, 13, Style(bold=True))]
- assert str(text2) == "Hello, World!"
- assert text2._spans == [Span(7, 13, Style(bold=True)), Span(0, 13, "red")]
+
+ text = Text.from_ansi("Hello, \033[1m\nWorld!\033[0m")
+ assert str(text) == "Hello, \nWorld!"
+ assert text._spans == [Span(8, 14, Style(bold=True))]
def test_copy():
| Fixes https://github.com/willmcgugan/rich/issues/1721
Fixes https://github.com/willmcgugan/rich/issues/1530 | https://api.github.com/repos/Textualize/rich/pulls/1723 | 2021-11-27T19:53:07Z | 2021-11-28T16:35:33Z | 2021-11-28T16:35:33Z | 2021-11-28T16:35:37Z | 1,550 | Textualize/rich | 48,332 |
Fix for `py_dataset_adapter_test` on GPU. | diff --git a/keras/trainers/data_adapters/py_dataset_adapter_test.py b/keras/trainers/data_adapters/py_dataset_adapter_test.py
index f9ff419ecf1..df2ede7e979 100644
--- a/keras/trainers/data_adapters/py_dataset_adapter_test.py
+++ b/keras/trainers/data_adapters/py_dataset_adapter_test.py
@@ -68,37 +68,48 @@ class PyDatasetAdapterTest(testing.TestCase, parameterized.TestCase):
named_product(
[
{
- "testcase_name": "multi_on",
+ "testcase_name": "multiprocessing",
"workers": 2,
"use_multiprocessing": True,
"max_queue_size": 10,
+ "dataset_type": "np",
},
{
- "testcase_name": "multi_off",
+ "testcase_name": "multithreading",
"workers": 2,
"use_multiprocessing": False,
"max_queue_size": 10,
+ "dataset_type": "np",
},
{
- "testcase_name": "multi_off_zero",
- "workers": 0,
- "use_multiprocessing": False,
- "max_queue_size": 0,
+ "testcase_name": "single_np",
+ "dataset_type": "np",
+ },
+ {
+ "testcase_name": "single_tf",
+ "dataset_type": "tf",
+ },
+ {
+ "testcase_name": "single_jax",
+ "dataset_type": "jax",
+ },
+ {
+ "testcase_name": "single_torch",
+ "dataset_type": "torch",
},
],
- shuffle=[True, False],
- dataset_type=["np", "tf", "jax", "torch"],
iterator_type=["np", "tf", "jax", "torch"],
+ shuffle=[True, False],
)
)
def test_basic_flow(
self,
shuffle,
- workers,
- use_multiprocessing,
- max_queue_size,
dataset_type,
iterator_type,
+ workers=0,
+ use_multiprocessing=False,
+ max_queue_size=0,
):
set_random_seed(1337)
x = np.random.random((64, 4)).astype("float32")
| Removed the parts of the test that were invalid. We were using libraries (TensorFlow, JAX, Torch) in multiple threads or multiple processes in a way that is not supported. This was causing issues with CUDA. | https://api.github.com/repos/keras-team/keras/pulls/19095 | 2024-01-24T18:05:12Z | 2024-01-24T20:45:58Z | 2024-01-24T20:45:58Z | 2024-01-24T21:08:03Z | 512 | keras-team/keras | 47,417 |
Additional responses can be status groups or "default" | diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index 9c043103dc0b7..96be89d937fe0 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -43,6 +43,15 @@
},
}
+status_code_ranges: Dict[str, str] = {
+ "1XX": "Information",
+ "2XX": "Success",
+ "3XX": "Redirection",
+ "4XX": "Client Error",
+ "5XX": "Server Error",
+ "default": "Default Response",
+}
+
def get_openapi_params(dependant: Dependant) -> List[Field]:
flat_dependant = get_flat_dependant(dependant)
@@ -190,12 +199,14 @@ def get_openapi_path(
response.setdefault("content", {}).setdefault(
"application/json", {}
)["schema"] = response_schema
- status_text = http.client.responses.get(int(additional_status_code))
+ status_text: Optional[str] = status_code_ranges.get(
+ str(additional_status_code).upper()
+ ) or http.client.responses.get(int(additional_status_code))
response.setdefault(
"description", status_text or "Additional Response"
)
operation.setdefault("responses", {})[
- str(additional_status_code)
+ str(additional_status_code).upper()
] = response
status_code = str(route.status_code)
response_schema = {"type": "string"}
diff --git a/tests/test_additional_responses_bad.py b/tests/test_additional_responses_bad.py
new file mode 100644
index 0000000000000..fda4755763b3e
--- /dev/null
+++ b/tests/test_additional_responses_bad.py
@@ -0,0 +1,40 @@
+import pytest
+from fastapi import FastAPI
+from starlette.testclient import TestClient
+
+app = FastAPI()
+
+
+@app.get("/a", responses={"hello": {"description": "Not a valid additional response"}})
+async def a():
+ pass # pragma: no cover
+
+
+openapi_schema = {
+ "openapi": "3.0.2",
+ "info": {"title": "Fast API", "version": "0.1.0"},
+ "paths": {
+ "/a": {
+ "get": {
+ "responses": {
+ # this is how one would imagine the openapi schema to be
+ # but since the key is not valid, openapi.utils.get_openapi will raise ValueError
+ "hello": {"description": "Not a valid additional response"},
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ },
+ "summary": "A",
+ "operationId": "a_a_get",
+ }
+ }
+ },
+}
+
+client = TestClient(app)
+
+
+def test_openapi_schema():
+ with pytest.raises(ValueError):
+ client.get("/openapi.json")
diff --git a/tests/test_additional_responses_router.py b/tests/test_additional_responses_router.py
index 49ef5f04992f4..ce66ead7e0c71 100644
--- a/tests/test_additional_responses_router.py
+++ b/tests/test_additional_responses_router.py
@@ -10,12 +10,24 @@ async def a():
return "a"
-@router.get("/b", responses={502: {"description": "Error 2"}})
+@router.get(
+ "/b",
+ responses={
+ 502: {"description": "Error 2"},
+ "4XX": {"description": "Error with range, upper"},
+ },
+)
async def b():
return "b"
-@router.get("/c", responses={501: {"description": "Error 3"}})
+@router.get(
+ "/c",
+ responses={
+ "400": {"description": "Error with str"},
+ "5xx": {"description": "Error with range, lower"},
+ },
+)
async def c():
return "c"
@@ -43,6 +55,7 @@ async def c():
"get": {
"responses": {
"502": {"description": "Error 2"},
+ "4XX": {"description": "Error with range, upper"},
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
@@ -55,7 +68,8 @@ async def c():
"/c": {
"get": {
"responses": {
- "501": {"description": "Error 3"},
+ "400": {"description": "Error with str"},
+ "5XX": {"description": "Error with range, lower"},
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
| Catching exception when generating OpenAPI specification. Added status groups and "default" as possible key for the additional responses.
If merged, this issue fixes #428 | https://api.github.com/repos/tiangolo/fastapi/pulls/435 | 2019-08-13T07:07:42Z | 2019-08-30T16:17:43Z | 2019-08-30T16:17:43Z | 2019-08-30T21:44:11Z | 1,097 | tiangolo/fastapi | 22,991 |
Lookup plugin for the OpenShift Container Platform | diff --git a/lib/ansible/plugins/lookup/openshift.py b/lib/ansible/plugins/lookup/openshift.py
new file mode 100644
index 00000000000000..6753141971bef0
--- /dev/null
+++ b/lib/ansible/plugins/lookup/openshift.py
@@ -0,0 +1,248 @@
+# -*- coding: utf-8 -*-
+# (c) 2017, Kenneth D. Evensen <kevensen@redhat.com>
+
+# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+DOCUMENTATION = """
+ lookup: openshift
+ version_added: "2.5"
+ short_description: Returns the JSON definition of an object in OpenShift
+ description:
+ - This lookup plugin provides the ability to query an OpenShift Container
+ - platform cluster for information about objects. This plugin requires
+ - a valid user or service account token.
+ options:
+ kind:
+ description:
+ - The kind of OpenShift resource to read (e.g. Project, Service, Pod)
+ required: True
+ host:
+ description:
+ - The IP address of the host serving the OpenShift API
+ required: False
+ default: 127.0.0.1
+ port:
+ description:
+ - The port on which to access the OpenShift API
+ required: False
+ default: 8443
+ token:
+ description:
+ - The token to use for authentication against the OpenShift API.
+ - This can be a user or ServiceAccount token.
+ required: True
+ validate_certs:
+ description:
+ - Whether or not to validate the TLS certificate of the API.
+ required: False
+ default: True
+ namespace:
+ description:
+ - The namespace/project where the object resides.
+ required: False
+ resource_name:
+ description:
+ - The name of the object to query.
+ required: False
+ pretty:
+ description:
+ - Whether or not to prettify the output. This is useful for debugging.
+ required: False
+ default: False
+ labelSelector:
+ description:
+ - Additional labels to include in the query.
+ required: False
+ fieldSelector:
+ description:
+ - Specific fields on which to query.
+ required: False
+ resourceVersion:
+ description:
+ - Query for a specific resource version.
+ required: False
+"""
+
+EXAMPLES = """
+- name: Get Project {{ project_name }}
+ set_fact:
+ project_fact: "{{ lookup('openshift',
+ kind='Project',
+ host=inventory_host,
+ token=hostvars[inventory_host]['ansible_sa_token'],
+ resource_name=project_name,
+ validate_certs=validate_certs) }}"
+- name: Get All Service Accounts in a Project
+ set_fact:
+ service_fact: "{{ lookup('openshift',
+ kind='ServiceAccount',
+ host=inventory_host,
+ token=hostvars[inventory_host]['ansible_sa_token'],
+ namespace=project_name,
+ validate_certs=validate_certs) }}"
+"""
+
+RETURN = """
+ _list:
+ description:
+ - An object definition or list of objects definitions returned from OpenShift.
+ type: dict
+"""
+
+import json
+from ansible.errors import AnsibleError
+from ansible.plugins.lookup import LookupBase
+from ansible.module_utils import urls
+from ansible.module_utils.six.moves import urllib
+from ansible.module_utils.six.moves import urllib_error
+from ansible.module_utils.six.moves.urllib.parse import urlencode
+from ansible.module_utils._text import to_text
+from ansible.module_utils._text import to_native
+
+
+class OcpQuery(object):
+ def __init__(self, host, port, token, validate_certs):
+ self.apis = ['api', 'oapi']
+ self.token = token
+ self.validate_certs = validate_certs
+ self.host = host
+ self.port = port
+ self.kinds = {}
+ bearer = "Bearer " + self.token
+ self.headers = {"Authorization": bearer}
+ self.build_facts()
+
+ def build_facts(self):
+
+ for api in self.apis:
+ url = "https://{0}:{1}/{2}/v1".format(self.host, self.port, api)
+ try:
+ response = urls.open_url(url=url,
+ headers=self.headers,
+ validate_certs=self.validate_certs,
+ method='get')
+ except urllib_error.HTTPError as error:
+ try:
+ body = to_native(error.read())
+ except AttributeError:
+ body = ''
+ raise AnsibleError("OC Query raised exception with code {0} and message {1} against url {2}".format(error.code, body, url))
+
+ for resource in json.loads(to_text(response.read(), errors='surrogate_or_strict'))['resources']:
+ if 'generated' not in resource['name']:
+ self.kinds[resource['kind']] = \
+ {'kind': resource['kind'],
+ 'name': resource['name'].split('/')[0],
+ 'namespaced': resource['namespaced'],
+ 'api': api,
+ 'version': 'v1',
+ 'baseurl': url
+ }
+
+ def url(self, kind=None, namespace=None, resource_name=None, pretty=False, labelSelector=None, fieldSelector=None, resourceVersion=None):
+ first_param = True
+
+ url = [self.kinds[kind]['baseurl']]
+ if self.kinds[kind]['namespaced'] is True:
+ url.append('/namespaces/')
+ if namespace is None:
+ raise AnsibleError('Kind %s requires a namespace.'
+ ' None provided' % kind)
+ url.append(namespace)
+
+ url.append('/' + self.kinds[kind]['name'])
+
+ if resource_name is not None:
+ url.append('/' + resource_name)
+
+ if pretty:
+ url.append('?pretty')
+ first_param = False
+
+ if labelSelector is not None:
+ if first_param:
+ url.append('?')
+ else:
+ url.append('&')
+
+ url.append(urlencode({'labelSelector': labelSelector}))
+ first_param = False
+
+ if fieldSelector is not None:
+ if first_param:
+ url.append('?')
+ else:
+ url.append('&')
+
+ url.append(urlencode({'fieldSelector': fieldSelector}))
+ first_param = False
+
+ if resourceVersion is not None:
+ if first_param:
+ url.append('?')
+ else:
+ url.append('&')
+
+ url.append(urlencode({'resourceVersion': resourceVersion}))
+ first_param = False
+
+ return "".join(url)
+
+ def query(self, kind=None, namespace=None, resource_name=None, pretty=False, labelSelector=None, fieldSelector=None, resourceVersion=None):
+ url = self.url(kind=kind,
+ namespace=namespace,
+ resource_name=resource_name,
+ pretty=pretty,
+ labelSelector=labelSelector,
+ fieldSelector=fieldSelector,
+ resourceVersion=resourceVersion)
+
+ try:
+ response = urls.open_url(url=url,
+ headers=self.headers,
+ validate_certs=self.validate_certs,
+ method='get')
+ except urllib_error.HTTPError as error:
+ try:
+ body = to_native(error.read())
+ except AttributeError:
+ body = ''
+ raise AnsibleError("OC Query raised exception with code {0} and message {1} against url {2}".format(error.code, body, url))
+
+ return json.loads(to_text(response.read(), errors='surrogate_or_strict'))
+
+
+class LookupModule(LookupBase):
+ def run(self, terms, variables=None, **kwargs):
+
+ host = kwargs.get('host', '127.0.0.1')
+ port = kwargs.get('port', '8443')
+ validate_certs = kwargs.get('validate_certs', True)
+ token = kwargs.get('token', None)
+
+ namespace = kwargs.get('namespace', None)
+ resource_name = kwargs.get('resource_name', None)
+ pretty = kwargs.get('pretty', False)
+ label_selector = kwargs.get('labelSelector', None)
+ field_selector = kwargs.get('fieldSelector', None)
+ resource_version = kwargs.get('resourceVersion', None)
+ resource_kind = kwargs.get('kind', None)
+
+ ocp = OcpQuery(host, port, token, validate_certs)
+
+ search_response = ocp.query(kind=resource_kind,
+ namespace=namespace,
+ resource_name=resource_name,
+ pretty=pretty,
+ labelSelector=label_selector,
+ fieldSelector=field_selector,
+ resourceVersion=resource_version)
+ if search_response is not None and "items" in search_response:
+ search_response['item_list'] = search_response.pop('items')
+
+ values = [search_response]
+
+ return values
| ##### SUMMARY
The OC plugin allows for the creation, deletion and modification of OpenShift resources in a cluster. There are use cases where one may wish to simply **read** resources from a cluster. This functionality could be built into the existing OC module. But, given the paradigm for Ansible, it seems more appropriate to have this **read** functionality in a lookup plugin.
##### ISSUE TYPE
- New Module Pull Request
##### COMPONENT NAME
plugins/lookup/openshift.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
ansible 2.5.0 (oc-lookup 00299a63b0) last updated 2017/10/10 08:50:47 (GMT -400)
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/Users/k6n/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /Users/k6n/git/ansible/lib/ansible
executable location = ./bin/ansible
python version = 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
```
##### ADDITIONAL INFORMATION
The following is an example of how this could be used.
<!--- Paste verbatim command output below, e.g. before and after your change -->
```yaml
---
# file: migrate.yml
- hosts: all
vars:
ansible_become: false
validate_certs: false
project_name: myproject
tasks:
- name: Get Project {{ project_name }}
set_fact:
my_project: "{{ lookup('oc',
'Project',
host=inventory_host,
token=hostvars[inventory_host]['ansible_sa_token'],
resource_name=project_name,
validate_certs=validate_certs) }}"
- debug:
var: my_project
```
| https://api.github.com/repos/ansible/ansible/pulls/31525 | 2017-10-10T12:57:26Z | 2017-11-07T00:21:53Z | 2017-11-07T00:21:53Z | 2019-04-26T23:02:10Z | 2,088 | ansible/ansible | 49,153 |
Updated README.md to provide more insight on BLEU and specific appendices | diff --git a/README.md b/README.md
index 64e2d84c..2916e91c 100644
--- a/README.md
+++ b/README.md
@@ -70,7 +70,7 @@ There are five model sizes, four with English-only versions, offering speed and
The `.en` models for English-only applications tend to perform better, especially for the `tiny.en` and `base.en` models. We observed that the difference becomes less significant for the `small.en` and `medium.en` models.
-Whisper's performance varies widely depending on the language. The figure below shows a WER (Word Error Rate) breakdown by languages of the Fleurs dataset using the `large-v2` model. More WER and BLEU scores corresponding to the other models and datasets can be found in Appendix D in [the paper](https://arxiv.org/abs/2212.04356). The smaller, the better.
+Whisper's performance varies widely depending on the language. The figure below shows a WER (Word Error Rate) breakdown by languages of the Fleurs dataset using the `large-v2` model (The smaller the numbers, the better the performance). Additional WER scores corresponding to the other models and datasets can be found in Appendix D.1, D.2, and D.4. Meanwhile, more BLEU (Bilingual Evaluation Understudy) scores can be found in Appendix D.3. Both are found in [the paper](https://arxiv.org/abs/2212.04356).

| **Improves Documentation**
Previous documentation did not include a description of what BLEU acronym stood for. Additionally, did not provide the specific appendices to find additional comparisons for WER and BLEU scores for other models.
This change improves readability of the Available models and languages section of the README.md and includes the full description of the acronym BLEU and specific appendices within the research paper. | https://api.github.com/repos/openai/whisper/pulls/1236 | 2023-04-15T16:29:12Z | 2023-05-05T06:47:46Z | 2023-05-05T06:47:46Z | 2023-05-05T06:47:46Z | 353 | openai/whisper | 45,812 |
Fix the gitlab user mention in issue templates to the correct user | diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml
index 427809501b063..1ec76462acfdf 100644
--- a/.github/ISSUE_TEMPLATE/bug-report.yml
+++ b/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -37,7 +37,7 @@ body:
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- - trainer: @muellerz and @pacman100
+ - trainer: @muellerzr and @pacman100
Integrations:
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4b863179b1bcf..d9e6b15f00fd2 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -51,7 +51,7 @@ Library:
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
-- trainer: @muellerz and @pacman100
+- trainer: @muellerzr and @pacman100
Integrations:
| # What does this PR do?
This fixes a wrong suggested tag of a Github user not acquainted with this project to the correct contributor.
#### Personal Note
I can definitely see that his and my username seem switched given our clear names and I'm sorry for any confusion. That username was given to me by a teacher in school who didn't want to spell my full last name and it stuck.
## Before submitting
- [X] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [X] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
[documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
[here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.
Documentation: @stevhliu and @MKhalusova | https://api.github.com/repos/huggingface/transformers/pulls/26237 | 2023-09-18T23:19:10Z | 2023-09-18T23:49:03Z | 2023-09-18T23:49:03Z | 2023-09-19T00:05:31Z | 291 | huggingface/transformers | 11,996 |
Update enable_ipv6.bat | diff --git a/code/default/gae_proxy/local/ipv6_tunnel/enable_ipv6.bat b/code/default/gae_proxy/local/ipv6_tunnel/enable_ipv6.bat
index 37dac97f74..00a6413158 100644
--- a/code/default/gae_proxy/local/ipv6_tunnel/enable_ipv6.bat
+++ b/code/default/gae_proxy/local/ipv6_tunnel/enable_ipv6.bat
@@ -38,7 +38,7 @@ sc start RpcSs
sc config nsi start= auto
sc start nsi
-sc config Wingmt start= auto
+sc config Winmgmt start= auto
sc start Winmgmt
sc config Dhcp start= auto
| change "sc config Wingmt start= auto" to "sc config Winmgmt start=auto" | https://api.github.com/repos/XX-net/XX-Net/pulls/10111 | 2018-03-20T10:04:52Z | 2018-03-22T01:14:11Z | 2018-03-22T01:14:11Z | 2018-03-22T01:14:12Z | 151 | XX-net/XX-Net | 17,071 |
Strip Authorization header whenever root URL changes | diff --git a/requests/sessions.py b/requests/sessions.py
index dd525e2ac9..27d0e9717d 100644
--- a/requests/sessions.py
+++ b/requests/sessions.py
@@ -115,6 +115,22 @@ def get_redirect_target(self, resp):
return to_native_string(location, 'utf8')
return None
+ def should_strip_auth(self, old_url, new_url):
+ """Decide whether Authorization header should be removed when redirecting"""
+ old_parsed = urlparse(old_url)
+ new_parsed = urlparse(new_url)
+ if old_parsed.hostname != new_parsed.hostname:
+ return True
+ # Special case: allow http -> https redirect when using the standard
+ # ports. This isn't specified by RFC 7235, but is kept to avoid
+ # breaking backwards compatibility with older versions of requests
+ # that allowed any redirects on the same host.
+ if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)
+ and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):
+ return False
+ # Standard case: root URI must match
+ return old_parsed.port != new_parsed.port or old_parsed.scheme != new_parsed.scheme
+
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
"""Receives a Response. Returns a generator of Responses or Requests."""
@@ -236,14 +252,10 @@ def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers
url = prepared_request.url
- if 'Authorization' in headers:
+ if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):
# If we get redirected to a new host, we should strip out any
# authentication headers.
- original_parsed = urlparse(response.request.url)
- redirect_parsed = urlparse(url)
-
- if (original_parsed.hostname != redirect_parsed.hostname):
- del headers['Authorization']
+ del headers['Authorization']
# .netrc might have more auth for us on our new host.
new_auth = get_netrc_auth(url) if self.trust_env else None
diff --git a/tests/test_requests.py b/tests/test_requests.py
index fd04ad2705..660437988a 100644
--- a/tests/test_requests.py
+++ b/tests/test_requests.py
@@ -1573,15 +1573,15 @@ def test_nonhttp_schemes_dont_check_URLs(self):
preq = req.prepare()
assert test_url == preq.url
- @pytest.mark.xfail(raises=ConnectionError)
- def test_auth_is_stripped_on_redirect_off_host(self, httpbin):
+ def test_auth_is_stripped_on_http_downgrade(self, httpbin, httpbin_secure, httpbin_ca_bundle):
r = requests.get(
- httpbin('redirect-to'),
- params={'url': 'http://www.google.co.uk'},
+ httpbin_secure('redirect-to'),
+ params={'url': httpbin('get')},
auth=('user', 'pass'),
+ verify=httpbin_ca_bundle
)
assert r.history[0].request.headers['Authorization']
- assert not r.request.headers.get('Authorization', '')
+ assert 'Authorization' not in r.request.headers
def test_auth_is_retained_for_redirect_on_host(self, httpbin):
r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))
@@ -1590,6 +1590,27 @@ def test_auth_is_retained_for_redirect_on_host(self, httpbin):
assert h1 == h2
+ def test_should_strip_auth_host_change(self):
+ s = requests.Session()
+ assert s.should_strip_auth('http://example.com/foo', 'http://another.example.com/')
+
+ def test_should_strip_auth_http_downgrade(self):
+ s = requests.Session()
+ assert s.should_strip_auth('https://example.com/foo', 'http://example.com/bar')
+
+ def test_should_strip_auth_https_upgrade(self):
+ s = requests.Session()
+ assert not s.should_strip_auth('http://example.com/foo', 'https://example.com/bar')
+ assert not s.should_strip_auth('http://example.com:80/foo', 'https://example.com/bar')
+ assert not s.should_strip_auth('http://example.com/foo', 'https://example.com:443/bar')
+ # Non-standard ports should trigger stripping
+ assert s.should_strip_auth('http://example.com:8080/foo', 'https://example.com/bar')
+ assert s.should_strip_auth('http://example.com/foo', 'https://example.com:8443/bar')
+
+ def test_should_strip_auth_port_change(self):
+ s = requests.Session()
+ assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar')
+
def test_manual_redirect_with_partial_body_read(self, httpbin):
s = requests.Session()
r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)
| Previously the header was stripped only if the hostname changed, but in
an https -> http redirect that can leak the credentials on the wire
(#4716). Based on with RFC 7235 section 2.2, the header is now stripped
if the "canonical root URL" (scheme+authority) has changed.
Closes #4716. | https://api.github.com/repos/psf/requests/pulls/4718 | 2018-06-28T14:48:34Z | 2018-09-14T12:08:05Z | 2018-09-14T12:08:05Z | 2021-09-01T00:11:53Z | 1,132 | psf/requests | 32,915 |
Backport PR #54927 on branch 2.1.x (REGR: interpolate raising if fill_value is given) | diff --git a/doc/source/whatsnew/v2.1.1.rst b/doc/source/whatsnew/v2.1.1.rst
index 11b19b1508a71..9dcc829ba7db3 100644
--- a/doc/source/whatsnew/v2.1.1.rst
+++ b/doc/source/whatsnew/v2.1.1.rst
@@ -21,6 +21,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.to_sql` not roundtripping datetime columns correctly for sqlite (:issue:`54877`)
- Fixed regression in :meth:`MultiIndex.append` raising when appending overlapping :class:`IntervalIndex` levels (:issue:`54934`)
- Fixed regression in :meth:`Series.drop_duplicates` for PyArrow strings (:issue:`54904`)
+- Fixed regression in :meth:`Series.interpolate` raising when ``fill_value`` was given (:issue:`54920`)
- Fixed regression in :meth:`Series.value_counts` raising for numeric data if ``bins`` was specified (:issue:`54857`)
- Fixed regression when comparing a :class:`Series` with ``datetime64`` dtype with ``None`` (:issue:`54870`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f6bf51f65049a..23c37fb34ec0d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8160,10 +8160,11 @@ def interpolate(
stacklevel=find_stack_level(),
)
- if "fill_value" in kwargs:
+ if method in fillna_methods and "fill_value" in kwargs:
raise ValueError(
"'fill_value' is not a valid keyword for "
- f"{type(self).__name__}.interpolate"
+ f"{type(self).__name__}.interpolate with method from "
+ f"{fillna_methods}"
)
if isinstance(obj.index, MultiIndex) and method != "linear":
diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py
index 619690f400d98..549f429f09d35 100644
--- a/pandas/tests/series/methods/test_interpolate.py
+++ b/pandas/tests/series/methods/test_interpolate.py
@@ -858,3 +858,11 @@ def test_interpolate_asfreq_raises(self):
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(FutureWarning, match=msg2):
ser.interpolate(method="asfreq")
+
+ def test_interpolate_fill_value(self):
+ # GH#54920
+ pytest.importorskip("scipy")
+ ser = Series([np.nan, 0, 1, np.nan, 3, np.nan])
+ result = ser.interpolate(method="nearest", fill_value=0)
+ expected = Series([np.nan, 0, 1, 1, 3, 0])
+ tm.assert_series_equal(result, expected)
| Backport PR #54927: REGR: interpolate raising if fill_value is given | https://api.github.com/repos/pandas-dev/pandas/pulls/55017 | 2023-09-05T18:43:34Z | 2023-09-05T23:50:28Z | 2023-09-05T23:50:28Z | 2023-09-05T23:50:28Z | 668 | pandas-dev/pandas | 45,499 |
Add `Notus` support | diff --git a/docs/model_support.md b/docs/model_support.md
index 3420f5e3a6..86e08fed0a 100644
--- a/docs/model_support.md
+++ b/docs/model_support.md
@@ -36,6 +36,7 @@
- example: `python3 -m fastchat.serve.cli --model-path mosaicml/mpt-7b-chat`
- [Neutralzz/BiLLa-7B-SFT](https://huggingface.co/Neutralzz/BiLLa-7B-SFT)
- [nomic-ai/gpt4all-13b-snoozy](https://huggingface.co/nomic-ai/gpt4all-13b-snoozy)
+- [argilla/notus-7b-v1](https://huggingface.co/argilla/notus-7b-v1)
- [NousResearch/Nous-Hermes-13b](https://huggingface.co/NousResearch/Nous-Hermes-13b)
- [openaccess-ai-collective/manticore-13b-chat-pyg](https://huggingface.co/openaccess-ai-collective/manticore-13b-chat-pyg)
- [OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5](https://huggingface.co/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5)
diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py
index 7aee537dfc..b0f1c80629 100644
--- a/fastchat/model/model_adapter.py
+++ b/fastchat/model/model_adapter.py
@@ -1951,6 +1951,16 @@ def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("zephyr")
+class NotusAdapter(BaseModelAdapter):
+ """The model adapter for Notus (e.g. argilla/notus-7b-v1)"""
+
+ def match(self, model_path: str):
+ return "notus" in model_path.lower()
+
+ def get_default_conv_template(self, model_path: str) -> Conversation:
+ return get_conv_template("zephyr")
+
+
class CatPPTAdapter(BaseModelAdapter):
"""The model adapter for CatPPT (e.g. rishiraj/CatPPT)"""
@@ -2161,6 +2171,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation:
register_model_adapter(CodeLlamaAdapter)
register_model_adapter(Llama2ChangAdapter)
register_model_adapter(ZephyrAdapter)
+register_model_adapter(NotusAdapter)
register_model_adapter(CatPPTAdapter)
register_model_adapter(TinyLlamaAdapter)
register_model_adapter(XwinLMAdapter)
diff --git a/fastchat/model/model_registry.py b/fastchat/model/model_registry.py
index ab54d23f9f..60fd55df28 100644
--- a/fastchat/model/model_registry.py
+++ b/fastchat/model/model_registry.py
@@ -168,6 +168,13 @@ def get_model_info(name: str) -> ModelInfo:
"a chatbot fine-tuned from Mistral by Hugging Face",
)
+register_model_info(
+ ["notus-7b-v1"],
+ "Notus",
+ "https://huggingface.co/argilla/notus-7b-v1",
+ "a chatbot fine-tuned from Zephyr SFT by Argilla",
+)
+
register_model_info(
["catppt"],
"CatPPT",
| ## Why are these changes needed?
At @argilla-io we fine-tuned Zephyr SFT using DPO and a new version of the UltraFeedback dataset after detecting some issues with the critique score in the original UltraFeedback dataset that was used to fine-tune Zephyr 7B Beta. We called this model Notus 7B v1 and it achieved roughly the same score as Zephyr in MT-Bench while exhibiting a better instruction following.
More information about Notus:
- https://argilla.io/blog/notus7b/
- https://huggingface.co/argilla/notus-7b-v1
## Checks
- [x] I've run `format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed.
- [ ] I've made sure the relevant tests are passing (if applicable).
| https://api.github.com/repos/lm-sys/FastChat/pulls/2813 | 2023-12-13T09:41:56Z | 2024-01-07T21:04:32Z | 2024-01-07T21:04:32Z | 2024-01-07T21:04:32Z | 787 | lm-sys/FastChat | 41,590 |
FIX [`quantization` / `ESM`] Fix ESM 8bit / 4bit with bitsandbytes | diff --git a/src/transformers/models/esm/modeling_esm.py b/src/transformers/models/esm/modeling_esm.py
index 57c436224099c..2349ce580023d 100755
--- a/src/transformers/models/esm/modeling_esm.py
+++ b/src/transformers/models/esm/modeling_esm.py
@@ -377,7 +377,7 @@ def forward(
if head_mask is not None:
attention_probs = attention_probs * head_mask
- context_layer = torch.matmul(attention_probs, value_layer)
+ context_layer = torch.matmul(attention_probs.to(value_layer.dtype), value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
diff --git a/src/transformers/quantizers/quantizer_bnb_4bit.py b/src/transformers/quantizers/quantizer_bnb_4bit.py
index 6cea1b5512392..494bf1382e9f7 100644
--- a/src/transformers/quantizers/quantizer_bnb_4bit.py
+++ b/src/transformers/quantizers/quantizer_bnb_4bit.py
@@ -121,7 +121,7 @@ def check_quantized_param(
import bitsandbytes as bnb
module, tensor_name = get_module_from_name(model, param_name)
- if isinstance(module._parameters[tensor_name], bnb.nn.Params4bit):
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Params4bit):
# Add here check for loaded components' dtypes once serialization is implemented
return True
elif isinstance(module, bnb.nn.Linear4bit) and tensor_name == "bias":
diff --git a/src/transformers/quantizers/quantizer_bnb_8bit.py b/src/transformers/quantizers/quantizer_bnb_8bit.py
index 193da44d2c855..cc6942857af8f 100644
--- a/src/transformers/quantizers/quantizer_bnb_8bit.py
+++ b/src/transformers/quantizers/quantizer_bnb_8bit.py
@@ -139,7 +139,7 @@ def check_quantized_param(
import bitsandbytes as bnb
module, tensor_name = get_module_from_name(model, param_name)
- if isinstance(module._parameters[tensor_name], bnb.nn.Int8Params):
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params):
if self.pre_quantized:
if param_name.replace("weight", "SCB") not in state_dict.keys():
raise ValueError("Missing quantization component `SCB`")
diff --git a/tests/models/esm/test_modeling_esm.py b/tests/models/esm/test_modeling_esm.py
index d09326df606b3..7e99f86bbf626 100644
--- a/tests/models/esm/test_modeling_esm.py
+++ b/tests/models/esm/test_modeling_esm.py
@@ -18,7 +18,7 @@
import unittest
from transformers import EsmConfig, is_torch_available
-from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
+from transformers.testing_utils import TestCasePlus, require_bitsandbytes, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
@@ -303,9 +303,9 @@ def test_resize_tokens_embeddings(self):
pass
+@slow
@require_torch
class EsmModelIntegrationTest(TestCasePlus):
- @slow
def test_inference_masked_lm(self):
with torch.no_grad():
model = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D")
@@ -323,7 +323,6 @@ def test_inference_masked_lm(self):
)
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
- @slow
def test_inference_no_head(self):
with torch.no_grad():
model = EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D")
@@ -336,3 +335,18 @@ def test_inference_no_head(self):
[[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]]
)
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
+
+ @require_bitsandbytes
+ def test_inference_bitsandbytes(self):
+ model = EsmForMaskedLM.from_pretrained("facebook/esm2_t36_3B_UR50D", load_in_8bit=True)
+
+ input_ids = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
+ # Just test if inference works
+ with torch.no_grad():
+ _ = model(input_ids)[0]
+
+ model = EsmForMaskedLM.from_pretrained("facebook/esm2_t36_3B_UR50D", load_in_4bit=True)
+
+ input_ids = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
+ # Just test if inference works
+ _ = model(input_ids)[0]
| # What does this PR do?
Fixes: https://github.com/huggingface/transformers/issues/29323
Currently on main, simply running:
```python
import torch
from transformers import AutoModelForMaskedLM, AutoTokenizer
model = AutoModelForMaskedLM.from_pretrained("facebook/esm2_t36_3B_UR50D", load_in_4bit=True)
```
Fails with an error
```bash
File "/home/younes_huggingface_co/code/transformers/src/transformers/modeling_utils.py", line 802, in _load_state_dict_into_meta_model
or (not hf_quantizer.check_quantized_param(model, param, param_name, state_dict))
File "/home/younes_huggingface_co/code/transformers/src/transformers/quantizers/quantizer_bnb_4bit.py", line 124, in check_quantized_param
if isinstance(module._parameters[tensor_name], bnb.nn.Params4bit):
KeyError: 'inv_freq'
```
This is because the model pushed in `"facebook/esm2_t36_3B_UR50D"` do not contain the `inv_freq`. Maybe during the HfQuantizer refactor we did not properly dealt with that specific scenario, leading to this bug for transformers > 4.37
cc @SunMarc
I ran the quantization tests and they seem to all pass on my end | https://api.github.com/repos/huggingface/transformers/pulls/29329 | 2024-02-28T01:11:48Z | 2024-03-01T02:01:53Z | 2024-03-01T02:01:53Z | 2024-03-11T09:34:07Z | 1,275 | huggingface/transformers | 12,330 |
gh-110147: run console io test in new process | diff --git a/Lib/test/test_msvcrt.py b/Lib/test/test_msvcrt.py
index 81ec13026014e6..600c4446fd5cd4 100644
--- a/Lib/test/test_msvcrt.py
+++ b/Lib/test/test_msvcrt.py
@@ -1,17 +1,17 @@
import os
+import subprocess
import sys
import unittest
+from textwrap import dedent
-from test.support import os_helper
+from test.support import os_helper, requires_resource
from test.support.os_helper import TESTFN, TESTFN_ASCII
if sys.platform != "win32":
raise unittest.SkipTest("windows related tests")
import _winapi
-import msvcrt;
-
-from _testconsole import write_input, flush_console_input_buffer
+import msvcrt
class TestFileOperations(unittest.TestCase):
@@ -61,34 +61,45 @@ def test_get_osfhandle(self):
class TestConsoleIO(unittest.TestCase):
+ # CREATE_NEW_CONSOLE creates a "popup" window.
+ @requires_resource('gui')
+ def run_in_separated_process(self, code):
+ # Run test in a seprated process to avoid stdin conflicts.
+ # See: gh-110147
+ cmd = [sys.executable, '-c', code]
+ subprocess.run(cmd, check=True, capture_output=True,
+ creationflags=subprocess.CREATE_NEW_CONSOLE)
+
def test_kbhit(self):
- h = msvcrt.get_osfhandle(sys.stdin.fileno())
- flush_console_input_buffer(h)
- self.assertEqual(msvcrt.kbhit(), 0)
+ code = dedent('''
+ import msvcrt
+ assert msvcrt.kbhit() == 0
+ ''')
+ self.run_in_separated_process(code)
def test_getch(self):
msvcrt.ungetch(b'c')
self.assertEqual(msvcrt.getch(), b'c')
- def test_getwch(self):
- with open('CONIN$', 'rb', buffering=0) as stdin:
- h = msvcrt.get_osfhandle(stdin.fileno())
- flush_console_input_buffer(h)
+ def check_getwch(self, funcname):
+ code = dedent(f'''
+ import msvcrt
+ from _testconsole import write_input
+ with open("CONIN$", "rb", buffering=0) as stdin:
+ write_input(stdin, {ascii(c_encoded)})
+ assert msvcrt.{funcname}() == "{c}"
+ ''')
+ self.run_in_separated_process(code)
- write_input(stdin, c_encoded)
- self.assertEqual(msvcrt.getwch(), c)
+ def test_getwch(self):
+ self.check_getwch('getwch')
def test_getche(self):
msvcrt.ungetch(b'c')
self.assertEqual(msvcrt.getche(), b'c')
def test_getwche(self):
- with open('CONIN$', 'rb', buffering=0) as stdin:
- h = msvcrt.get_osfhandle(stdin.fileno())
- flush_console_input_buffer(h)
-
- write_input(stdin, c_encoded)
- self.assertEqual(msvcrt.getwche(), c)
+ self.check_getwch('getwche')
def test_putch(self):
msvcrt.putch(b'c')
diff --git a/PC/_testconsole.c b/PC/_testconsole.c
index 5e5a771b96bfec..1dc0d230c4d7c3 100644
--- a/PC/_testconsole.c
+++ b/PC/_testconsole.c
@@ -133,31 +133,12 @@ _testconsole_read_output_impl(PyObject *module, PyObject *file)
Py_RETURN_NONE;
}
-/*[clinic input]
-_testconsole.flush_console_input_buffer
- handle: HANDLE
-
-Flushes the console input buffer.
-
-All input records currently in the input buffer are discarded.
-[clinic start generated code]*/
-
-static PyObject *
-_testconsole_flush_console_input_buffer_impl(PyObject *module, void *handle)
-/*[clinic end generated code: output=1f923a81331465ce input=be8203ae84a288f5]*/
-/*[clinic end generated code:]*/
-{
- FlushConsoleInputBuffer(handle);
-
- Py_RETURN_NONE;
-}
#include "clinic\_testconsole.c.h"
PyMethodDef testconsole_methods[] = {
_TESTCONSOLE_WRITE_INPUT_METHODDEF
_TESTCONSOLE_READ_OUTPUT_METHODDEF
- _TESTCONSOLE_FLUSH_CONSOLE_INPUT_BUFFER_METHODDEF
{NULL, NULL}
};
diff --git a/PC/clinic/_testconsole.c.h b/PC/clinic/_testconsole.c.h
index b76588909782ea..99cd302ff34698 100644
--- a/PC/clinic/_testconsole.c.h
+++ b/PC/clinic/_testconsole.c.h
@@ -132,70 +132,6 @@ _testconsole_read_output(PyObject *module, PyObject *const *args, Py_ssize_t nar
#endif /* defined(MS_WINDOWS) */
-#if defined(MS_WINDOWS)
-
-PyDoc_STRVAR(_testconsole_flush_console_input_buffer__doc__,
-"flush_console_input_buffer($module, /, handle)\n"
-"--\n"
-"\n"
-"Flushes the console input buffer.\n"
-"\n"
-"All input records currently in the input buffer are discarded.");
-
-#define _TESTCONSOLE_FLUSH_CONSOLE_INPUT_BUFFER_METHODDEF \
- {"flush_console_input_buffer", _PyCFunction_CAST(_testconsole_flush_console_input_buffer), METH_FASTCALL|METH_KEYWORDS, _testconsole_flush_console_input_buffer__doc__},
-
-static PyObject *
-_testconsole_flush_console_input_buffer_impl(PyObject *module, void *handle);
-
-static PyObject *
-_testconsole_flush_console_input_buffer(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
-{
- PyObject *return_value = NULL;
- #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
-
- #define NUM_KEYWORDS 1
- static struct {
- PyGC_Head _this_is_not_used;
- PyObject_VAR_HEAD
- PyObject *ob_item[NUM_KEYWORDS];
- } _kwtuple = {
- .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
- .ob_item = { &_Py_ID(handle), },
- };
- #undef NUM_KEYWORDS
- #define KWTUPLE (&_kwtuple.ob_base.ob_base)
-
- #else // !Py_BUILD_CORE
- # define KWTUPLE NULL
- #endif // !Py_BUILD_CORE
-
- static const char * const _keywords[] = {"handle", NULL};
- static _PyArg_Parser _parser = {
- .keywords = _keywords,
- .fname = "flush_console_input_buffer",
- .kwtuple = KWTUPLE,
- };
- #undef KWTUPLE
- PyObject *argsbuf[1];
- void *handle;
-
- args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf);
- if (!args) {
- goto exit;
- }
- handle = PyLong_AsVoidPtr(args[0]);
- if (!handle && PyErr_Occurred()) {
- goto exit;
- }
- return_value = _testconsole_flush_console_input_buffer_impl(module, handle);
-
-exit:
- return return_value;
-}
-
-#endif /* defined(MS_WINDOWS) */
-
#ifndef _TESTCONSOLE_WRITE_INPUT_METHODDEF
#define _TESTCONSOLE_WRITE_INPUT_METHODDEF
#endif /* !defined(_TESTCONSOLE_WRITE_INPUT_METHODDEF) */
@@ -203,8 +139,4 @@ _testconsole_flush_console_input_buffer(PyObject *module, PyObject *const *args,
#ifndef _TESTCONSOLE_READ_OUTPUT_METHODDEF
#define _TESTCONSOLE_READ_OUTPUT_METHODDEF
#endif /* !defined(_TESTCONSOLE_READ_OUTPUT_METHODDEF) */
-
-#ifndef _TESTCONSOLE_FLUSH_CONSOLE_INPUT_BUFFER_METHODDEF
- #define _TESTCONSOLE_FLUSH_CONSOLE_INPUT_BUFFER_METHODDEF
-#endif /* !defined(_TESTCONSOLE_FLUSH_CONSOLE_INPUT_BUFFER_METHODDEF) */
-/*[clinic end generated code: output=5d488564f2500dd9 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=f59fe72cd4e73704 input=a9049054013a1b77]*/
| <!--
Thanks for your contribution!
Please read this comment in its entirety. It's quite important.
# Pull Request title
It should be in the following format:
```
gh-NNNNN: Summary of the changes made
```
Where: gh-NNNNN refers to the GitHub issue number.
Most PRs will require an issue number. Trivial changes, like fixing a typo, do not need an issue.
# Backport Pull Request title
If this is a backport PR (PR made against branches other than `main`),
please ensure that the PR title is in the following format:
```
[X.Y] <title from the original PR> (GH-NNNN)
```
Where: [X.Y] is the branch name, e.g. [3.6].
GH-NNNN refers to the PR number from `main`.
-->
<!-- gh-issue-number: gh-110147 -->
* Issue: gh-110147
<!-- /gh-issue-number -->
| https://api.github.com/repos/python/cpython/pulls/110268 | 2023-10-03T09:23:59Z | 2023-10-05T17:52:26Z | 2023-10-05T17:52:26Z | 2023-10-05T17:52:56Z | 1,923 | python/cpython | 4,528 |
update documentation on how to set ulimit for Redis | diff --git a/doc/source/using-ray-on-a-large-cluster.md b/doc/source/using-ray-on-a-large-cluster.md
index f90499c9c71cb..ea101fa722cbf 100644
--- a/doc/source/using-ray-on-a-large-cluster.md
+++ b/doc/source/using-ray-on-a-large-cluster.md
@@ -237,6 +237,8 @@ Note that the destination argument for this command must represent an absolute p
## Troubleshooting
+### Problems with parallel-ssh
+
If any of the above commands fail, verify that the head node has SSH access to
the other nodes by running
@@ -253,3 +255,19 @@ node with agent forwarding enabled. This is done as follows.
ssh-add <ssh-key>
ssh -A ubuntu@<head-node-public-ip>
```
+
+### Configuring EC2 instances to increase the number of allowed Redis clients
+
+This section can be ignored unless you run into problems with the maximum
+number of Redis clients.
+
+* Ensure that the hard limit for the number of open file descriptors is set
+ to a large number (e.g., 65536). This only needs to be done on instances
+ where Redis shards will run --- by default, just the _head node_.
+ - Check the hard ulimit for open file descriptors with `ulimit -Hn`
+ - If that number is smaller than 65536, set the hard ulimit for open file descriptors
+ system-wide:
+ ```
+ sudo bash -c "echo $USER hard nofile 65536 >> /etc/security/limits.conf"
+ ```
+ - Logout and log back in
| https://api.github.com/repos/ray-project/ray/pulls/508 | 2017-05-03T21:37:39Z | 2017-05-04T00:24:58Z | 2017-05-04T00:24:58Z | 2017-05-04T00:49:14Z | 360 | ray-project/ray | 19,696 | |
styles(profiling): Additional styles for inlining stacktrace component | diff --git a/static/app/components/events/interfaces/crashContent/stackTrace/contentV3.tsx b/static/app/components/events/interfaces/crashContent/stackTrace/contentV3.tsx
index cf40965f337e47..321b425e019062 100644
--- a/static/app/components/events/interfaces/crashContent/stackTrace/contentV3.tsx
+++ b/static/app/components/events/interfaces/crashContent/stackTrace/contentV3.tsx
@@ -18,8 +18,8 @@ type Props = {
platform: PlatformType;
expandFirstFrame?: boolean;
groupingCurrentLevel?: Group['metadata']['current_level'];
- hideIcon?: boolean;
includeSystemFrames?: boolean;
+ inlined?: boolean;
isHoverPreviewed?: boolean;
maxDepth?: number;
meta?: Record<any, any>;
@@ -32,6 +32,7 @@ function Content({
event,
newestFirst,
isHoverPreviewed,
+ inlined,
groupingCurrentLevel,
includeSystemFrames = true,
expandFirstFrame = true,
@@ -171,7 +172,9 @@ function Content({
prevFrame,
nextFrame,
isExpanded: expandFirstFrame && lastFrameIndex === frameIndex,
- emptySourceNotation: lastFrameIndex === frameIndex && frameIndex === 0,
+ emptySourceNotation: inlined
+ ? false
+ : lastFrameIndex === frameIndex && frameIndex === 0,
platform,
timesRepeated: nRepeats,
showingAbsoluteAddress: showingAbsoluteAddresses,
@@ -231,7 +234,11 @@ function Content({
return (
<Wrapper className={className}>
- <Frames isHoverPreviewed={isHoverPreviewed} data-test-id="stack-trace">
+ <Frames
+ isHoverPreviewed={isHoverPreviewed}
+ inlined={inlined}
+ data-test-id="stack-trace"
+ >
{!newestFirst ? convertedFrames : [...convertedFrames].reverse()}
</Frames>
</Wrapper>
@@ -248,7 +255,7 @@ const Wrapper = styled(Panel)`
}
`;
-const Frames = styled('ul')<{isHoverPreviewed?: boolean}>`
+export const Frames = styled('ul')<{inlined?: boolean; isHoverPreviewed?: boolean}>`
background: ${p => p.theme.background};
border-radius: ${p => p.theme.borderRadius};
border: 1px ${p => 'solid ' + p.theme.border};
@@ -268,4 +275,12 @@ const Frames = styled('ul')<{isHoverPreviewed?: boolean}>`
box-shadow: none;
margin-bottom: 0;
`}
+
+ ${p =>
+ p.inlined &&
+ `
+ border-radius: 0;
+ border-left: 0;
+ border-right: 0;
+ `}
`;
diff --git a/static/app/components/events/interfaces/crashContent/stackTrace/index.tsx b/static/app/components/events/interfaces/crashContent/stackTrace/index.tsx
index 575d4edbc49d72..694a0f5fafb3d0 100644
--- a/static/app/components/events/interfaces/crashContent/stackTrace/index.tsx
+++ b/static/app/components/events/interfaces/crashContent/stackTrace/index.tsx
@@ -58,7 +58,6 @@ function StackTrace({
newestFirst={newestFirst}
groupingCurrentLevel={groupingCurrentLevel}
meta={meta}
- hideIcon={inlined}
inlined={inlined}
maxDepth={maxDepth}
/>
diff --git a/static/app/components/events/interfaces/frame/line.tsx b/static/app/components/events/interfaces/frame/line.tsx
index 7de784e0f534ae..4ac1b34faf151c 100644
--- a/static/app/components/events/interfaces/frame/line.tsx
+++ b/static/app/components/events/interfaces/frame/line.tsx
@@ -437,6 +437,7 @@ const LeftLineTitle = styled('div')`
const RepeatedContent = styled(LeftLineTitle)`
justify-content: center;
+ margin-right: ${space(1)};
`;
const NativeLineContent = styled('div')<{isFrameAfterLastNonApp: boolean}>`
diff --git a/static/app/components/events/interfaces/frame/lineV2/default.tsx b/static/app/components/events/interfaces/frame/lineV2/default.tsx
index a4b55752513c98..44b637ae9f2fc5 100644
--- a/static/app/components/events/interfaces/frame/lineV2/default.tsx
+++ b/static/app/components/events/interfaces/frame/lineV2/default.tsx
@@ -126,6 +126,7 @@ const Title = styled('div')`
const RepeatedContent = styled(VertCenterWrapper)`
justify-content: center;
+ margin-right: ${space(1)};
`;
const RepeatedFrames = styled('div')`
| This adds addition styles for the stacktrace component when inlined for profiling use cases. This includes
- removing the border from native stacktraces
- adds some space between the recursion icon and the in app/system badge
# Screenshots
## Before

## After

| https://api.github.com/repos/getsentry/sentry/pulls/46390 | 2023-03-27T17:05:18Z | 2023-03-28T11:04:06Z | 2023-03-28T11:04:06Z | 2023-04-12T12:00:49Z | 1,078 | getsentry/sentry | 44,153 |
[Core] [runtime env] [Tests] Add C++ unit test for dispatch queue nonblocking behavior | diff --git a/src/ray/raylet/scheduling/cluster_task_manager_test.cc b/src/ray/raylet/scheduling/cluster_task_manager_test.cc
index db7020ca34bfb..901595e8bf0e6 100644
--- a/src/ray/raylet/scheduling/cluster_task_manager_test.cc
+++ b/src/ray/raylet/scheduling/cluster_task_manager_test.cc
@@ -47,12 +47,23 @@ class MockWorkerPool : public WorkerPoolInterface {
std::shared_ptr<WorkerInterface> PopWorker(const TaskSpecification &task_spec) {
num_pops++;
- if (workers.empty()) {
- return nullptr;
+ const WorkerCacheKey env = {task_spec.OverrideEnvironmentVariables(),
+ task_spec.SerializedRuntimeEnv()};
+ const int runtime_env_hash = env.IntHash();
+ std::shared_ptr<WorkerInterface> worker = nullptr;
+
+ for (auto it = workers.begin(); it != workers.end(); it++) {
+ // Skip if the runtime env doesn't match.
+ if (runtime_env_hash != (*it)->GetRuntimeEnvHash()) {
+ continue;
+ }
+
+ worker = std::move(*it);
+ workers.erase(it);
+ break;
}
- auto worker_ptr = workers.front();
- workers.pop_front();
- return worker_ptr;
+
+ return worker;
}
void PushWorker(const std::shared_ptr<WorkerInterface> &worker) {
@@ -77,16 +88,17 @@ std::shared_ptr<ClusterResourceScheduler> CreateSingleNodeScheduler(
}
Task CreateTask(const std::unordered_map<std::string, double> &required_resources,
- int num_args = 0, std::vector<ObjectID> args = {}) {
+ int num_args = 0, std::vector<ObjectID> args = {},
+ std::string serialized_runtime_env = "{}") {
TaskSpecBuilder spec_builder;
TaskID id = RandomTaskId();
JobID job_id = RandomJobId();
rpc::Address address;
- spec_builder.SetCommonTaskSpec(id, "dummy_task", Language::PYTHON,
- FunctionDescriptorBuilder::BuildPython("", "", "", ""),
- job_id, TaskID::Nil(), 0, TaskID::Nil(), address, 0,
- required_resources, {},
- std::make_pair(PlacementGroupID::Nil(), -1), true, "");
+ spec_builder.SetCommonTaskSpec(
+ id, "dummy_task", Language::PYTHON,
+ FunctionDescriptorBuilder::BuildPython("", "", "", ""), job_id, TaskID::Nil(), 0,
+ TaskID::Nil(), address, 0, required_resources, {},
+ std::make_pair(PlacementGroupID::Nil(), -1), true, "", serialized_runtime_env);
if (!args.empty()) {
for (auto &arg : args) {
@@ -270,6 +282,70 @@ TEST_F(ClusterTaskManagerTest, BasicTest) {
AssertNoLeaks();
}
+TEST_F(ClusterTaskManagerTest, DispatchQueueNonBlockingTest) {
+ /*
+ Test that if no worker is available for the first task in a dispatch
+ queue (because the runtime env in the task spec doesn't match any
+ available worker), other tasks in the dispatch queue can still be scheduled.
+ https://github.com/ray-project/ray/issues/16226
+ */
+
+ // Use the same required_resources for all tasks so they end up in the same queue.
+ const std::unordered_map<std::string, double> required_resources = {
+ {ray::kCPU_ResourceLabel, 4}};
+
+ std::string serialized_runtime_env_A = "mock_env_A";
+ Task task_A = CreateTask(required_resources, /*num_args=*/0, /*args=*/{},
+ serialized_runtime_env_A);
+ rpc::RequestWorkerLeaseReply reply_A;
+ bool callback_occurred = false;
+ bool *callback_occurred_ptr = &callback_occurred;
+ auto callback = [callback_occurred_ptr](Status, std::function<void()>,
+ std::function<void()>) {
+ *callback_occurred_ptr = true;
+ };
+
+ std::string serialized_runtime_env_B = "mock_env_B";
+ Task task_B_1 = CreateTask(required_resources, /*num_args=*/0, /*args=*/{},
+ serialized_runtime_env_B);
+ Task task_B_2 = CreateTask(required_resources, /*num_args=*/0, /*args=*/{},
+ serialized_runtime_env_B);
+ rpc::RequestWorkerLeaseReply reply_B_1;
+ rpc::RequestWorkerLeaseReply reply_B_2;
+ auto empty_callback = [](Status, std::function<void()>, std::function<void()>) {};
+
+ // Ensure task_A is not at the front of the queue.
+ task_manager_.QueueAndScheduleTask(task_B_1, &reply_B_1, empty_callback);
+ task_manager_.QueueAndScheduleTask(task_A, &reply_A, callback);
+ task_manager_.QueueAndScheduleTask(task_B_2, &reply_B_2, empty_callback);
+
+ // Push a worker that can only run task A.
+ const WorkerCacheKey env_A = {/*override_environment_variables=*/{},
+ serialized_runtime_env_A};
+ const int runtime_env_hash_A = env_A.IntHash();
+ std::shared_ptr<MockWorker> worker_A =
+ std::make_shared<MockWorker>(WorkerID::FromRandom(), 1234, runtime_env_hash_A);
+ pool_.PushWorker(std::static_pointer_cast<WorkerInterface>(worker_A));
+ ASSERT_EQ(pool_.workers.size(), 1);
+
+ // Check we can schedule task A, even though task B is at the front of the queue
+ // and no workers are available for task B.
+ task_manager_.ScheduleAndDispatchTasks();
+
+ ASSERT_TRUE(callback_occurred);
+ ASSERT_EQ(leased_workers_.size(), 1);
+ ASSERT_EQ(pool_.workers.size(), 0);
+ ASSERT_EQ(node_info_calls_, 0);
+
+ Task finished_task;
+ task_manager_.TaskFinished(leased_workers_.begin()->second, &finished_task);
+ ASSERT_EQ(finished_task.GetTaskSpecification().TaskId(),
+ task_A.GetTaskSpecification().TaskId());
+
+ // task_B_1 and task_B_2 remain in the dispatch queue, so don't call AssertNoLeaks().
+ // AssertNoLeaks();
+}
+
TEST_F(ClusterTaskManagerTest, BlockedWorkerDiesTest) {
/*
Tests the edge case in which a worker crashes while it's blocked. In this case, its CPU
diff --git a/src/ray/raylet/test/util.h b/src/ray/raylet/test/util.h
index 095280b78fcd0..6ccf69881fa60 100644
--- a/src/ray/raylet/test/util.h
+++ b/src/ray/raylet/test/util.h
@@ -20,8 +20,11 @@ namespace raylet {
class MockWorker : public WorkerInterface {
public:
- MockWorker(WorkerID worker_id, int port)
- : worker_id_(worker_id), port_(port), is_detached_actor_(false) {}
+ MockWorker(WorkerID worker_id, int port, int runtime_env_hash = 0)
+ : worker_id_(worker_id),
+ port_(port),
+ is_detached_actor_(false),
+ runtime_env_hash_(runtime_env_hash) {}
WorkerID WorkerId() const { return worker_id_; }
@@ -106,7 +109,7 @@ class MockWorker : public WorkerInterface {
RAY_CHECK(false) << "Method unused";
return JobID::Nil();
}
- int GetRuntimeEnvHash() const { return 0; }
+ int GetRuntimeEnvHash() const { return runtime_env_hash_; }
void AssignActorId(const ActorID &actor_id) { RAY_CHECK(false) << "Method unused"; }
const ActorID &GetActorId() const {
RAY_CHECK(false) << "Method unused";
@@ -194,6 +197,7 @@ class MockWorker : public WorkerInterface {
BundleID bundle_id_;
bool blocked_ = false;
Task task_;
+ int runtime_env_hash_;
};
} // namespace raylet
| <!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. -->
<!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. -->
Adds a unit test for #16535.
## Why are these changes needed?
<!-- Please give a short summary of the change and the problem this solves. -->
## Related issue number
Partial progress towards #16537. A Python integration test will be added in a follow-up PR.
<!-- For example: "Closes #1234" -->
## Checks
- [x] I've run `scripts/format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed for https://docs.ray.io/en/master/.
- [x] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
- [x] Unit tests
- [ ] Release tests
- [ ] This PR is not tested :(
| https://api.github.com/repos/ray-project/ray/pulls/16751 | 2021-06-29T18:43:52Z | 2021-06-30T03:16:17Z | 2021-06-30T03:16:17Z | 2021-06-30T03:16:17Z | 1,819 | ray-project/ray | 19,405 |
Don't set all session cookies on response.cookies | diff --git a/requests/sessions.py b/requests/sessions.py
index f37d009d14..eb6b1eb616 100644
--- a/requests/sessions.py
+++ b/requests/sessions.py
@@ -160,8 +160,6 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,
i += 1
yield resp
- resp.cookies = self.cookies.copy()
-
class Session(SessionRedirectMixin):
"""A Requests session.
| This prevents all the session cookies from being set in response.cookies. I believe the old behavior was a workaround due to how session cookies were being updated before #1290
After this, response.cookies will match up with the set-cookies header for the response.
As discussed here: https://botbot.me/freenode/python-requests/msg/2568299/
| https://api.github.com/repos/psf/requests/pulls/1291 | 2013-04-05T03:37:35Z | 2013-04-05T03:41:52Z | 2013-04-05T03:41:52Z | 2021-09-08T20:01:10Z | 110 | psf/requests | 32,855 |
Add StreamingLLM for llamacpp & llamacpp_HF (2nd attempt) | diff --git a/modules/cache_utils.py b/modules/cache_utils.py
new file mode 100644
index 0000000000..3a200d8e69
--- /dev/null
+++ b/modules/cache_utils.py
@@ -0,0 +1,108 @@
+import torch
+
+from modules import shared
+from modules.logging_colors import logger
+
+
+def process_llamacpp_cache(model, new_sequence, past_sequence):
+ i1, i2, j1, j2 = find_longest_common_substring_indices(past_sequence, new_sequence)
+ overlap_length = i2 - i1 + 1
+
+ # Do StreamingLLM if i1 > 0 (ie the longest common subsequence is not a prefix)
+ # and the overlap length is sufficiently long.
+ if i1 > 0 and overlap_length > 0.2 * len(new_sequence):
+
+ new_sequence = torch.tensor(new_sequence)
+ past_sequence = torch.tensor(past_sequence)
+
+ prefix_length = find_prefix_length(past_sequence[:i1], new_sequence[:j1])
+ sink_length = prefix_length
+ if sink_length < shared.args.attention_sink_size:
+ sink_length = shared.args.attention_sink_size
+
+ removed_length = i1 - sink_length
+
+ matching_prefix = past_sequence[:prefix_length]
+ removed_chunk = past_sequence[sink_length:i1]
+ overlapping_sequence = new_sequence[j1:j2 + 1]
+ added_chunk = new_sequence[j2 + 1:]
+
+ # print(past_sequence)
+ # print(new_sequence)
+
+ print()
+ print('MATCHING PREFIX=', repr(shared.tokenizer.decode(matching_prefix)))
+ print('ADDED CHUNK=', repr(shared.tokenizer.decode(added_chunk)))
+ print('REMOVED CHUNK=', repr(shared.tokenizer.decode(removed_chunk)))
+ print()
+
+ # Remove interval [sink_length, sink_length + removed_length) from the context
+ # Subtract removed_length from model.n_tokens
+ model._ctx.kv_cache_seq_rm(0, sink_length, sink_length + removed_length)
+ model._ctx.kv_cache_seq_shift(0, sink_length + removed_length, -1, -removed_length)
+
+ new_sequence = new_sequence.tolist()
+ model.input_ids[:j2 + 1] = new_sequence[:j2 + 1]
+ model.n_tokens = j2 + 1
+
+ return new_sequence[:j2 + 1]
+ else:
+ return past_sequence
+
+
+def find_prefix_length(past_seq, seq_tensor):
+ '''
+ Given two torch tensors, finds the length of the longest
+ common prefix between the two.
+ '''
+ min_length = min(past_seq.shape[0], seq_tensor.shape[0])
+ indices = torch.nonzero(~torch.eq(past_seq[:min_length], seq_tensor[:min_length]))
+ if len(indices) > 0:
+ prefix_length = indices[0].item()
+ else:
+ prefix_length = min_length
+
+ return prefix_length
+
+
+def find_longest_common_substring_indices(list1, list2):
+ '''
+ Given two lists, solves the Longest Common Substring problem.
+
+ It returns the indices where the substring starts and ends in
+ s1 and s2.
+
+ Example:
+
+ ir, jr, ir2, jr2 = find_longest_common_substring_indices(s1, s2)
+ print(s1[ir:jr + 1])
+ print(s2[ir2:jr2 + 1])
+
+ Adapted from
+ https://rosettacode.org/wiki/Longest_common_substring#Python
+ '''
+
+ len_list1, len_list2 = len(list1), len(list2)
+ start_index_list1, end_index_list1 = 0, -1
+ start_index_list2, end_index_list2 = 0, -1
+
+ for index1 in range(len_list1):
+ try:
+ index2 = list2.index(list1[index1])
+ except ValueError:
+ continue
+ while index2 >= 0:
+ temp_index1, temp_index2 = index1, index2
+ while temp_index1 < len_list1 and temp_index2 < len_list2 and list2[temp_index2] == list1[temp_index1]:
+ if temp_index1 - index1 >= end_index_list1 - start_index_list1:
+ start_index_list1, end_index_list1 = index1, temp_index1
+ start_index_list2, end_index_list2 = index2, temp_index2
+
+ temp_index1 += 1
+ temp_index2 += 1
+ try:
+ index2 = list2.index(list1[index1], index2 + 1)
+ except ValueError:
+ break
+
+ return start_index_list1, end_index_list1, start_index_list2, end_index_list2
diff --git a/modules/llama_cpp_python_hijack.py b/modules/llama_cpp_python_hijack.py
index 9bb38512e5..96de839e01 100644
--- a/modules/llama_cpp_python_hijack.py
+++ b/modules/llama_cpp_python_hijack.py
@@ -2,6 +2,9 @@
from tqdm import tqdm
+from modules import shared
+from modules.cache_utils import process_llamacpp_cache
+
try:
import llama_cpp
except:
@@ -58,6 +61,25 @@ def eval_with_progress(self, tokens: Sequence[int]):
self.n_tokens += n_tokens
+def monkey_patch_generate(lib):
+
+ def my_generate(self, *args, **kwargs):
+
+ if shared.args.streaming_llm:
+ new_sequence = args[0]
+ past_sequence = self._input_ids
+
+ # Do the cache trimming for StreamingLLM
+ process_llamacpp_cache(self, new_sequence, past_sequence)
+
+ for output in self.original_generate(*args, **kwargs):
+ yield output
+
+ lib.Llama.original_generate = lib.Llama.generate
+ lib.Llama.generate = my_generate
+
+
for lib in [llama_cpp, llama_cpp_cuda, llama_cpp_cuda_tensorcores]:
if lib is not None:
lib.Llama.eval = eval_with_progress
+ monkey_patch_generate(lib)
diff --git a/modules/loaders.py b/modules/loaders.py
index 330f290389..f1c44a903c 100644
--- a/modules/loaders.py
+++ b/modules/loaders.py
@@ -46,6 +46,8 @@
'no_offload_kqv',
'row_split',
'tensorcores',
+ 'streaming_llm',
+ 'attention_sink_size',
],
'llamacpp_HF': [
'n_ctx',
@@ -69,6 +71,8 @@
'no_offload_kqv',
'row_split',
'tensorcores',
+ 'streaming_llm',
+ 'attention_sink_size',
'llamacpp_HF_info',
],
'ExLlamav2_HF': [
diff --git a/modules/shared.py b/modules/shared.py
index 10a70001cc..8758cee1ca 100644
--- a/modules/shared.py
+++ b/modules/shared.py
@@ -130,6 +130,8 @@
group.add_argument('--no_offload_kqv', action='store_true', help='Do not offload the K, Q, V to the GPU. This saves VRAM but reduces the performance.')
group.add_argument('--cache-capacity', type=str, help='Maximum cache capacity (llama-cpp-python). Examples: 2000MiB, 2GiB. When provided without units, bytes will be assumed.')
group.add_argument('--row_split', action='store_true', help='Split the model by rows across GPUs. This may improve multi-gpu performance.')
+group.add_argument('--streaming-llm', action='store_true', help='Activates StreamingLLM, which prevents the prompt from ever being reevaluated when old chat messages are removed due to the context length for the model being reached.')
+group.add_argument('--attention-sink-size', type=int, default=5, help='Minimum attention sink length from StreamingLLM.')
# ExLlamaV2
group = parser.add_argument_group('ExLlamaV2')
diff --git a/modules/text_generation.py b/modules/text_generation.py
index 227d1822d1..dc9c63eaf1 100644
--- a/modules/text_generation.py
+++ b/modules/text_generation.py
@@ -13,6 +13,7 @@
from transformers import LogitsProcessorList, is_torch_xpu_available
import modules.shared as shared
+from modules.cache_utils import process_llamacpp_cache
from modules.callbacks import (
Iteratorize,
Stream,
@@ -364,6 +365,12 @@ def generate_reply_HF(question, original_question, seed, state, stopping_strings
print(decode(input_ids[0], skip_special_tokens=False))
print()
+ # Handle StreamingLLM for llamacpp_HF
+ if shared.model.__class__.__name__ == 'LlamacppHF' and shared.args.streaming_llm:
+ tmp = process_llamacpp_cache(shared.model.model, input_ids[-1].tolist(), shared.model.model._input_ids)
+ shared.model.past_seq = torch.tensor(tmp)
+ shared.model.save_cache()
+
t0 = time.time()
try:
if not is_chat and not shared.is_seq2seq:
diff --git a/modules/ui.py b/modules/ui.py
index 6e1b12b0bf..4a03f8432c 100644
--- a/modules/ui.py
+++ b/modules/ui.py
@@ -97,6 +97,8 @@ def list_model_elements():
'no_offload_kqv',
'row_split',
'tensorcores',
+ 'streaming_llm',
+ 'attention_sink_size',
'hqq_backend',
]
if is_torch_xpu_available():
diff --git a/modules/ui_model_menu.py b/modules/ui_model_menu.py
index c29db7d0d9..e3b0e883f3 100644
--- a/modules/ui_model_menu.py
+++ b/modules/ui_model_menu.py
@@ -117,6 +117,8 @@ def create_ui():
shared.gradio['use_flash_attention_2'] = gr.Checkbox(label="use_flash_attention_2", value=shared.args.use_flash_attention_2, info='Set use_flash_attention_2=True while loading the model.')
shared.gradio['auto_devices'] = gr.Checkbox(label="auto-devices", value=shared.args.auto_devices)
shared.gradio['tensorcores'] = gr.Checkbox(label="tensorcores", value=shared.args.tensorcores, info='NVIDIA only: use llama-cpp-python compiled with tensor cores support. This increases performance on RTX cards.')
+ shared.gradio['streaming_llm'] = gr.Checkbox(label="streaming_llm", value=shared.args.streaming_llm, info='(experimental) Activate StreamingLLM to avoid re-evaluating the entire prompt when old messages are removed.')
+ shared.gradio['attention_sink_size'] = gr.Number(label="attention_sink_size", value=shared.args.attention_sink_size)
shared.gradio['cpu'] = gr.Checkbox(label="cpu", value=shared.args.cpu, info='llama.cpp: Use llama-cpp-python compiled without GPU acceleration. Transformers: use PyTorch in CPU mode.')
shared.gradio['row_split'] = gr.Checkbox(label="row_split", value=shared.args.row_split, info='Split the model by rows across GPUs. This may improve multi-gpu performance.')
shared.gradio['no_offload_kqv'] = gr.Checkbox(label="no_offload_kqv", value=shared.args.no_offload_kqv, info='Do not offload the K, Q, V to the GPU. This saves VRAM but reduces the performance.')
| Cleaned-up version of https://github.com/oobabooga/text-generation-webui/pull/4761. It seems to be working reliably for both llamacpp and llamacpp_HF now.
### Description
When active, this prevents the prompt from being re-evaluated once an old chat message is removed, thus allowing you to talk to the model indefinitely.
### Usage
`--streaming-llm` or check the box below before loading the model.

| https://api.github.com/repos/oobabooga/text-generation-webui/pulls/5669 | 2024-03-09T03:14:54Z | 2024-03-09T03:25:33Z | 2024-03-09T03:25:33Z | 2024-04-09T09:36:35Z | 2,647 | oobabooga/text-generation-webui | 26,335 |
Base output path off data path | diff --git a/modules/paths_internal.py b/modules/paths_internal.py
index 89131a54fa1..b86ecd7f192 100644
--- a/modules/paths_internal.py
+++ b/modules/paths_internal.py
@@ -28,5 +28,6 @@
extensions_dir = os.path.join(data_path, "extensions")
extensions_builtin_dir = os.path.join(script_path, "extensions-builtin")
config_states_dir = os.path.join(script_path, "config_states")
+default_output_dir = os.path.join(data_path, "output")
roboto_ttf_file = os.path.join(modules_path, 'Roboto-Regular.ttf')
diff --git a/modules/shared_options.py b/modules/shared_options.py
index fa542ba8cd6..752a4f1259a 100644
--- a/modules/shared_options.py
+++ b/modules/shared_options.py
@@ -1,7 +1,8 @@
+import os
import gradio as gr
-from modules import localization, ui_components, shared_items, shared, interrogate, shared_gradio_themes
-from modules.paths_internal import models_path, script_path, data_path, sd_configs_path, sd_default_config, sd_model_file, default_sd_model_file, extensions_dir, extensions_builtin_dir # noqa: F401
+from modules import localization, ui_components, shared_items, shared, interrogate, shared_gradio_themes, util
+from modules.paths_internal import models_path, script_path, data_path, sd_configs_path, sd_default_config, sd_model_file, default_sd_model_file, extensions_dir, extensions_builtin_dir, default_output_dir # noqa: F401
from modules.shared_cmd_options import cmd_opts
from modules.options import options_section, OptionInfo, OptionHTML, categories
@@ -74,14 +75,14 @@
options_templates.update(options_section(('saving-paths', "Paths for saving", "saving"), {
"outdir_samples": OptionInfo("", "Output directory for images; if empty, defaults to three directories below", component_args=hide_dirs),
- "outdir_txt2img_samples": OptionInfo("outputs/txt2img-images", 'Output directory for txt2img images', component_args=hide_dirs),
- "outdir_img2img_samples": OptionInfo("outputs/img2img-images", 'Output directory for img2img images', component_args=hide_dirs),
- "outdir_extras_samples": OptionInfo("outputs/extras-images", 'Output directory for images from extras tab', component_args=hide_dirs),
+ "outdir_txt2img_samples": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'txt2img-images')), 'Output directory for txt2img images', component_args=hide_dirs),
+ "outdir_img2img_samples": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'img2img-images')), 'Output directory for img2img images', component_args=hide_dirs),
+ "outdir_extras_samples": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'extras-images')), 'Output directory for images from extras tab', component_args=hide_dirs),
"outdir_grids": OptionInfo("", "Output directory for grids; if empty, defaults to two directories below", component_args=hide_dirs),
- "outdir_txt2img_grids": OptionInfo("outputs/txt2img-grids", 'Output directory for txt2img grids', component_args=hide_dirs),
- "outdir_img2img_grids": OptionInfo("outputs/img2img-grids", 'Output directory for img2img grids', component_args=hide_dirs),
- "outdir_save": OptionInfo("log/images", "Directory for saving images using the Save button", component_args=hide_dirs),
- "outdir_init_images": OptionInfo("outputs/init-images", "Directory for saving init images when using img2img", component_args=hide_dirs),
+ "outdir_txt2img_grids": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'txt2img-grids')), 'Output directory for txt2img grids', component_args=hide_dirs),
+ "outdir_img2img_grids": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'img2img-grids')), 'Output directory for img2img grids', component_args=hide_dirs),
+ "outdir_save": OptionInfo(util.truncate_path(os.path.join(data_path, 'log', 'images')), "Directory for saving images using the Save button", component_args=hide_dirs),
+ "outdir_init_images": OptionInfo(util.truncate_path(os.path.join(default_output_dir, 'init-images')), "Directory for saving init images when using img2img", component_args=hide_dirs),
}))
options_templates.update(options_section(('saving-to-dirs', "Saving to a directory", "saving"), {
diff --git a/modules/ui_gradio_extensions.py b/modules/ui_gradio_extensions.py
index 0d368f8b2c4..a86c368ef70 100644
--- a/modules/ui_gradio_extensions.py
+++ b/modules/ui_gradio_extensions.py
@@ -1,17 +1,12 @@
import os
import gradio as gr
-from modules import localization, shared, scripts
-from modules.paths import script_path, data_path, cwd
+from modules import localization, shared, scripts, util
+from modules.paths import script_path, data_path
def webpath(fn):
- if fn.startswith(cwd):
- web_path = os.path.relpath(fn, cwd)
- else:
- web_path = os.path.abspath(fn)
-
- return f'file={web_path}?{os.path.getmtime(fn)}'
+ return f'file={util.truncate_path(fn)}?{os.path.getmtime(fn)}'
def javascript_html():
diff --git a/modules/util.py b/modules/util.py
index 60afc0670c7..4861bcb0861 100644
--- a/modules/util.py
+++ b/modules/util.py
@@ -2,7 +2,7 @@
import re
from modules import shared
-from modules.paths_internal import script_path
+from modules.paths_internal import script_path, cwd
def natural_sort_key(s, regex=re.compile('([0-9]+)')):
@@ -56,3 +56,13 @@ def ldm_print(*args, **kwargs):
return
print(*args, **kwargs)
+
+
+def truncate_path(target_path, base_path=cwd):
+ abs_target, abs_base = os.path.abspath(target_path), os.path.abspath(base_path)
+ try:
+ if os.path.commonpath([abs_target, abs_base]) == abs_base:
+ return os.path.relpath(abs_target, abs_base)
+ except ValueError:
+ pass
+ return abs_target
| ## Description
alternative implementation of https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14443 Added shared.cmd_opts.data_dir prefix to "outputs" and "log" paths.
achieve the same thing with minor differences being
1. the default path is truncated if it's a child's of CWD
this has the advantage of making existing config.json more usable if webui is moved
2. using the path separator of the respective of OS
other minor change
1. create a path truncate utility function `truncate_path()`
2. create a new paths_internal var `default_output_dir` (I guess this can be reused by extensions)
3. also use this utility function for `def webpath(fn)` simplifying it
(I know I probably shouldn't have bundle this one in this PR)
## Implications
this change could potentially have a minor impact on existing users
if the user decides to create a new configuration file and happens to be using --data-dir
but they also wish for some reason the output to be in the webui root
these user will have to set the output to webui root manually
but for existing users that are using existing configuration file there will be no impact, as this only changes the default output path not the current path
## 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/14446 | 2023-12-27T21:48:47Z | 2023-12-30T11:45:28Z | 2023-12-30T11:45:28Z | 2023-12-30T11:45:32Z | 1,436 | AUTOMATIC1111/stable-diffusion-webui | 40,123 |
TYP: loosen types of to_markdown, align to docs | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b7974e5764100..e23c735fe41df 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -18,7 +18,6 @@
import itertools
from textwrap import dedent
from typing import (
- IO,
TYPE_CHECKING,
Any,
Callable,
@@ -2717,7 +2716,7 @@ def to_feather(self, path: FilePath | WriteBuffer[bytes], **kwargs) -> None:
)
def to_markdown(
self,
- buf: IO[str] | str | None = None,
+ buf: FilePath | WriteBuffer[str] | None = None,
mode: str = "wt",
index: bool = True,
storage_options: StorageOptions = None,
| Docs already allowed pathlib.Path objects and such
code runs, but failed mypy typechecks. This fixes it.
- [x] closes #46211
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46212 | 2022-03-03T15:51:07Z | 2022-03-03T18:46:16Z | 2022-03-03T18:46:15Z | 2022-03-03T18:46:19Z | 189 | pandas-dev/pandas | 44,975 |
Bump word-wrap from 1.2.3 to 1.2.5 in /component-lib | diff --git a/component-lib/yarn.lock b/component-lib/yarn.lock
index 74bde065fc7d..cb080aa01d0f 100644
--- a/component-lib/yarn.lock
+++ b/component-lib/yarn.lock
@@ -4103,9 +4103,9 @@ which@^2.0.1:
isexe "^2.0.0"
word-wrap@~1.2.3:
- version "1.2.3"
- resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c"
- integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==
+ version "1.2.5"
+ resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.5.tgz#d2c45c6dd4fbce621a66f136cbe328afd0410b34"
+ integrity sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==
wordwrapjs@^4.0.0:
version "4.0.1"
| Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.5.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/jonschlinkert/word-wrap/releases">word-wrap's releases</a>.</em></p>
<blockquote>
<h2>1.2.5</h2>
<p><strong>Changes</strong>:</p>
<p>Reverts default value for <code>options.indent</code> to two spaces <code>' '</code>.</p>
<p><strong>Full Changelog</strong>: <a href="https://github.com/jonschlinkert/word-wrap/compare/1.2.4...1.2.5">https://github.com/jonschlinkert/word-wrap/compare/1.2.4...1.2.5</a></p>
<h2>1.2.4</h2>
<h2>What's Changed</h2>
<ul>
<li>Remove default indent by <a href="https://github.com/mohd-akram"><code>@mohd-akram</code></a> in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/24">jonschlinkert/word-wrap#24</a></li>
<li>🔒fix: CVE 2023 26115 (2) by <a href="https://github.com/OlafConijn"><code>@OlafConijn</code></a> in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/41">jonschlinkert/word-wrap#41</a></li>
<li>:lock: fix: CVE-2023-26115 by <a href="https://github.com/aashutoshrathi"><code>@aashutoshrathi</code></a> in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/33">jonschlinkert/word-wrap#33</a></li>
<li>chore: publish workflow by <a href="https://github.com/OlafConijn"><code>@OlafConijn</code></a> in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/42">jonschlinkert/word-wrap#42</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/mohd-akram"><code>@mohd-akram</code></a> made their first contribution in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/24">jonschlinkert/word-wrap#24</a></li>
<li><a href="https://github.com/OlafConijn"><code>@OlafConijn</code></a> made their first contribution in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/41">jonschlinkert/word-wrap#41</a></li>
<li><a href="https://github.com/aashutoshrathi"><code>@aashutoshrathi</code></a> made their first contribution in <a href="https://redirect.github.com/jonschlinkert/word-wrap/pull/33">jonschlinkert/word-wrap#33</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4">https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/207044ebda1dd3809d15b6000a48409266536771"><code>207044e</code></a> 1.2.5</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/98943154855b0dd79b707462b9202614990c7f61"><code>9894315</code></a> revert default indent</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/f64b188c7261d26b99e1e2075d6b12f21798e83a"><code>f64b188</code></a> run verb to generate README</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/03ea08256ba0c8e8b02b1b304f0f5bd2b1863207"><code>03ea082</code></a> Merge pull request <a href="https://redirect.github.com/jonschlinkert/word-wrap/issues/42">#42</a> from jonschlinkert/chore/publish-workflow</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/420dce9a2412b21881202b73a3c34f0edc53cb2e"><code>420dce9</code></a> Merge pull request <a href="https://redirect.github.com/jonschlinkert/word-wrap/issues/41">#41</a> from jonschlinkert/fix/CVE-2023-26115-2</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/bfa694edf55bb84ff84512f13da6d68bf7593f06"><code>bfa694e</code></a> Update .github/workflows/publish.yml</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/ace0b3c78f81aaf43040bab3bc91d3c5546d3fd2"><code>ace0b3c</code></a> chore: bump version to 1.2.4</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/6fd727594676f3e1b196b08a320908bec2f4ca02"><code>6fd7275</code></a> chore: add publish workflow</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/30d6daf60fce429f5f559252fa86ee78200652c4"><code>30d6daf</code></a> chore: fix test</li>
<li><a href="https://github.com/jonschlinkert/word-wrap/commit/655929cabea6299dddf3b4a21fc3713fca701b48"><code>655929c</code></a> chore: remove package-lock</li>
<li>Additional commits viewable in <a href="https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.5">compare view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot 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)
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/streamlit/streamlit/network/alerts).
</details> | https://api.github.com/repos/streamlit/streamlit/pulls/7066 | 2023-07-24T21:12:45Z | 2023-07-24T21:41:40Z | 2023-07-24T21:41:40Z | 2023-07-24T21:41:43Z | 377 | streamlit/streamlit | 22,487 |
Subaru: Global gen1 experimental longitudinal | diff --git a/selfdrive/car/subaru/carcontroller.py b/selfdrive/car/subaru/carcontroller.py
index b37c88797a9367..80634bf2610666 100644
--- a/selfdrive/car/subaru/carcontroller.py
+++ b/selfdrive/car/subaru/carcontroller.py
@@ -1,3 +1,4 @@
+from common.numpy_fast import clip, interp
from opendbc.can.packer import CANPacker
from selfdrive.car import apply_driver_steer_torque_limits
from selfdrive.car.subaru import subarucan
@@ -42,6 +43,21 @@ def update(self, CC, CS, now_nanos):
self.apply_steer_last = apply_steer
+ # *** longitudinal ***
+
+ if CC.longActive:
+ apply_throttle = int(round(interp(actuators.accel, CarControllerParams.THROTTLE_LOOKUP_BP, CarControllerParams.THROTTLE_LOOKUP_V)))
+ apply_rpm = int(round(interp(actuators.accel, CarControllerParams.RPM_LOOKUP_BP, CarControllerParams.RPM_LOOKUP_V)))
+ apply_brake = int(round(interp(actuators.accel, CarControllerParams.BRAKE_LOOKUP_BP, CarControllerParams.BRAKE_LOOKUP_V)))
+
+ # limit min and max values
+ cruise_throttle = clip(apply_throttle, CarControllerParams.THROTTLE_MIN, CarControllerParams.THROTTLE_MAX)
+ cruise_rpm = clip(apply_rpm, CarControllerParams.RPM_MIN, CarControllerParams.RPM_MAX)
+ cruise_brake = clip(apply_brake, CarControllerParams.BRAKE_MIN, CarControllerParams.BRAKE_MAX)
+ else:
+ cruise_throttle = CarControllerParams.THROTTLE_INACTIVE
+ cruise_rpm = CarControllerParams.RPM_INACTIVE
+ cruise_brake = CarControllerParams.BRAKE_MIN
# *** alerts and pcm cancel ***
if self.CP.carFingerprint in PREGLOBAL_CARS:
@@ -64,13 +80,9 @@ def update(self, CC, CS, now_nanos):
can_sends.append(subarucan.create_preglobal_es_distance(self.packer, cruise_button, CS.es_distance_msg))
else:
- if pcm_cancel_cmd and (self.frame - self.last_cancel_frame) > 0.2:
- bus = CanBus.alt if self.CP.carFingerprint in GLOBAL_GEN2 else CanBus.main
- can_sends.append(subarucan.create_es_distance(self.packer, CS.es_distance_msg, bus, pcm_cancel_cmd))
- self.last_cancel_frame = self.frame
-
if self.frame % 10 == 0:
- can_sends.append(subarucan.create_es_dashstatus(self.packer, CS.es_dashstatus_msg))
+ can_sends.append(subarucan.create_es_dashstatus(self.packer, CS.es_dashstatus_msg, CC.enabled, self.CP.openpilotLongitudinalControl,
+ CC.longActive, hud_control.leadVisible))
can_sends.append(subarucan.create_es_lkas_state(self.packer, CS.es_lkas_state_msg, CC.enabled, hud_control.visualAlert,
hud_control.leftLaneVisible, hud_control.rightLaneVisible,
@@ -79,6 +91,20 @@ def update(self, CC, CS, now_nanos):
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
can_sends.append(subarucan.create_es_infotainment(self.packer, CS.es_infotainment_msg, hud_control.visualAlert))
+ if self.CP.openpilotLongitudinalControl:
+ if self.frame % 5 == 0:
+ can_sends.append(subarucan.create_es_status(self.packer, CS.es_status_msg, self.CP.openpilotLongitudinalControl, CC.longActive, cruise_rpm))
+
+ can_sends.append(subarucan.create_es_brake(self.packer, CS.es_brake_msg, CC.enabled, cruise_brake))
+
+ can_sends.append(subarucan.create_es_distance(self.packer, CS.es_distance_msg, 0, pcm_cancel_cmd,
+ self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle))
+ else:
+ if pcm_cancel_cmd and (self.frame - self.last_cancel_frame) > 0.2:
+ bus = CanBus.alt if self.CP.carFingerprint in GLOBAL_GEN2 else CanBus.main
+ can_sends.append(subarucan.create_es_distance(self.packer, CS.es_distance_msg, bus, pcm_cancel_cmd))
+ self.last_cancel_frame = self.frame
+
new_actuators = actuators.copy()
new_actuators.steer = self.apply_steer_last / self.p.STEER_MAX
new_actuators.steerOutputCan = self.apply_steer_last
diff --git a/selfdrive/car/subaru/carstate.py b/selfdrive/car/subaru/carstate.py
index 6e0bef2068fffc..84c1285af19682 100644
--- a/selfdrive/car/subaru/carstate.py
+++ b/selfdrive/car/subaru/carstate.py
@@ -91,6 +91,12 @@ def update(self, cp, cp_cam, cp_body):
ret.stockAeb = (cp_es_distance.vl["ES_Brake"]["AEB_Status"] == 8) and \
(cp_es_distance.vl["ES_Brake"]["Brake_Pressure"] != 0)
self.es_lkas_state_msg = copy.copy(cp_cam.vl["ES_LKAS_State"])
+ cp_es_brake = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp_cam
+ self.es_brake_msg = copy.copy(cp_es_brake.vl["ES_Brake"])
+ cp_es_status = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp_cam
+ self.es_status_msg = copy.copy(cp_es_status.vl["ES_Status"])
+ self.cruise_control_msg = copy.copy(cp_cruise.vl["CruiseControl"])
+ self.brake_status_msg = copy.copy(cp_brakes.vl["Brake_Status"])
self.es_distance_msg = copy.copy(cp_es_distance.vl["ES_Distance"])
self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"])
@@ -114,6 +120,8 @@ def get_common_global_es_messages():
messages = [
("ES_Brake", 20),
("ES_Distance", 20),
+ ("ES_Status", 20),
+ ("ES_Brake", 20),
]
return messages
diff --git a/selfdrive/car/subaru/interface.py b/selfdrive/car/subaru/interface.py
index b01d1eb3bc642e..7b532a1b22aae9 100644
--- a/selfdrive/car/subaru/interface.py
+++ b/selfdrive/car/subaru/interface.py
@@ -107,6 +107,18 @@ def _get_params(ret, candidate, fingerprint, car_fw, experimental_long, docs):
else:
raise ValueError(f"unknown car: {candidate}")
+ #ret.experimentalLongitudinalAvailable = candidate not in (GLOBAL_GEN2 | PREGLOBAL_CARS | LKAS_ANGLE)
+ ret.openpilotLongitudinalControl = experimental_long and ret.experimentalLongitudinalAvailable
+
+ if ret.openpilotLongitudinalControl:
+ ret.longitudinalTuning.kpBP = [0., 5., 35.]
+ ret.longitudinalTuning.kpV = [0.8, 1.0, 1.5]
+ ret.longitudinalTuning.kiBP = [0., 35.]
+ ret.longitudinalTuning.kiV = [0.54, 0.36]
+
+ ret.stoppingControl = True
+ ret.safetyConfigs[0].safetyParam |= Panda.FLAG_SUBARU_LONG
+
return ret
# returns a car.CarState
diff --git a/selfdrive/car/subaru/subarucan.py b/selfdrive/car/subaru/subarucan.py
index 39658e958a2d01..df2718c76456dc 100644
--- a/selfdrive/car/subaru/subarucan.py
+++ b/selfdrive/car/subaru/subarucan.py
@@ -16,8 +16,7 @@ def create_steering_control(packer, apply_steer, steer_req):
def create_steering_status(packer):
return packer.make_can_msg("ES_LKAS_State", 0, {})
-
-def create_es_distance(packer, es_distance_msg, bus, pcm_cancel_cmd):
+def create_es_distance(packer, es_distance_msg, bus, pcm_cancel_cmd, long_enabled = False, brake_cmd = False, cruise_throttle = 0):
values = {s: es_distance_msg[s] for s in [
"CHECKSUM",
"COUNTER",
@@ -41,9 +40,20 @@ def create_es_distance(packer, es_distance_msg, bus, pcm_cancel_cmd):
"Signal6",
]}
values["COUNTER"] = (values["COUNTER"] + 1) % 0x10
+
+ if long_enabled:
+ values["Cruise_Throttle"] = cruise_throttle
+
+ # Do not disable openpilot on Eyesight Soft Disable, if openpilot is controlling long
+ values["Cruise_Soft_Disable"] = 0
+
+ if brake_cmd:
+ values["Cruise_Brake_Active"] = 1
+
if pcm_cancel_cmd:
values["Cruise_Cancel"] = 1
values["Cruise_Throttle"] = 1818 # inactive throttle
+
return packer.make_can_msg("ES_Distance", bus, values)
@@ -106,8 +116,7 @@ def create_es_lkas_state(packer, es_lkas_state_msg, enabled, visual_alert, left_
return packer.make_can_msg("ES_LKAS_State", CanBus.main, values)
-
-def create_es_dashstatus(packer, dashstatus_msg):
+def create_es_dashstatus(packer, dashstatus_msg, enabled, long_enabled, long_active, lead_visible):
values = {s: dashstatus_msg[s] for s in [
"CHECKSUM",
"COUNTER",
@@ -138,12 +147,68 @@ def create_es_dashstatus(packer, dashstatus_msg):
"Cruise_State",
]}
+ if enabled and long_active:
+ values["Cruise_State"] = 0
+ values["Cruise_Activated"] = 1
+ values["Cruise_Disengaged"] = 0
+ values["Car_Follow"] = int(lead_visible)
+
+ if long_enabled:
+ values["PCB_Off"] = 1 # AEB is not presevered, so show the PCB_Off on dash
+
# Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts
if values["LKAS_State_Msg"] in (2, 3):
values["LKAS_State_Msg"] = 0
return packer.make_can_msg("ES_DashStatus", CanBus.main, values)
+def create_es_brake(packer, es_brake_msg, enabled, brake_value):
+ values = {s: es_brake_msg[s] for s in [
+ "CHECKSUM",
+ "COUNTER",
+ "Signal1",
+ "Brake_Pressure",
+ "AEB_Status",
+ "Cruise_Brake_Lights",
+ "Cruise_Brake_Fault",
+ "Cruise_Brake_Active",
+ "Cruise_Activated",
+ "Signal3",
+ ]}
+
+ if enabled:
+ values["Cruise_Activated"] = 1
+
+ values["Brake_Pressure"] = brake_value
+
+ if brake_value > 0:
+ values["Cruise_Brake_Active"] = 1
+ values["Cruise_Brake_Lights"] = 1 if brake_value >= 70 else 0
+
+ return packer.make_can_msg("ES_Brake", CanBus.main, values)
+
+def create_es_status(packer, es_status_msg, long_enabled, long_active, cruise_rpm):
+ values = {s: es_status_msg[s] for s in [
+ "CHECKSUM",
+ "COUNTER",
+ "Signal1",
+ "Cruise_Fault",
+ "Cruise_RPM",
+ "Signal2",
+ "Cruise_Activated",
+ "Brake_Lights",
+ "Cruise_Hold",
+ "Signal3",
+ ]}
+
+ if long_enabled:
+ values["Cruise_RPM"] = cruise_rpm
+
+ if long_active:
+ values["Cruise_Activated"] = 1
+
+ return packer.make_can_msg("ES_Status", CanBus.main, values)
+
def create_es_infotainment(packer, es_infotainment_msg, visual_alert):
# Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts
diff --git a/selfdrive/car/subaru/values.py b/selfdrive/car/subaru/values.py
index ebeb5ea2a0b252..dc25f31f730959 100644
--- a/selfdrive/car/subaru/values.py
+++ b/selfdrive/car/subaru/values.py
@@ -29,6 +29,29 @@ def __init__(self, CP):
else:
self.STEER_MAX = 2047
+ THROTTLE_MIN = 808
+ THROTTLE_MAX = 3400
+
+ THROTTLE_INACTIVE = 1818 # corresponds to zero acceleration
+ THROTTLE_ENGINE_BRAKE = 808 # while braking, eyesight sets throttle to this, probably for engine braking
+
+ BRAKE_MIN = 0
+ BRAKE_MAX = 600 # about -3.5m/s2 from testing
+
+ RPM_MIN = 0
+ RPM_MAX = 2400
+
+ RPM_INACTIVE = 600 # a good base rpm for zero acceleration
+
+ THROTTLE_LOOKUP_BP = [0, 1]
+ THROTTLE_LOOKUP_V = [THROTTLE_INACTIVE, THROTTLE_MAX]
+
+ RPM_LOOKUP_BP = [0, 1]
+ RPM_LOOKUP_V = [RPM_INACTIVE, RPM_MAX]
+
+ BRAKE_LOOKUP_BP = [-1, 0]
+ BRAKE_LOOKUP_V = [BRAKE_MAX, BRAKE_MIN]
+
class SubaruFlags(IntFlag):
SEND_INFOTAINMENT = 1
| - Experimental long for gen1 subarus, gated behind an experimental flag for testing | https://api.github.com/repos/commaai/openpilot/pulls/28872 | 2023-07-11T03:17:00Z | 2023-08-16T19:58:09Z | 2023-08-16T19:58:09Z | 2023-08-16T19:58:10Z | 3,244 | commaai/openpilot | 9,769 |
Fix --ui-debug-mode exit | diff --git a/modules/errors.py b/modules/errors.py
index f6b80dbbde7..da4694f8536 100644
--- a/modules/errors.py
+++ b/modules/errors.py
@@ -12,9 +12,13 @@ def print_error_explanation(message):
print('=' * max_len, file=sys.stderr)
-def display(e: Exception, task):
+def display(e: Exception, task, *, full_traceback=False):
print(f"{task or 'error'}: {type(e).__name__}", file=sys.stderr)
- print(traceback.format_exc(), file=sys.stderr)
+ te = traceback.TracebackException.from_exception(e)
+ if full_traceback:
+ # include frames leading up to the try-catch block
+ te.stack = traceback.StackSummary(traceback.extract_stack()[:-2] + te.stack)
+ print(*te.format(), sep="", file=sys.stderr)
message = str(e)
if "copying a param with shape torch.Size([640, 1024]) from checkpoint, the shape in current model is torch.Size([640, 768])" in message:
diff --git a/modules/sd_models.py b/modules/sd_models.py
index 91b3eb1158f..3e7fc7e32dd 100644
--- a/modules/sd_models.py
+++ b/modules/sd_models.py
@@ -164,6 +164,7 @@ def model_hash(filename):
def select_checkpoint():
+ """Raises `FileNotFoundError` if no checkpoints are found."""
model_checkpoint = shared.opts.sd_model_checkpoint
checkpoint_info = checkpoint_alisases.get(model_checkpoint, None)
@@ -171,14 +172,14 @@ def select_checkpoint():
return checkpoint_info
if len(checkpoints_list) == 0:
- print("No checkpoints found. When searching for checkpoints, looked at:", file=sys.stderr)
+ error_message = "No checkpoints found. When searching for checkpoints, looked at:"
if shared.cmd_opts.ckpt is not None:
- print(f" - file {os.path.abspath(shared.cmd_opts.ckpt)}", file=sys.stderr)
- print(f" - directory {model_path}", file=sys.stderr)
+ error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}"
+ error_message += f"\n - directory {model_path}"
if shared.cmd_opts.ckpt_dir is not None:
- print(f" - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}", file=sys.stderr)
- print("Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations. The program will exit.", file=sys.stderr)
- exit(1)
+ error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}"
+ error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations."
+ raise FileNotFoundError(error_message)
checkpoint_info = next(iter(checkpoints_list.values()))
if model_checkpoint is not None:
@@ -423,7 +424,7 @@ def get_sd_model(self):
try:
load_model()
except Exception as e:
- errors.display(e, "loading stable diffusion model")
+ errors.display(e, "loading stable diffusion model", full_traceback=True)
print("", file=sys.stderr)
print("Stable diffusion model failed to load", file=sys.stderr)
self.sd_model = None
| **Describe what this pull request is trying to achieve.**
Fix for bug #10680 causing `--ui-debug-mode` to cause early program exit. Changes allow the program to start with `--ui-debug-mode` without exiting immediately.
**Additional notes and description of your changes**
* Changed `select_checkpoint()` to raise an error instead of exiting.
* Changed error logging in `get_sd_model()` to display full stack trace, making it easily identifiable if an error is caused by an extension.
**Environment this was tested in**
List the environment you have developed / tested this on. As per the contributing page, changes should be able to work on Windows out of the box.
- OS: Windows
- Browser: N/A
- Graphics card: N/A | https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/10739 | 2023-05-26T19:45:24Z | 2023-05-27T17:02:07Z | 2023-05-27T17:02:07Z | 2023-05-27T17:02:07Z | 758 | AUTOMATIC1111/stable-diffusion-webui | 40,299 |
[keras/utils/dataset_utils.py] Standardise docstring usage of "Default to" | diff --git a/keras/utils/dataset_utils.py b/keras/utils/dataset_utils.py
index 0103cad42c3..35d234d6255 100644
--- a/keras/utils/dataset_utils.py
+++ b/keras/utils/dataset_utils.py
@@ -41,11 +41,11 @@ def split_dataset(
left_size: If float (in the range `[0, 1]`), it signifies
the fraction of the data to pack in the left dataset. If integer, it
signifies the number of samples to pack in the left dataset. If
- `None`, it defaults to the complement to `right_size`.
+ `None`, it uses the complement to `right_size`. Defaults to `None`.
right_size: If float (in the range `[0, 1]`), it signifies
the fraction of the data to pack in the right dataset. If integer, it
signifies the number of samples to pack in the right dataset. If
- `None`, it defaults to the complement to `left_size`.
+ `None`, it uses the complement to `left_size`. Defaults to `None`.
shuffle: Boolean, whether to shuffle the data before splitting it.
seed: A random seed for shuffling.
@@ -130,10 +130,10 @@ def _convert_dataset_to_list(
dataset_type_spec : the type of the dataset
data_size_warning_flag (bool, optional): If set to True, a warning will
be issued if the dataset takes longer than 10 seconds to iterate.
- Defaults to True.
+ Defaults to `True`.
ensure_shape_similarity (bool, optional): If set to True, the shape of
the first sample will be used to validate the shape of rest of the
- samples. Defaults to True.
+ samples. Defaults to `True`.
Returns:
List: A list of tuples/NumPy arrays.
@@ -254,10 +254,10 @@ def _get_next_sample(
dataset_iterator : An `iterator` object.
ensure_shape_similarity (bool, optional): If set to True, the shape of
the first sample will be used to validate the shape of rest of the
- samples. Defaults to True.
+ samples. Defaults to `True`.
data_size_warning_flag (bool, optional): If set to True, a warning will
be issued if the dataset takes longer than 10 seconds to iterate.
- Defaults to True.
+ Defaults to `True`.
start_time (float): the start time of the dataset iteration. this is
used only if `data_size_warning_flag` is set to true.
| This is one of many PRs. Discussion + request to split into multiple PRs @ #17748 | https://api.github.com/repos/keras-team/keras/pulls/17895 | 2023-04-04T22:41:17Z | 2023-04-15T18:04:25Z | 2023-04-15T18:04:25Z | 2023-04-15T18:04:25Z | 578 | keras-team/keras | 47,391 |
changed to old-style .format() calls | diff --git a/plugins/Model_OriginalHighRes/Model.py b/plugins/Model_OriginalHighRes/Model.py
index a40f170c42..1c7150423d 100644
--- a/plugins/Model_OriginalHighRes/Model.py
+++ b/plugins/Model_OriginalHighRes/Model.py
@@ -41,13 +41,12 @@ class Encoders():
REGULAR = 'v2' # high memory consumption encoder
NEW_SLIM = 'v3' # slightly lighter on resources and taining speed is faster
-
+
ENCODER = Encoders.NEW_SLIM
-
-hdf = {'encoderH5': f'encoder_{version_str}{ENCODER}.h5',
- 'decoder_AH5': f'decoder_A_{version_str}{ENCODER}.h5',
- 'decoder_BH5': f'decoder_B_{version_str}{ENCODER}.h5'}
+hdf = {'encoderH5': 'encoder_{version_str}{ENCODER}.h5'.format(**vars()),
+ 'decoder_AH5': 'decoder_A_{version_str}{ENCODER}.h5'.format(**vars()),
+ 'decoder_BH5': 'decoder_B_{version_str}{ENCODER}.h5'.format(**vars())}
class Model():
| Changed weights naming to old-style .format() | https://api.github.com/repos/deepfakes/faceswap/pulls/401 | 2018-05-16T16:05:17Z | 2018-05-16T19:06:02Z | 2018-05-16T19:06:02Z | 2018-05-16T19:06:02Z | 286 | deepfakes/faceswap | 18,846 |
Correcting minor typo | diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md
index 5c162977f..7bb8bd521 100644
--- a/CppCoreGuidelines.md
+++ b/CppCoreGuidelines.md
@@ -4557,7 +4557,7 @@ The alternative is to make two failure states compare equal and any valid state
// ...
};
-// `B`'s comparison accpts conversions for its second operand, but not its first.
+// `B`'s comparison accepts conversions for its second operand, but not its first.
class D :B {
char character;
| "accpt" -> "accept"
| https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/149 | 2015-09-26T04:07:49Z | 2015-09-26T07:45:50Z | 2015-09-26T07:45:50Z | 2015-09-26T07:46:07Z | 141 | isocpp/CppCoreGuidelines | 16,079 |
Revert "add encoding for open" | diff --git a/ppocr/data/imaug/label_ops.py b/ppocr/data/imaug/label_ops.py
index 48f12b96a0..148b093687 100644
--- a/ppocr/data/imaug/label_ops.py
+++ b/ppocr/data/imaug/label_ops.py
@@ -118,7 +118,7 @@ def __init__(self,
self.lower = True
else:
self.character_str = []
- with open(character_dict_path, "rb", encoding="utf-8") as fin:
+ with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
@@ -278,7 +278,7 @@ def __init__(self,
char = line.strip()
self.dict[char] = idx
idx += 1
- with open(class_path, "r", encoding="utf-8") as fin:
+ with open(class_path, "r") as fin:
lines = fin.readlines()
for idx, line in enumerate(lines):
line = line.strip("\n")
@@ -640,7 +640,7 @@ def __init__(self,
self.replace_empty_cell_token = replace_empty_cell_token
dict_character = []
- with open(character_dict_path, "rb", encoding="utf-8") as fin:
+ with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
@@ -1380,7 +1380,7 @@ def __init__(self,
super(SRLabelEncode, self).__init__(max_text_length,
character_dict_path, use_space_char)
self.dic = {}
- with open(character_dict_path, 'r', encoding="utf-8") as fin:
+ with open(character_dict_path, 'r') as fin:
for line in fin.readlines():
line = line.strip()
character, sequence = line.split()
diff --git a/ppocr/data/pubtab_dataset.py b/ppocr/data/pubtab_dataset.py
index c84a7af902..642d3eb196 100644
--- a/ppocr/data/pubtab_dataset.py
+++ b/ppocr/data/pubtab_dataset.py
@@ -59,7 +59,7 @@ def get_image_info_list(self, file_list, ratio_list):
file_list = [file_list]
data_lines = []
for idx, file in enumerate(file_list):
- with open(file, "rb", encoding="utf-8") as f:
+ with open(file, "rb") as f:
lines = f.readlines()
if self.mode == "train" or ratio_list[idx] < 1.0:
random.seed(self.seed)
@@ -112,7 +112,7 @@ def __getitem__(self, idx):
'file_name': file_name
}
- with open(data['img_path'], 'rb', encoding="utf-8") as f:
+ with open(data['img_path'], 'rb') as f:
img = f.read()
data['image'] = img
outs = transform(data, self.ops)
diff --git a/ppocr/data/simple_dataset.py b/ppocr/data/simple_dataset.py
index d17f931fac..044eafe10e 100644
--- a/ppocr/data/simple_dataset.py
+++ b/ppocr/data/simple_dataset.py
@@ -74,7 +74,7 @@ def get_image_info_list(self, file_list, ratio_list):
file_list = [file_list]
data_lines = []
for idx, file in enumerate(file_list):
- with open(file, "rb", encoding="utf-8") as f:
+ with open(file, "rb") as f:
lines = f.readlines()
if self.mode == "train" or ratio_list[idx] < 1.0:
random.seed(self.seed)
@@ -120,7 +120,7 @@ def get_ext_data(self):
data = {'img_path': img_path, 'label': label}
if not os.path.exists(img_path):
continue
- with open(data['img_path'], 'rb', encoding="utf-8") as f:
+ with open(data['img_path'], 'rb') as f:
img = f.read()
data['image'] = img
data = transform(data, load_data_ops)
@@ -146,7 +146,7 @@ def __getitem__(self, idx):
data = {'img_path': img_path, 'label': label}
if not os.path.exists(img_path):
raise Exception("{} does not exist!".format(img_path))
- with open(data['img_path'], 'rb', encoding="utf-8") as f:
+ with open(data['img_path'], 'rb') as f:
img = f.read()
data['image'] = img
data['ext_data'] = self.get_ext_data()
@@ -240,7 +240,7 @@ def __getitem__(self, properties):
data = {'img_path': img_path, 'label': label}
if not os.path.exists(img_path):
raise Exception("{} does not exist!".format(img_path))
- with open(data['img_path'], 'rb', encoding="utf-8") as f:
+ with open(data['img_path'], 'rb') as f:
img = f.read()
data['image'] = img
data['ext_data'] = self.get_ext_data()
diff --git a/ppocr/postprocess/rec_postprocess.py b/ppocr/postprocess/rec_postprocess.py
index 3af3536e35..f64ea1ce7a 100644
--- a/ppocr/postprocess/rec_postprocess.py
+++ b/ppocr/postprocess/rec_postprocess.py
@@ -31,7 +31,7 @@ def __init__(self, character_dict_path=None, use_space_char=False):
self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
dict_character = list(self.character_str)
else:
- with open(character_dict_path, "rb", encoding="utf-8") as fin:
+ with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
diff --git a/ppocr/postprocess/table_postprocess.py b/ppocr/postprocess/table_postprocess.py
index 05e89bb92c..a47061f935 100644
--- a/ppocr/postprocess/table_postprocess.py
+++ b/ppocr/postprocess/table_postprocess.py
@@ -26,7 +26,7 @@ def __init__(self,
merge_no_span_structure=False,
**kwargs):
dict_character = []
- with open(character_dict_path, "rb", encoding="utf-8") as fin:
+ with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
| Reverts PaddlePaddle/PaddleOCR#10769 | https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/10789 | 2023-08-31T07:43:12Z | 2023-08-31T07:43:18Z | 2023-08-31T07:43:18Z | 2024-04-09T11:23:44Z | 1,543 | PaddlePaddle/PaddleOCR | 42,254 |
fix: update incompatible xformers version | diff --git a/launch.py b/launch.py
index 4269f1fcb..f545c39e6 100644
--- a/launch.py
+++ b/launch.py
@@ -42,7 +42,7 @@ def prepare_environment():
if TRY_INSTALL_XFORMERS:
if REINSTALL_ALL or not is_installed("xformers"):
- xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.20')
+ xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.23')
if platform.system() == "Windows":
if platform.python_version().startswith("3.10"):
run_pip(f"install -U -I --no-deps {xformers_package}", "xformers", live=True)
| fixes https://github.com/lllyasviel/Fooocus/issues/2513
```
WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:
PyTorch 2.0.1+cu118 with CUDA 1108 (you have 2.1.0+cu121)
Python 3.10.11 (you have 3.10.9)
```
=> updating from 0.0.20 to 0.0.23 | https://api.github.com/repos/lllyasviel/Fooocus/pulls/2517 | 2024-03-12T21:47:09Z | 2024-03-12T22:13:39Z | 2024-03-12T22:13:39Z | 2024-03-12T22:34:16Z | 185 | lllyasviel/Fooocus | 7,030 |
Remove pytest.importorskip | diff --git a/gym/wrappers/frame_stack.py b/gym/wrappers/frame_stack.py
index c7eb19aaacd..388e1e75de5 100644
--- a/gym/wrappers/frame_stack.py
+++ b/gym/wrappers/frame_stack.py
@@ -178,7 +178,8 @@ def step(self, action):
)
self.frames.append(observation)
return step_api_compatibility(
- (self.observation(), reward, terminated, truncated, info), self.new_step_api
+ (self.observation(None), reward, terminated, truncated, info),
+ self.new_step_api,
)
def reset(self, **kwargs):
diff --git a/tests/testing_env.py b/tests/testing_env.py
index ecac8b7370c..bc03c35be62 100644
--- a/tests/testing_env.py
+++ b/tests/testing_env.py
@@ -24,12 +24,18 @@ def basic_reset_fn(
return self.observation_space.sample()
-def basic_step_fn(self, action: ActType) -> Tuple[ObsType, float, bool, bool, dict]:
- """A basic step function that will pass the environment check using random actions from the observation space."""
+def new_step_fn(self, action: ActType) -> Tuple[ObsType, float, bool, bool, dict]:
+ """A step function that follows the new step api that will pass the environment check using random actions from the observation space."""
return self.observation_space.sample(), 0, False, False, {}
+def old_step_fn(self, action: ActType) -> Tuple[ObsType, float, bool, dict]:
+ """A step function that follows the old step api that will pass the environment check using random actions from the observation space."""
+ return self.observation_space.sample(), 0, False, {}
+
+
def basic_render_fn(self):
+ """Basic render fn that does nothing."""
pass
@@ -42,7 +48,7 @@ def __init__(
action_space: spaces.Space = spaces.Box(0, 1, (1,)),
observation_space: spaces.Space = spaces.Box(0, 1, (1,)),
reset_fn: callable = basic_reset_fn,
- step_fn: callable = basic_step_fn,
+ step_fn: callable = new_step_fn,
render_fn: callable = basic_render_fn,
render_modes: Optional[List[str]] = None,
render_fps: Optional[int] = None,
diff --git a/tests/wrappers/test_atari_preprocessing.py b/tests/wrappers/test_atari_preprocessing.py
index 845d7b25c96..e083d3f0ed5 100644
--- a/tests/wrappers/test_atari_preprocessing.py
+++ b/tests/wrappers/test_atari_preprocessing.py
@@ -1,90 +1,124 @@
import numpy as np
import pytest
-import gym
+from gym.spaces import Box, Discrete
from gym.wrappers import AtariPreprocessing
+from tests.testing_env import GenericTestEnv, old_step_fn
-pytest.importorskip("gym.envs.atari")
+class AleTesting:
+ """A testing implementation for the ALE object in atari games."""
-@pytest.fixture(scope="module")
-def env_fn():
- return lambda: gym.make("PongNoFrameskip-v4", disable_env_checker=True)
+ grayscale_obs_space = Box(low=0, high=255, shape=(210, 160), dtype=np.uint8, seed=1)
+ rgb_obs_space = Box(low=0, high=255, shape=(210, 160, 3), dtype=np.uint8, seed=1)
+ def lives(self) -> int:
+ """Returns the number of lives in the atari game."""
+ return 1
-def test_atari_preprocessing_grayscale(env_fn):
- import cv2
+ def getScreenGrayscale(self, buffer: np.ndarray):
+ """Updates the buffer with a random grayscale observation."""
+ buffer[...] = self.grayscale_obs_space.sample()
- env1 = env_fn()
- env2 = AtariPreprocessing(
- env_fn(), screen_size=84, grayscale_obs=True, frame_skip=1, noop_max=0
- )
- env3 = AtariPreprocessing(
- env_fn(), screen_size=84, grayscale_obs=False, frame_skip=1, noop_max=0
- )
- env4 = AtariPreprocessing(
- env_fn(),
+ def getScreenRGB(self, buffer: np.ndarray):
+ """Updates the buffer with a random rgb observation."""
+ buffer[...] = self.rgb_obs_space.sample()
+
+
+class AtariTestingEnv(GenericTestEnv):
+ """A testing environment to replicate the atari (ale-py) environments."""
+
+ def __init__(self):
+ super().__init__(
+ observation_space=Box(
+ low=0, high=255, shape=(210, 160, 3), dtype=np.uint8, seed=1
+ ),
+ action_space=Discrete(3, seed=1),
+ step_fn=old_step_fn,
+ )
+ self.ale = AleTesting()
+
+ def get_action_meanings(self):
+ """Returns the meanings of each of the actions available to the agent. First index must be 'NOOP'."""
+ return ["NOOP", "UP", "DOWN"]
+
+
+@pytest.mark.parametrize(
+ "env, obs_shape",
+ [
+ (AtariTestingEnv(), (210, 160, 3)),
+ (
+ AtariPreprocessing(
+ AtariTestingEnv(),
+ screen_size=84,
+ grayscale_obs=True,
+ frame_skip=1,
+ noop_max=0,
+ ),
+ (84, 84),
+ ),
+ (
+ AtariPreprocessing(
+ AtariTestingEnv(),
+ screen_size=84,
+ grayscale_obs=False,
+ frame_skip=1,
+ noop_max=0,
+ ),
+ (84, 84, 3),
+ ),
+ (
+ AtariPreprocessing(
+ AtariTestingEnv(),
+ screen_size=84,
+ grayscale_obs=True,
+ frame_skip=1,
+ noop_max=0,
+ grayscale_newaxis=True,
+ ),
+ (84, 84, 1),
+ ),
+ ],
+)
+def test_atari_preprocessing_grayscale(env, obs_shape):
+ assert env.observation_space.shape == obs_shape
+
+ # It is not possible to test the outputs as we are not using actual observations.
+ # todo: update when ale-py is compatible with the ci
+
+ obs = env.reset(seed=0)
+ assert obs in env.observation_space
+ obs, _ = env.reset(seed=0, return_info=True)
+ assert obs in env.observation_space
+
+ obs, _, _, _ = env.step(env.action_space.sample())
+ assert obs in env.observation_space
+
+ env.close()
+
+
+@pytest.mark.parametrize("grayscale", [True, False])
+@pytest.mark.parametrize("scaled", [True, False])
+def test_atari_preprocessing_scale(grayscale, scaled, max_test_steps=10):
+ # arbitrarily chosen number for stepping into env. and ensuring all observations are in the required range
+ env = AtariPreprocessing(
+ AtariTestingEnv(),
screen_size=84,
- grayscale_obs=True,
+ grayscale_obs=grayscale,
+ scale_obs=scaled,
frame_skip=1,
noop_max=0,
- grayscale_newaxis=True,
)
- obs1 = env1.reset(seed=0)
- obs2 = env2.reset(seed=0)
- obs3 = env3.reset(seed=0)
- obs4 = env4.reset(seed=0)
- assert env1.observation_space.shape == (210, 160, 3)
- assert env2.observation_space.shape == (84, 84)
- assert env3.observation_space.shape == (84, 84, 3)
- assert env4.observation_space.shape == (84, 84, 1)
- assert obs1.shape == (210, 160, 3)
- assert obs2.shape == (84, 84)
- assert obs3.shape == (84, 84, 3)
- assert obs4.shape == (84, 84, 1)
- assert np.allclose(obs3, cv2.resize(obs1, (84, 84), interpolation=cv2.INTER_AREA))
- obs3_gray = cv2.cvtColor(obs3, cv2.COLOR_RGB2GRAY)
- # the edges of the numbers do not render quite the same in the grayscale, so we ignore them
- assert np.allclose(obs2[10:38], obs3_gray[10:38])
- # the paddle also do not render quite the same
- assert np.allclose(obs2[44:], obs3_gray[44:])
- # now add a channel axis and re-test
- obs3_gray = obs3_gray.reshape(84, 84, 1)
- assert np.allclose(obs4[10:38], obs3_gray[10:38])
- assert np.allclose(obs4[44:], obs3_gray[44:])
-
- env1.close()
- env2.close()
- env3.close()
- env4.close()
-
-
-def test_atari_preprocessing_scale(env_fn):
- # arbitrarily chosen number for stepping into env. and ensuring all observations are in the required range
- max_test_steps = 10
- for grayscale in [True, False]:
- for scaled in [True, False]:
- env = AtariPreprocessing(
- env_fn(),
- screen_size=84,
- grayscale_obs=grayscale,
- scale_obs=scaled,
- frame_skip=1,
- noop_max=0,
- )
- obs = env.reset().flatten()
- done, step_i = False, 0
- max_obs = 1 if scaled else 255
- assert (0 <= obs).all() and (
- obs <= max_obs
- ).all(), f"Obs. must be in range [0,{max_obs}]"
- while not done or step_i <= max_test_steps:
- obs, _, done, _ = env.step(env.action_space.sample())
- obs = obs.flatten()
- assert (0 <= obs).all() and (
- obs <= max_obs
- ).all(), f"Obs. must be in range [0,{max_obs}]"
- step_i += 1
-
- env.close()
+ obs = env.reset()
+
+ max_obs = 1 if scaled else 255
+ assert np.all(0 <= obs) and np.all(obs <= max_obs)
+
+ done, step_i = False, 0
+ while not done and step_i <= max_test_steps:
+ obs, _, done, _ = env.step(env.action_space.sample())
+ assert np.all(0 <= obs) and np.all(obs <= max_obs)
+
+ step_i += 1
+ env.close()
diff --git a/tests/wrappers/test_frame_stack.py b/tests/wrappers/test_frame_stack.py
index 826790f86b4..8c4ed0664de 100644
--- a/tests/wrappers/test_frame_stack.py
+++ b/tests/wrappers/test_frame_stack.py
@@ -10,10 +10,7 @@
lz4 = None
-pytest.importorskip("gym.envs.atari")
-
-
-@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "Pong-v0"])
+@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "CarRacing-v2"])
@pytest.mark.parametrize("num_stack", [2, 3, 4])
@pytest.mark.parametrize(
"lz4_compress",
@@ -42,8 +39,13 @@ def test_frame_stack(env_id, num_stack, lz4_compress):
for _ in range(num_stack**2):
action = env.action_space.sample()
- dup_obs, _, _, _ = dup.step(action)
- obs, _, _, _ = env.step(action)
+ dup_obs, _, dup_done, _ = dup.step(action)
+ obs, _, done, _ = env.step(action)
+
+ assert dup_done == done
assert np.allclose(obs[-1], dup_obs)
+ if done:
+ break
+
assert len(obs) == num_stack
diff --git a/tests/wrappers/test_gray_scale_observation.py b/tests/wrappers/test_gray_scale_observation.py
index 58f878952db..be63fc0d20d 100644
--- a/tests/wrappers/test_gray_scale_observation.py
+++ b/tests/wrappers/test_gray_scale_observation.py
@@ -1,44 +1,26 @@
-import numpy as np
import pytest
import gym
from gym import spaces
-from gym.wrappers import AtariPreprocessing, GrayScaleObservation
+from gym.wrappers import GrayScaleObservation
-pytest.importorskip("gym.envs.atari")
-pytest.importorskip("cv2")
-
-@pytest.mark.parametrize(
- "env_id", ["PongNoFrameskip-v0", "SpaceInvadersNoFrameskip-v0"]
-)
+@pytest.mark.parametrize("env_id", ["CarRacing-v2"])
@pytest.mark.parametrize("keep_dim", [True, False])
def test_gray_scale_observation(env_id, keep_dim):
- gray_env = AtariPreprocessing(
- gym.make(env_id, disable_env_checker=True), screen_size=84, grayscale_obs=True
- )
- rgb_env = AtariPreprocessing(
- gym.make(env_id, disable_env_checker=True), screen_size=84, grayscale_obs=False
- )
- wrapped_env = GrayScaleObservation(rgb_env, keep_dim=keep_dim)
+ rgb_env = gym.make(env_id, disable_env_checker=True)
assert isinstance(rgb_env.observation_space, spaces.Box)
+ assert len(rgb_env.observation_space.shape) == 3
assert rgb_env.observation_space.shape[-1] == 3
+ wrapped_env = GrayScaleObservation(rgb_env, keep_dim=keep_dim)
assert isinstance(wrapped_env.observation_space, spaces.Box)
-
- seed = 0
-
- gray_obs = gray_env.reset(seed=seed)
- wrapped_obs = wrapped_env.reset(seed=seed)
-
if keep_dim:
+ assert len(wrapped_env.observation_space.shape) == 3
assert wrapped_env.observation_space.shape[-1] == 1
- assert len(wrapped_obs.shape) == 3
- wrapped_obs = wrapped_obs.squeeze(-1)
else:
assert len(wrapped_env.observation_space.shape) == 2
- assert len(wrapped_obs.shape) == 2
- # ALE gray scale is slightly different, but no more than by one shade
- assert np.allclose(gray_obs.astype("int32"), wrapped_obs.astype("int32"), atol=1)
+ wrapped_obs = wrapped_env.reset()
+ assert wrapped_obs in wrapped_env.observation_space
diff --git a/tests/wrappers/test_resize_observation.py b/tests/wrappers/test_resize_observation.py
index 62b3a3d737e..b0553df602e 100644
--- a/tests/wrappers/test_resize_observation.py
+++ b/tests/wrappers/test_resize_observation.py
@@ -4,12 +4,8 @@
from gym import spaces
from gym.wrappers import ResizeObservation
-pytest.importorskip("gym.envs.atari")
-
-@pytest.mark.parametrize(
- "env_id", ["PongNoFrameskip-v0", "SpaceInvadersNoFrameskip-v0"]
-)
+@pytest.mark.parametrize("env_id", ["CarRacing-v2"])
@pytest.mark.parametrize("shape", [16, 32, (8, 5), [10, 7]])
def test_resize_observation(env_id, shape):
env = gym.make(env_id, disable_env_checker=True)
| Currently, there were four tests that included `pytest.importorskip`, in particular for atari.
As our CI does not include atari in our testing then these tests are always skipped meaning that new bugs could occur and never be picked up in the testing.
This PR removes all of these `pytest.importorskip` replacing the atari environments for `CarRacing` as a similar image-based environment and a fake atari environment for testing with the `AtariPreprocessing`.
While this fake atari environment is not optimal, it is the best we can do until ale-py change their install method or the pip `21.3` which may provide a solution for installing gym and ale-py in editible mode | https://api.github.com/repos/openai/gym/pulls/2976 | 2022-07-17T20:53:57Z | 2022-07-23T14:38:53Z | 2022-07-23T14:38:53Z | 2022-07-23T14:38:53Z | 3,577 | openai/gym | 5,167 |
bugfix issue 3135 | diff --git a/llama_index/output_parsers/selection.py b/llama_index/output_parsers/selection.py
index 54c784d000085..4e8800ed6f0ad 100644
--- a/llama_index/output_parsers/selection.py
+++ b/llama_index/output_parsers/selection.py
@@ -1,8 +1,9 @@
-from dataclasses import dataclass
import json
+from dataclasses import dataclass
from typing import Any
from dataclasses_json import DataClassJsonMixin
+
from llama_index.output_parsers.base import BaseOutputParser, StructuredOutput
@@ -45,7 +46,26 @@ class Answer(DataClassJsonMixin):
class SelectionOutputParser(BaseOutputParser):
+ def _marshal_llm_to_json(self, output: str) -> str:
+ """Extract a valid JSON array from a string.
+ Extracts a substring that represents a valid JSON array.
+
+ Args:
+ output: A string that may contain a valid JSON array surrounded by
+ extraneous characters or information.
+
+ Returns:
+ A string representing a valid JSON array.
+
+ """
+ output = output.strip()
+ left = output.find("[")
+ right = output.rfind("]")
+ output = output[left : right + 1]
+ return output
+
def parse(self, output: str) -> Any:
+ output = self._marshal_llm_to_json(output)
json_list = json.loads(output)
answers = [Answer.from_dict(json_dict) for json_dict in json_list]
return StructuredOutput(raw_output=output, parsed_output=answers)
diff --git a/tests/output_parsers/test_selection.py b/tests/output_parsers/test_selection.py
index 0ec124dd5e342..ff320e5c39a8d 100644
--- a/tests/output_parsers/test_selection.py
+++ b/tests/output_parsers/test_selection.py
@@ -1,4 +1,5 @@
import pytest
+
from llama_index.output_parsers.base import StructuredOutput
from llama_index.output_parsers.selection import SelectionOutputParser
@@ -26,3 +27,24 @@ def test_parse(output_parser: SelectionOutputParser) -> None:
assert len(parsed.parsed_output) == 2
assert parsed.parsed_output[0].choice == 1
assert parsed.parsed_output[0].reason == "just because"
+
+
+def test_parse_non_json_friendly_llm_output(
+ output_parser: SelectionOutputParser,
+) -> None:
+ # https://github.com/jerryjliu/llama_index/issues/3135
+ output = """
+ Output:
+ [
+ {
+ "choice": 1,
+ "reason": "Useful for questions"
+ }
+ ]
+ """
+ parsed = output_parser.parse(output)
+ assert isinstance(parsed, StructuredOutput)
+ assert isinstance(parsed.parsed_output, list)
+ assert len(parsed.parsed_output) == 1
+ assert parsed.parsed_output[0].choice == 1
+ assert parsed.parsed_output[0].reason == "Useful for questions"
| fixes issue (includes test) | https://api.github.com/repos/run-llama/llama_index/pulls/3136 | 2023-05-10T02:09:57Z | 2023-05-12T06:05:42Z | 2023-05-12T06:05:42Z | 2023-05-12T06:05:42Z | 691 | run-llama/llama_index | 6,135 |
community: add helpful comments to sparkllm.py | diff --git a/libs/community/langchain_community/chat_models/sparkllm.py b/libs/community/langchain_community/chat_models/sparkllm.py
index 7e84c2e98c2e5a..17fb83687d1c70 100644
--- a/libs/community/langchain_community/chat_models/sparkllm.py
+++ b/libs/community/langchain_community/chat_models/sparkllm.py
@@ -104,6 +104,18 @@ class ChatSparkLLM(BaseChatModel):
spark_api_key="<api_key>",
spark_api_secret="<api_secret>"
)
+
+ Extra infos:
+ 1. Get app_id, api_key, api_secret from the iFlyTek Open Platform Console:
+ https://console.xfyun.cn/services/bm35
+ 2. By default, iFlyTek Spark LLM V3.0 is invoked.
+ If you need to invoke other versions, please configure the corresponding
+ parameters(spark_api_url and spark_llm_domain) according to the document:
+ https://www.xfyun.cn/doc/spark/Web.html
+ 3. It is necessary to ensure that the app_id used has a license for
+ the corresponding model version.
+ 4. If you encounter problems during use, try getting help at:
+ https://console.xfyun.cn/workorder/commit
"""
@classmethod
| Adding helpful comments to sparkllm.py, help users to use ChatSparkLLM more effectively | https://api.github.com/repos/langchain-ai/langchain/pulls/17774 | 2024-02-20T06:24:23Z | 2024-02-22T00:42:54Z | 2024-02-22T00:42:54Z | 2024-02-22T00:42:55Z | 302 | langchain-ai/langchain | 43,297 |
[RLlib] Fix "seed" setting to work in all frameworks and w/ all CUDA versions. | diff --git a/rllib/BUILD b/rllib/BUILD
index 1acd31b8dc0eb..4dc3148cb159a 100644
--- a/rllib/BUILD
+++ b/rllib/BUILD
@@ -2075,6 +2075,33 @@ py_test(
args = ["--stop-iters=2", "--num-cpus=4"]
)
+py_test(
+ name = "examples/deterministic_training_tf",
+ main = "examples/deterministic_training.py",
+ tags = ["examples", "examples_D"],
+ size = "medium",
+ srcs = ["examples/deterministic_training.py"],
+ args = ["--as-test", "--stop-iters=1", "--framework=tf"]
+)
+
+py_test(
+ name = "examples/deterministic_training_tf2",
+ main = "examples/deterministic_training.py",
+ tags = ["examples", "examples_D"],
+ size = "medium",
+ srcs = ["examples/deterministic_training.py"],
+ args = ["--as-test", "--stop-iters=1", "--framework=tf2"]
+)
+
+py_test(
+ name = "examples/deterministic_training_torch",
+ main = "examples/deterministic_training.py",
+ tags = ["examples", "examples_D"],
+ size = "medium",
+ srcs = ["examples/deterministic_training.py"],
+ args = ["--as-test", "--stop-iters=1", "--framework=torch"]
+)
+
py_test(
name = "examples/eager_execution",
tags = ["examples", "examples_E"],
diff --git a/rllib/evaluation/rollout_worker.py b/rllib/evaluation/rollout_worker.py
index 680587589ea85..47d8b62680b70 100644
--- a/rllib/evaluation/rollout_worker.py
+++ b/rllib/evaluation/rollout_worker.py
@@ -48,7 +48,7 @@
if TYPE_CHECKING:
from ray.rllib.evaluation.observation_function import ObservationFunction
- from ray.rllib.agents.callbacks import DefaultCallbacks
+ from ray.rllib.agents.callbacks import DefaultCallbacks # noqa
# Generic type var for foreach_* methods.
T = TypeVar("T")
@@ -356,7 +356,7 @@ def gen_rollouts():
if callbacks:
self.callbacks: "DefaultCallbacks" = callbacks()
else:
- from ray.rllib.agents.callbacks import DefaultCallbacks
+ from ray.rllib.agents.callbacks import DefaultCallbacks # noqa
self.callbacks: DefaultCallbacks = DefaultCallbacks()
self.worker_index: int = worker_index
self.num_workers: int = num_workers
@@ -482,20 +482,39 @@ def make_env(vector_index):
self.policy_map: Dict[PolicyID, Policy] = None
self.preprocessors: Dict[PolicyID, Preprocessor] = None
- # set numpy and python seed
+ # Set Python random, numpy, env, and torch/tf seeds.
if seed is not None:
- np.random.seed(seed)
+ # Python random module.
random.seed(seed)
+ # Numpy.
+ np.random.seed(seed)
+ # Gym.env.
if not hasattr(self.env, "seed"):
logger.info("Env doesn't support env.seed(): {}".format(
self.env))
else:
self.env.seed(seed)
- try:
- assert torch is not None
+
+ # Torch.
+ if torch and policy_config.get("framework") == "torch":
torch.manual_seed(seed)
- except AssertionError:
- logger.info("Could not seed torch")
+ # See https://github.com/pytorch/pytorch/issues/47672.
+ cuda_version = torch.version.cuda
+ if cuda_version is not None and float(
+ torch.version.cuda) >= 10.2:
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = "4096:8"
+ else:
+ # Not all Operations support this.
+ torch.use_deterministic_algorithms(True)
+ # This is only for Convolution no problem.
+ torch.backends.cudnn.deterministic = True
+ # Tf2.x.
+ elif tf and policy_config.get("framework") == "tf2":
+ tf.random.set_seed(seed)
+ # Tf-eager.
+ elif tf1 and policy_config.get("framework") == "tfe":
+ tf1.set_random_seed(seed)
+
if _has_tensorflow_graph(policy_dict) and not (
tf1 and tf1.executing_eagerly()):
if not tf1:
diff --git a/rllib/examples/deterministic_training.py b/rllib/examples/deterministic_training.py
new file mode 100644
index 0000000000000..c9951ae605f58
--- /dev/null
+++ b/rllib/examples/deterministic_training.py
@@ -0,0 +1,61 @@
+"""
+Example of a fully deterministic, repeatable RLlib train run using
+the "seed" config key.
+"""
+import argparse
+import os
+
+import ray
+from ray import tune
+from ray.rllib.examples.env.env_using_remote_actor import \
+ CartPoleWithRemoteParamServer, ParameterStorage
+from ray.rllib.utils.framework import try_import_tf, try_import_torch
+from ray.rllib.utils.test_utils import check
+
+tf1, tf, tfv = try_import_tf()
+torch, nn = try_import_torch()
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--run", type=str, default="PPO")
+parser.add_argument(
+ "--framework", choices=["tf2", "tf", "tfe", "torch"], default="tf")
+parser.add_argument("--seed", type=int, default=42)
+parser.add_argument("--as-test", action="store_true")
+parser.add_argument("--stop-iters", type=int, default=2)
+
+if __name__ == "__main__":
+ args = parser.parse_args()
+ ray.init()
+
+ param_storage = ParameterStorage.options(name="param-server").remote()
+
+ config = {
+ "env": CartPoleWithRemoteParamServer,
+ "env_config": {
+ "param_server": "param-server",
+ },
+ # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.
+ "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
+ "num_workers": 2, # parallelism
+ "framework": args.framework,
+ "seed": args.seed,
+
+ # Simplify to run this example script faster.
+ "train_batch_size": 100,
+ "sgd_minibatch_size": 10,
+ "num_sgd_iter": 5,
+ "rollout_fragment_length": 50,
+ }
+
+ stop = {
+ "training_iteration": args.stop_iters,
+ }
+
+ results = tune.run(args.run, config=config, stop=stop, verbose=1)
+ results2 = tune.run(args.run, config=config, stop=stop, verbose=1)
+
+ if args.as_test:
+ check(
+ list(results.results.values())[0]["hist_stats"],
+ list(results2.results.values())[0]["hist_stats"])
+ ray.shutdown()
diff --git a/rllib/examples/env/env_using_remote_actor.py b/rllib/examples/env/env_using_remote_actor.py
new file mode 100644
index 0000000000000..15c5c4f610ec7
--- /dev/null
+++ b/rllib/examples/env/env_using_remote_actor.py
@@ -0,0 +1,56 @@
+"""
+Example of an environment that uses a named remote actor as parameter
+server.
+
+"""
+from gym.envs.classic_control.cartpole import CartPoleEnv
+from gym.utils import seeding
+
+import ray
+
+
+@ray.remote
+class ParameterStorage:
+ def get_params(self, rng):
+ return {
+ "MASSCART": rng.uniform(low=0.5, high=2.0),
+ }
+
+
+class CartPoleWithRemoteParamServer(CartPoleEnv):
+ """CartPoleMassEnv varies the weights of the cart and the pole.
+ """
+
+ def __init__(self, env_config):
+ self.env_config = env_config
+ super().__init__()
+ # Get our param server (remote actor) by name.
+ self._handler = ray.get_actor(
+ env_config.get("param_server", "param-server"))
+
+ # def seed(self, seed=None):
+ # print(f"Seeding env (worker={self.env_config.worker_index}) "
+ # f"with {seed}")
+ # self.np_random, seed = seeding.np_random(seed)
+ # return [seed]
+
+ def reset(self):
+ # Pass in our RNG to guarantee no race conditions.
+ # If `self._handler` had its own RNG, this may clash with other
+ # envs trying to use the same param-server.
+ params = ray.get(self._handler.get_params.remote(self.np_random))
+
+ # IMPORTANT: Advance the state of our RNG (self._rng was passed
+ # above via ray (serialized) and thus not altered locally here!).
+ # Or create a new RNG from another random number:
+ new_seed = self.np_random.randint(0, 1000000)
+ self.np_random, _ = seeding.np_random(new_seed)
+
+ print(f"Env worker-idx={self.env_config.worker_index} "
+ f"mass={params['MASSCART']}")
+
+ self.masscart = params["MASSCART"]
+ self.total_mass = (self.masspole + self.masscart)
+ self.polemass_length = (self.masspole * self.length)
+
+ return super().reset()
| <!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. -->
Fix "seed" setting to work in all frameworks and w/ all CUDA versions.
- Added example script that tests determinism in the parallel setting for all frameworks.
<!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. -->
## Why are these changes needed?
<!-- Please give a short summary of the change and the problem this solves. -->
## Related issue number
<!-- For example: "Closes #1234" -->
## Checks
- [x] I've run `scripts/format.sh` to lint the changes in this PR.
- [x] I've included any doc changes needed for https://docs.ray.io/en/master/.
- [x] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
- [x] Unit tests
- [ ] Release tests
- [ ] This PR is not tested :(
| https://api.github.com/repos/ray-project/ray/pulls/15682 | 2021-05-07T11:49:44Z | 2021-05-18T09:00:24Z | 2021-05-18T09:00:24Z | 2023-06-02T20:14:41Z | 2,201 | ray-project/ray | 19,845 |
Fix appfactories doc | diff --git a/docs/patterns/appfactories.rst b/docs/patterns/appfactories.rst
index 415c10fa47..a76e676f32 100644
--- a/docs/patterns/appfactories.rst
+++ b/docs/patterns/appfactories.rst
@@ -91,7 +91,7 @@ To run such an application, you can use the :command:`flask` command:
.. code-block:: text
- $ flask run --app hello run
+ $ flask --app hello run
Flask will automatically detect the factory if it is named
``create_app`` or ``make_app`` in ``hello``. You can also pass arguments
@@ -99,7 +99,7 @@ to the factory like this:
.. code-block:: text
- $ flask run --app hello:create_app(local_auth=True)``
+ $ flask --app hello:create_app(local_auth=True) run``
Then the ``create_app`` factory in ``myapp`` is called with the keyword
argument ``local_auth=True``. See :doc:`/cli` for more detail.
| <!--
Before opening a PR, open a ticket describing the issue or feature the
PR will address. Follow the steps in CONTRIBUTING.rst.
Replace this comment with a description of the change. Describe how it
addresses the linked ticket.
-->
<!--
Link to relevant issues or previous PRs, one per line. Use "fixes" to
automatically close an issue.
-->
- fixes #<issue number>
Fix appfactories doc
| https://api.github.com/repos/pallets/flask/pulls/4960 | 2023-02-02T15:45:50Z | 2023-02-02T17:01:04Z | 2023-02-02T17:01:03Z | 2023-02-17T00:05:54Z | 242 | pallets/flask | 20,905 |
[MRG+1] TST remove temp files and folders | diff --git a/tests/test_downloader_handlers.py b/tests/test_downloader_handlers.py
index 6333efceb15..f9980f7b2e6 100644
--- a/tests/test_downloader_handlers.py
+++ b/tests/test_downloader_handlers.py
@@ -1,6 +1,7 @@
import os
import six
import contextlib
+import shutil
try:
from unittest import mock
except ImportError:
@@ -84,11 +85,13 @@ class FileTestCase(unittest.TestCase):
def setUp(self):
self.tmpname = self.mktemp()
- fd = open(self.tmpname + '^', 'w')
- fd.write('0123456789')
- fd.close()
+ with open(self.tmpname + '^', 'w') as f:
+ f.write('0123456789')
self.download_request = FileDownloadHandler(Settings()).download_request
+ def tearDown(self):
+ os.unlink(self.tmpname + '^')
+
def test_download(self):
def _test(response):
self.assertEquals(response.url, request.url)
@@ -134,10 +137,10 @@ class HttpTestCase(unittest.TestCase):
certfile = 'keys/cert.pem'
def setUp(self):
- name = self.mktemp()
- os.mkdir(name)
- FilePath(name).child("file").setContent(b"0123456789")
- r = static.File(name)
+ self.tmpname = self.mktemp()
+ os.mkdir(self.tmpname)
+ FilePath(self.tmpname).child("file").setContent(b"0123456789")
+ r = static.File(self.tmpname)
r.putChild(b"redirect", util.Redirect(b"/file"))
r.putChild(b"wait", ForeverTakingResource())
r.putChild(b"hang-after-headers", ForeverTakingResource(write=True))
@@ -165,6 +168,7 @@ def tearDown(self):
yield self.port.stopListening()
if hasattr(self.download_handler, 'close'):
yield self.download_handler.close()
+ shutil.rmtree(self.tmpname)
def getURL(self, path):
return "%s://%s:%d/%s" % (self.scheme, self.host, self.portno, path)
@@ -709,6 +713,9 @@ def setUp(self):
self.download_handler = FTPDownloadHandler(Settings())
self.addCleanup(self.port.stopListening)
+ def tearDown(self):
+ shutil.rmtree(self.directory)
+
def _add_test_callbacks(self, deferred, callback=None, errback=None):
def _clean(data):
self.download_handler.client.transport.loseConnection()
diff --git a/tests/test_feedexport.py b/tests/test_feedexport.py
index e93d2bafbec..2d137edf48a 100644
--- a/tests/test_feedexport.py
+++ b/tests/test_feedexport.py
@@ -57,8 +57,11 @@ def _assert_stores(self, storage, path):
file.write(b"content")
yield storage.store(file)
self.assertTrue(os.path.exists(path))
- with open(path, 'rb') as fp:
- self.assertEqual(fp.read(), b"content")
+ try:
+ with open(path, 'rb') as fp:
+ self.assertEqual(fp.read(), b"content")
+ finally:
+ os.unlink(path)
class FTPFeedStorageTest(unittest.TestCase):
@@ -79,12 +82,15 @@ def _assert_stores(self, storage, path):
file.write(b"content")
yield storage.store(file)
self.assertTrue(os.path.exists(path))
- with open(path, 'rb') as fp:
- self.assertEqual(fp.read(), b"content")
- # again, to check s3 objects are overwritten
- yield storage.store(BytesIO(b"new content"))
- with open(path, 'rb') as fp:
- self.assertEqual(fp.read(), b"new content")
+ try:
+ with open(path, 'rb') as fp:
+ self.assertEqual(fp.read(), b"content")
+ # again, to check s3 objects are overwritten
+ yield storage.store(BytesIO(b"new content"))
+ with open(path, 'rb') as fp:
+ self.assertEqual(fp.read(), b"new content")
+ finally:
+ os.unlink(path)
class BlockingFeedStorageTest(unittest.TestCase):
diff --git a/tests/test_spiderstate.py b/tests/test_spiderstate.py
index d1d6debec20..383fadfeb61 100644
--- a/tests/test_spiderstate.py
+++ b/tests/test_spiderstate.py
@@ -1,5 +1,6 @@
import os
from datetime import datetime
+import shutil
from twisted.trial import unittest
from scrapy.extensions.spiderstate import SpiderState
@@ -13,20 +14,23 @@ class SpiderStateTest(unittest.TestCase):
def test_store_load(self):
jobdir = self.mktemp()
os.mkdir(jobdir)
- spider = Spider(name='default')
- dt = datetime.now()
-
- ss = SpiderState(jobdir)
- ss.spider_opened(spider)
- spider.state['one'] = 1
- spider.state['dt'] = dt
- ss.spider_closed(spider)
-
- spider2 = Spider(name='default')
- ss2 = SpiderState(jobdir)
- ss2.spider_opened(spider2)
- self.assertEqual(spider.state, {'one': 1, 'dt': dt})
- ss2.spider_closed(spider2)
+ try:
+ spider = Spider(name='default')
+ dt = datetime.now()
+
+ ss = SpiderState(jobdir)
+ ss.spider_opened(spider)
+ spider.state['one'] = 1
+ spider.state['dt'] = dt
+ ss.spider_closed(spider)
+
+ spider2 = Spider(name='default')
+ ss2 = SpiderState(jobdir)
+ ss2.spider_opened(spider2)
+ self.assertEqual(spider.state, {'one': 1, 'dt': dt})
+ ss2.spider_closed(spider2)
+ finally:
+ shutil.rmtree(jobdir)
def test_state_attribute(self):
# state attribute must be present if jobdir is not set, to provide a
diff --git a/tests/test_webclient.py b/tests/test_webclient.py
index 9b5beda4cac..3ad1aa70e09 100644
--- a/tests/test_webclient.py
+++ b/tests/test_webclient.py
@@ -4,7 +4,7 @@
"""
import os
import six
-from six.moves.urllib.parse import urlparse
+import shutil
from twisted.trial import unittest
from twisted.web import server, static, util, resource
@@ -12,6 +12,7 @@
from twisted.test.proto_helpers import StringTransport
from twisted.python.filepath import FilePath
from twisted.protocols.policies import WrappingFactory
+from twisted.internet.defer import inlineCallbacks
from scrapy.core.downloader import webclient as client
from scrapy.http import Request, Headers
@@ -229,10 +230,10 @@ def _listen(self, site):
return reactor.listenTCP(0, site, interface="127.0.0.1")
def setUp(self):
- name = self.mktemp()
- os.mkdir(name)
- FilePath(name).child("file").setContent(b"0123456789")
- r = static.File(name)
+ self.tmpname = self.mktemp()
+ os.mkdir(self.tmpname)
+ FilePath(self.tmpname).child("file").setContent(b"0123456789")
+ r = static.File(self.tmpname)
r.putChild(b"redirect", util.Redirect(b"/file"))
r.putChild(b"wait", ForeverTakingResource())
r.putChild(b"error", ErrorResource())
@@ -246,8 +247,10 @@ def setUp(self):
self.port = self._listen(self.wrapper)
self.portno = self.port.getHost().port
+ @inlineCallbacks
def tearDown(self):
- return self.port.stopListening()
+ yield self.port.stopListening()
+ shutil.rmtree(self.tmpname)
def getURL(self, path):
return "http://127.0.0.1:%d/%s" % (self.portno, path)
@@ -266,7 +269,6 @@ def testHostHeader(self):
getPage(self.getURL("host"), headers={"Host": "www.example.com"}).addCallback(
self.assertEquals, to_bytes("www.example.com"))])
-
def test_getPage(self):
"""
L{client.getPage} returns a L{Deferred} which is called back with
@@ -276,7 +278,6 @@ def test_getPage(self):
d.addCallback(self.assertEquals, b"0123456789")
return d
-
def test_getPageHead(self):
"""
L{client.getPage} returns a L{Deferred} which is called back with
@@ -289,7 +290,6 @@ def _getPage(method):
_getPage("head").addCallback(self.assertEqual, b""),
_getPage("HEAD").addCallback(self.assertEqual, b"")])
-
def test_timeoutNotTriggering(self):
"""
When a non-zero timeout is passed to L{getPage} and the page is
@@ -301,7 +301,6 @@ def test_timeoutNotTriggering(self):
self.assertEquals, to_bytes("127.0.0.1:%d" % self.portno))
return d
-
def test_timeoutTriggering(self):
"""
When a non-zero timeout is passed to L{getPage} and that many
@@ -351,7 +350,7 @@ def _cbRedirect(self, pageData):
b' </head>\n <body bgcolor="#FFFFFF" text="#000000">\n '
b'<a href="/file">click here</a>\n </body>\n</html>\n')
- def test_Encoding(self):
+ def test_encoding(self):
""" Test that non-standart body encoding matches
Content-Encoding header """
body = b'\xd0\x81\xd1\x8e\xd0\xaf'
| This PR makes sure temp files are deleted in tests. It also fixes a **weird** pytest+OS X issue. Previously tests failed for me with exception like this:
```
______________________________________________ ERROR at setup of WebClientTestCase.test_Encoding ______________________________________________
cls = <class 'py._path.local.LocalPath'>, prefix = 'test_Encoding'
rootdir = local('/private/var/folders/_5/cbsg50991szfp1r9nwxpx8580000gn/T/pytest-of-kmike/pytest-0'), keep = 0, lock_timeout = None
def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3,
lock_timeout = 172800): # two days
""" return unique directory with a number greater than the current
maximum one. The number is assumed to start directly after prefix.
if keep is true directories with a number less than (maxnum-keep)
will be removed.
"""
if rootdir is None:
rootdir = cls.get_temproot()
def parse_num(path):
""" parse the number out of a path (if it matches the prefix) """
bn = path.basename
if bn.startswith(prefix):
try:
return int(bn[len(prefix):])
except ValueError:
pass
# compute the maximum number currently in use with the
# prefix
lastmax = None
while True:
maxnum = -1
for path in rootdir.listdir():
num = parse_num(path)
if num is not None:
maxnum = max(maxnum, num)
# make the new directory
try:
> udir = rootdir.mkdir(prefix + str(maxnum+1))
/Users/kmike/svn/scrapy/.tox/py36/lib/python3.6/site-packages/py/_path/local.py:825:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/Users/kmike/svn/scrapy/.tox/py36/lib/python3.6/site-packages/py/_path/local.py:459: in mkdir
py.error.checked_call(os.mkdir, fspath(p))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <py._error.ErrorMaker object at 0x110844518>, func = <built-in function mkdir>
args = ('/private/var/folders/_5/cbsg50991szfp1r9nwxpx8580000gn/T/pytest-of-kmike/pytest-0/test_Encoding0',), kwargs = {}
__tracebackhide__ = False, cls = <class 'py.error.EEXIST'>, value = FileExistsError(17, 'File exists'), tb = <traceback object at 0x117b3f248>
errno = 17
def checked_call(self, func, *args, **kwargs):
""" call a function and raise an errno-exception if applicable. """
__tracebackhide__ = True
try:
return func(*args, **kwargs)
except self.Error:
raise
except (OSError, EnvironmentError):
cls, value, tb = sys.exc_info()
if not hasattr(value, 'errno'):
raise
__tracebackhide__ = False
errno = value.errno
try:
if not isinstance(value, WindowsError):
raise NameError
except NameError:
# we are not on Windows, or we got a proper OSError
cls = self._geterrnoclass(errno)
else:
try:
cls = self._geterrnoclass(_winerrnomap[errno])
except KeyError:
raise value
> raise cls("%s%r" % (func.__name__, args))
E py.error.EEXIST: [File exists]: mkdir('/private/var/folders/_5/cbsg50991szfp1r9nwxpx8580000gn/T/pytest-of-kmike/pytest-0/test_Encoding0',)
``` | https://api.github.com/repos/scrapy/scrapy/pulls/2570 | 2017-02-16T13:25:59Z | 2017-02-20T14:00:33Z | 2017-02-20T14:00:33Z | 2017-02-20T14:25:23Z | 2,197 | scrapy/scrapy | 34,362 |
TYP: overload for DataFrame.to_xml | diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst
index 445b93705cde5..6ddb1613076ac 100644
--- a/doc/source/whatsnew/v2.2.0.rst
+++ b/doc/source/whatsnew/v2.2.0.rst
@@ -218,6 +218,7 @@ Other Deprecations
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_parquet` except ``path``. (:issue:`54229`)
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_pickle` except ``path``. (:issue:`54229`)
- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_string` except ``buf``. (:issue:`54229`)
+- Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_xml` except ``path_or_buffer``. (:issue:`54229`)
- Deprecated automatic downcasting of object-dtype results in :meth:`Series.replace` and :meth:`DataFrame.replace`, explicitly call ``result = result.infer_objects(copy=False)`` instead. To opt in to the future version, use ``pd.set_option("future.no_silent_downcasting", True)`` (:issue:`54710`)
- Deprecated downcasting behavior in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, :meth:`DataFrame.mask`, :meth:`Series.clip`, :meth:`DataFrame.clip`; in a future version these will not infer object-dtype columns to non-object dtype, or all-round floats to integer dtype. Call ``result.infer_objects(copy=False)`` on the result for object inference, or explicitly cast floats to ints. To opt in to the future version, use ``pd.set_option("future.no_silent_downcasting", True)`` (:issue:`53656`)
- Deprecated including the groups in computations when using :meth:`DataFrameGroupBy.apply` and :meth:`DataFrameGroupBy.resample`; pass ``include_groups=False`` to exclude the groups (:issue:`7155`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 432c0a745c7a0..a16597221ac92 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3272,6 +3272,55 @@ def to_html(
render_links=render_links,
)
+ @overload
+ def to_xml(
+ self,
+ path_or_buffer: None = ...,
+ *,
+ index: bool = ...,
+ root_name: str | None = ...,
+ row_name: str | None = ...,
+ na_rep: str | None = ...,
+ attr_cols: list[str] | None = ...,
+ elem_cols: list[str] | None = ...,
+ namespaces: dict[str | None, str] | None = ...,
+ prefix: str | None = ...,
+ encoding: str = ...,
+ xml_declaration: bool | None = ...,
+ pretty_print: bool | None = ...,
+ parser: XMLParsers | None = ...,
+ stylesheet: FilePath | ReadBuffer[str] | ReadBuffer[bytes] | None = ...,
+ compression: CompressionOptions = ...,
+ storage_options: StorageOptions | None = ...,
+ ) -> str:
+ ...
+
+ @overload
+ def to_xml(
+ self,
+ path_or_buffer: FilePath | WriteBuffer[bytes] | WriteBuffer[str],
+ *,
+ index: bool = ...,
+ root_name: str | None = ...,
+ row_name: str | None = ...,
+ na_rep: str | None = ...,
+ attr_cols: list[str] | None = ...,
+ elem_cols: list[str] | None = ...,
+ namespaces: dict[str | None, str] | None = ...,
+ prefix: str | None = ...,
+ encoding: str = ...,
+ xml_declaration: bool | None = ...,
+ pretty_print: bool | None = ...,
+ parser: XMLParsers | None = ...,
+ stylesheet: FilePath | ReadBuffer[str] | ReadBuffer[bytes] | None = ...,
+ compression: CompressionOptions = ...,
+ storage_options: StorageOptions | None = ...,
+ ) -> None:
+ ...
+
+ @deprecate_nonkeyword_arguments(
+ version="3.0", allowed_args=["self", "path_or_buffer"], name="to_xml"
+ )
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path_or_buffer",
| and deprecate non-keyword arguments | https://api.github.com/repos/pandas-dev/pandas/pulls/55313 | 2023-09-28T01:26:31Z | 2023-09-28T16:16:11Z | 2023-09-28T16:16:11Z | 2023-09-28T16:16:23Z | 1,030 | pandas-dev/pandas | 45,295 |
Update backend.py, index.html, requirements.txt | diff --git a/g4f/gui/client/html/index.html b/g4f/gui/client/html/index.html
index 9dea5fe6f8..66534a510a 100644
--- a/g4f/gui/client/html/index.html
+++ b/g4f/gui/client/html/index.html
@@ -130,9 +130,9 @@
<option value="google-bard">google-bard</option>
<option value="google-palm">google-palm</option>
<option value="bard">bard</option>
- <option value="falcon-40b">falcon-40b</option>
- <option value="falcon-7b">falcon-7b</option>
- <option value="llama-13b">llama-13b</option>
+ <option value="llama2-7b">llama2-7b</option>
+ <option value="llama2-13b">llama2-13b</option>
+ <option value="llama2-70b">llama2-70b</option>
<option value="command-nightly">command-nightly</option>
<option value="gpt-neox-20b">gpt-neox-20b</option>
<option value="santacoder">santacoder</option>
@@ -188,7 +188,7 @@
<option value="g4f.Provider.Aibn">Aibn</option>
<option value="g4f.Provider.Bing">Bing</option>
<option value="g4f.Provider.You">You</option>
- <option value="g4f.Provider.H2o">H2o</option>
+ <option value="g4f.Provider.Llama2">Llama2</option>
<option value="g4f.Provider.Aivvm">Aivvm</option>
</select>
</div>
@@ -203,4 +203,4 @@
</script>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/g4f/gui/server/backend.py b/g4f/gui/server/backend.py
index 304b9fc835..3d7bfedc59 100644
--- a/g4f/gui/server/backend.py
+++ b/g4f/gui/server/backend.py
@@ -56,7 +56,7 @@ def _conversation(self):
def stream():
yield from g4f.ChatCompletion.create(
- model=g4f.models.gpt_35_long,
+ model=model,
provider=get_provider(provider),
messages=messages,
stream=True,
diff --git a/requirements.txt b/requirements.txt
index 857cc324b3..ed0d6e4b10 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -18,4 +18,5 @@ loguru
tiktoken
pillow
platformdirs
-numpy
\ No newline at end of file
+numpy
+asgiref
| change to the model that received from user interactive from the web interface model selection. | https://api.github.com/repos/xtekky/gpt4free/pulls/1180 | 2023-10-28T13:13:34Z | 2023-10-28T15:58:37Z | 2023-10-28T15:58:37Z | 2023-10-28T16:16:25Z | 663 | xtekky/gpt4free | 37,976 |
Lazily encode data, params, files | diff --git a/requests/models.py b/requests/models.py
index ff0ef019d9..7f391a0e45 100644
--- a/requests/models.py
+++ b/requests/models.py
@@ -110,14 +110,14 @@ def __init__(self,
# If no proxies are given, allow configuration by environment variables
# HTTP_PROXY and HTTPS_PROXY.
if not self.proxies and self.config.get('trust_env'):
- if 'HTTP_PROXY' in os.environ:
- self.proxies['http'] = os.environ['HTTP_PROXY']
- if 'HTTPS_PROXY' in os.environ:
- self.proxies['https'] = os.environ['HTTPS_PROXY']
+ if 'HTTP_PROXY' in os.environ:
+ self.proxies['http'] = os.environ['HTTP_PROXY']
+ if 'HTTPS_PROXY' in os.environ:
+ self.proxies['https'] = os.environ['HTTPS_PROXY']
- self.data, self._enc_data = self._encode_params(data)
- self.params, self._enc_params = self._encode_params(params)
- self.files, self._enc_files = self._encode_files(files)
+ self.data = data
+ self.params = params
+ self.files = files
#: :class:`Response <Response>` instance, containing
#: content and metadata of HTTP Response, once :attr:`sent <send>`.
@@ -309,19 +309,12 @@ def _encode_params(data):
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but abritrary
if parameters are supplied as a dict.
-
- If the data supplied contains parameters, encodes each parameter in it,
- and returns a list of tuples containing the encoded parameters, and a
- urlencoded version of that.
-
- Otherwise, assumes the data is already encoded appropriately, and
- returns it twice.
"""
if isinstance(data, bytes):
- return data, data
+ return data
if isinstance(data, str):
- return data, data
+ return data
elif hasattr(data, '__iter__'):
try:
dict(data)
@@ -335,14 +328,14 @@ def _encode_params(data):
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
- return result, urlencode(result, doseq=True)
+ return urlencode(result, doseq=True)
else:
- return data, data
+ return data
- def _encode_files(self,files):
+ def _encode_files(self, files):
if (not files) or isinstance(self.data, str):
- return None, None
+ return None
try:
fields = self.data.copy()
@@ -360,7 +353,7 @@ def _encode_files(self,files):
(body, content_type) = encode_multipart_formdata(fields)
- return files, (body, content_type)
+ return (body, content_type)
@property
def full_url(self):
@@ -385,7 +378,6 @@ def full_url(self):
if not path:
path = '/'
-
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
@@ -402,11 +394,12 @@ def full_url(self):
url = (urlunparse([scheme, netloc, path, params, query, fragment]))
- if self._enc_params:
+ enc_params = self._encode_params(self.params)
+ if enc_params:
if urlparse(url).query:
- url = '%s&%s' % (url, self._enc_params)
+ url = '%s&%s' % (url, enc_params)
else:
- url = '%s?%s' % (url, self._enc_params)
+ url = '%s?%s' % (url, enc_params)
if self.config.get('encode_uri', True):
url = requote_uri(url)
@@ -443,7 +436,7 @@ def register_hook(self, event, hook):
self.hooks[event].append(hook)
- def deregister_hook(self,event,hook):
+ def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
@@ -495,11 +488,11 @@ def send(self, anyway=False, prefetch=False):
# Multi-part file uploads.
if self.files:
- (body, content_type) = self._enc_files
+ (body, content_type) = self._encode_files(self.files)
else:
if self.data:
- body = self._enc_data
+ body = self._encode_params(self.data)
if isinstance(self.data, str):
content_type = None
else:
@@ -509,7 +502,6 @@ def send(self, anyway=False, prefetch=False):
if (content_type) and (not 'content-type' in self.headers):
self.headers['Content-Type'] = content_type
-
_p = urlparse(url)
proxy = self.proxies.get(_p.scheme)
@@ -793,7 +785,6 @@ def _detected_encoding(self):
except Exception:
pass
-
@property
def text(self):
"""Content of the response, in unicode.
@@ -840,7 +831,6 @@ def raise_for_status(self, allow_redirects=True):
http_error.response = self
raise http_error
-
elif (self.status_code >= 500) and (self.status_code < 600):
http_error = HTTPError('%s Server Error' % self.status_code)
http_error.response = self
| Previously, data, params, and files were encoded and stored in
Request.**init**, and subsequently put into service during
Request.send. The problem with this approach is that hooks and auth
callables need to be aware of the eager encoding, and if they touch the
originals, make sure to update the encoded versions.
A better approach is to only encode late in the sending process. This
way, hooks and auth callables can safely make changes without fear of
the old, encoded variant overriding it.
| https://api.github.com/repos/psf/requests/pulls/573 | 2012-05-02T21:11:19Z | 2012-05-02T21:19:56Z | 2012-05-02T21:19:56Z | 2021-09-08T15:01:01Z | 1,293 | psf/requests | 32,735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.