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
Faq updates
diff --git a/FAQ.md b/FAQ.md index 53e908266..e1d31afa8 100644 --- a/FAQ.md +++ b/FAQ.md @@ -73,3 +73,30 @@ You can adapt the finetuning script found [here](https://github.com/facebookrese **Q: Am I allowed a develop derivative models through fine-tuning based on Llama 2 for languages other than english? Is this a violation of the acceptable use policy?** A: Developers may fine-tune Llama 2 models for languages beyond English provided they comply with the Llama 2 Community License and the Acceptable Use Policy. + +**Q: What operating systems (OS) are officially supported?** + +A: +Linux is the only OS currently supported by this repo. + +**Q: I am getting the following error with download script. What should I do?** + + ``` + download.sh: 14: [[: not found + ``` + +A: +Make sure to run the command as follows + +``` +./download.sh +``` + +**Q: I am getting "Issue with the URL" as an error message. What do I do?** +``` + HTTP request sent, awaiting response... 400 Bad Request +``` + +A: +The issue occurs because of not copying the URL correctly. If you right click on the link and copy the link, the link may be copied with url defence wrapper. +To avoid this problem, please select the url manually and copy it
Adding OS and download questions to FAQs
https://api.github.com/repos/meta-llama/llama/pulls/851
2023-10-11T19:11:21Z
2023-10-11T19:18:13Z
2023-10-11T19:18:13Z
2023-10-11T19:18:14Z
339
meta-llama/llama
32,020
Fix handling of Lambda results
diff --git a/localstack/plugins.py b/localstack/plugins.py index 955f28f1645d2..5562d72a153a2 100644 --- a/localstack/plugins.py +++ b/localstack/plugins.py @@ -9,7 +9,7 @@ from localstack.services.kinesis import kinesis_listener, kinesis_starter from localstack.services.dynamodb import dynamodb_listener, dynamodb_starter from localstack.services.apigateway import apigateway_listener -from localstack.services.stepfunctions import stepfunctions_starter +from localstack.services.stepfunctions import stepfunctions_starter, stepfunctions_listener from localstack.services.cloudformation import cloudformation_listener, cloudformation_starter @@ -69,7 +69,8 @@ def register_localstack_plugins(): register_plugin(Plugin('cloudwatch', start=start_cloudwatch)) register_plugin(Plugin('stepfunctions', - start=stepfunctions_starter.start_stepfunctions)) + start=stepfunctions_starter.start_stepfunctions, + listener=stepfunctions_listener.UPDATE_STEPFUNCTIONS)) except Exception as e: print('Unable to register plugins: %s' % e) raise e diff --git a/localstack/services/awslambda/lambda_api.py b/localstack/services/awslambda/lambda_api.py index bdd1a18dc1b80..48360a0ce37e3 100644 --- a/localstack/services/awslambda/lambda_api.py +++ b/localstack/services/awslambda/lambda_api.py @@ -13,7 +13,7 @@ from io import BytesIO from datetime import datetime from six.moves import cStringIO as StringIO -from flask import Flask, Response, jsonify, request, make_response +from flask import Flask, Response, jsonify, request from localstack import config from localstack.services import generic_proxy from localstack.services.awslambda import lambda_executors @@ -570,7 +570,7 @@ def format_func_details(func_details, version=None, always_add_version=False): @app.before_request def before_request(): # fix to enable chunked encoding, as this is used by some Lambda clients - transfer_encoding = request.headers.get('Transfer-Encoding', None) + transfer_encoding = request.headers.get('Transfer-Encoding', '').lower() if transfer_encoding == 'chunked': request.environ['wsgi.input_terminated'] = True @@ -815,23 +815,48 @@ def invoke_function(function): # Default invocation type is RequestResponse invocation_type = request.environ.get('HTTP_X_AMZ_INVOCATION_TYPE', 'RequestResponse') + def _create_response(result, status_code=200): + """ Create the final response for the given invocation result """ + if isinstance(result, Response): + return result + details = { + 'StatusCode': status_code, + 'Payload': result, + 'Headers': {} + } + if isinstance(result, dict): + for key in ('StatusCode', 'Payload', 'FunctionError'): + if result.get(key): + details[key] = result[key] + # Try to parse parse payload as JSON + if isinstance(details['Payload'], (str, bytes)): + try: + details['Payload'] = json.loads(details['Payload']) + except Exception: + pass + # Set error headers + if details.get('FunctionError'): + details['Headers']['X-Amz-Function-Error'] = str(details['FunctionError']) + # Construct response object + response_obj = details['Payload'] + if isinstance(response_obj, (dict, list)): + # Assume this is a JSON response + response_obj = jsonify(response_obj) + else: + details['Headers']['Content-Type'] = 'text/plain' + return response_obj, details['StatusCode'], details['Headers'] + if invocation_type == 'RequestResponse': result = run_lambda(asynchronous=False, func_arn=arn, event=data, context={}, version=qualifier) - if isinstance(result, dict): - return jsonify(result) - if result: - return result - return make_response('', 200) + return _create_response(result) elif invocation_type == 'Event': run_lambda(asynchronous=True, func_arn=arn, event=data, context={}, version=qualifier) - return make_response('', 202) + return _create_response('', status_code=202) elif invocation_type == 'DryRun': # Assume the dry run always passes. - return make_response('', 204) - else: - return error_response('Invocation type not one of: RequestResponse, Event or DryRun', - code=400, - error_type='InvalidParameterValueException') + return _create_response('', status_code=204) + return error_response('Invocation type not one of: RequestResponse, Event or DryRun', + code=400, error_type='InvalidParameterValueException') @app.route('%s/event-source-mappings/' % PATH_ROOT, methods=['GET']) diff --git a/localstack/services/awslambda/lambda_executors.py b/localstack/services/awslambda/lambda_executors.py index 07e8e4b5abcab..04d0138a1e00e 100644 --- a/localstack/services/awslambda/lambda_executors.py +++ b/localstack/services/awslambda/lambda_executors.py @@ -5,7 +5,6 @@ import logging import threading import subprocess -# from datetime import datetime from multiprocessing import Process, Queue try: from shlex import quote as cmd_quote @@ -75,9 +74,15 @@ def run_lambda_executor(self, cmd, env_vars={}, asynchronous=False): log_output = 'Lambda executed asynchronously' else: result, log_output = process.communicate() - result = to_str(result) - log_output = to_str(log_output) + result = to_str(result).strip() + log_output = to_str(log_output).strip() return_code = process.returncode + # Note: The user's code may have been logging to stderr, in which case the logs + # will be part of the "result" variable here. Hence, make sure that we extract + # only the *last* line of "result" and consider anything above that as log output. + if '\n' in result: + additional_logs, _, result = result.rpartition('\n') + log_output += '\n%s' % additional_logs if return_code != 0: raise Exception('Lambda process returned error status code: %s. Output:\n%s' % @@ -149,7 +154,8 @@ def _execute(self, func_arn, func_details, event, context=None, version=None, as # lambci writes the Lambda result to stdout and logs to stderr, fetch it from there! LOG.debug('Running lambda cmd: %s' % cmd) result, log_output = self.run_lambda_executor(cmd, environment, asynchronous) - LOG.debug('Lambda result / log output:\n%s\n>%s' % (result.strip(), log_output.strip().replace('\n', '\n> '))) + log_formatted = log_output.strip().replace('\n', '\n> ') + LOG.debug('Lambda %s result / log output:\n%s\n>%s' % (func_arn, result.strip(), log_formatted)) return result, log_output diff --git a/localstack/services/stepfunctions/stepfunctions_listener.py b/localstack/services/stepfunctions/stepfunctions_listener.py index 259d487f8a77e..0ffb32e8df65a 100644 --- a/localstack/services/stepfunctions/stepfunctions_listener.py +++ b/localstack/services/stepfunctions/stepfunctions_listener.py @@ -6,10 +6,15 @@ class ProxyListenerStepFunctions(ProxyListener): - def forward_request(self, method, path, data, headers): - LOG.debug('StepFunctions request:', method, path, data) + # TODO: listener methods currently disabled + + def forward_request_DISABLED(self, method, path, data, headers): + LOG.debug('StepFunctions request: %s %s %s', method, path, data) return True + def return_response_DISABLED(self, method, path, data, headers, response): + LOG.debug('StepFunctions response: %s %s %s %s', method, path, response.status_code, response.content) + # instantiate listener UPDATE_STEPFUNCTIONS = ProxyListenerStepFunctions() diff --git a/requirements.txt b/requirements.txt index 533120547a99a..d2a8d5379b907 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ docopt>=0.6.2 elasticsearch==6.2.0 flake8>=3.6.0 flake8-quotes>=0.11.0 -flask==0.12.4 +flask==1.0.2 flask-cors==3.0.3 flask_swagger==0.2.12 jsonpath-rw==1.4.0 diff --git a/tests/integration/test_stepfunction.py b/tests/integration/test_stepfunction.py index 85e83b383515f..0a3432470c91f 100644 --- a/tests/integration/test_stepfunction.py +++ b/tests/integration/test_stepfunction.py @@ -9,13 +9,19 @@ THIS_FOLDER = os.path.dirname(os.path.realpath(__file__)) TEST_LAMBDA_PYTHON = os.path.join(THIS_FOLDER, 'lambdas', 'lambda_environment.py') -TEST_LAMBDA_NAME = 'lambda_sfn_1' +TEST_LAMBDA_NAME_1 = 'lambda_sfn_1' +TEST_LAMBDA_NAME_2 = 'lambda_sfn_2' STATE_MACHINE_NAME = 'test_sm_1' STATE_MACHINE_DEF = { 'Comment': 'Hello World example', 'StartAt': 'step1', 'States': { 'step1': { + 'Type': 'Task', + 'Resource': '__tbd__', + 'Next': 'step2' + }, + 'step2': { 'Type': 'Task', 'Resource': '__tbd__', 'End': True @@ -38,14 +44,20 @@ def setUpClass(cls): runtime=LAMBDA_RUNTIME_PYTHON36 ) testutil.create_lambda_function( - func_name=TEST_LAMBDA_NAME, + func_name=TEST_LAMBDA_NAME_1, + zip_file=zip_file, + runtime=LAMBDA_RUNTIME_PYTHON36 + ) + testutil.create_lambda_function( + func_name=TEST_LAMBDA_NAME_2, zip_file=zip_file, runtime=LAMBDA_RUNTIME_PYTHON36 ) @classmethod def tearDownClass(cls): - cls.lambda_client.delete_function(FunctionName=TEST_LAMBDA_NAME) + cls.lambda_client.delete_function(FunctionName=TEST_LAMBDA_NAME_1) + cls.lambda_client.delete_function(FunctionName=TEST_LAMBDA_NAME_2) def test_create_run_state_machine(self): state_machines_before = self.sfn_client.list_state_machines()['stateMachines'] @@ -53,8 +65,10 @@ def test_create_run_state_machine(self): # create state machine role_arn = aws_stack.role_arn('sfn_role') definition = clone(STATE_MACHINE_DEF) - lambda_arn = aws_stack.lambda_function_arn(TEST_LAMBDA_NAME) - definition['States']['step1']['Resource'] = lambda_arn + lambda_arn_1 = aws_stack.lambda_function_arn(TEST_LAMBDA_NAME_1) + lambda_arn_2 = aws_stack.lambda_function_arn(TEST_LAMBDA_NAME_2) + definition['States']['step1']['Resource'] = lambda_arn_1 + definition['States']['step2']['Resource'] = lambda_arn_2 definition = json.dumps(definition) result = self.sfn_client.create_state_machine( name=STATE_MACHINE_NAME, definition=definition, roleArn=role_arn) @@ -70,10 +84,11 @@ def test_create_run_state_machine(self): self.assertTrue(result.get('executionArn')) def check_invocations(): - assert lambda_api.LAMBDA_EXECUTOR.function_invoke_times[lambda_arn] + assert lambda_api.LAMBDA_EXECUTOR.function_invoke_times[lambda_arn_1] + assert lambda_api.LAMBDA_EXECUTOR.function_invoke_times[lambda_arn_2] # assert that the lambda has been invoked by the SM execution - retry(check_invocations, sleep=0.6, retries=15) + retry(check_invocations, sleep=0.7, retries=20) # clean up self.sfn_client.delete_state_machine(stateMachineArn=sm_arn)
Fix handling of Lambda invocation results. * Update `flask` to latest version (fixes an issue with chunked transfer encoding in Lambda API) * Fix Step Functions integration test (previously were hanging as soon as more than one state was defined in the state machine) * Return `X-Amz-Function-Error` header in Lambda API
https://api.github.com/repos/localstack/localstack/pulls/1151
2019-02-26T12:16:32Z
2019-02-26T15:09:51Z
2019-02-26T15:09:51Z
2019-02-26T15:35:29Z
2,846
localstack/localstack
28,489
Small fix in description of startproject arguments
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst index 8de858f8a32..dc8067d7ece 100644 --- a/docs/topics/commands.rst +++ b/docs/topics/commands.rst @@ -187,7 +187,7 @@ startproject Creates a new Scrapy project named ``project_name``, under the ``project_dir`` directory. -If ``project_dir`` wasn't specified, ``project_dir`` will be the same as ``myproject``. +If ``project_dir`` wasn't specified, ``project_dir`` will be the same as ``project_name``. Usage example::
https://api.github.com/repos/scrapy/scrapy/pulls/2866
2017-07-30T20:09:20Z
2017-07-31T11:03:50Z
2017-07-31T11:03:50Z
2017-08-01T11:18:23Z
142
scrapy/scrapy
34,312
Add FreeBSD port/package to documentation (Usage)
diff --git a/docs/using.rst b/docs/using.rst index eb8c3159532..603f38a9b2f 100644 --- a/docs/using.rst +++ b/docs/using.rst @@ -86,8 +86,15 @@ in ``/etc/letsencrypt/live`` on the host. .. _`install Docker`: https://docs.docker.com/userguide/ -Distro packages ---------------- +Operating System Packages +-------------------------- + +**FreeBSD** + + * Port: ``cd /usr/ports/security/py-letsencrypt && make install clean`` + * Package: ``pkg install py27-letsencrypt`` + +**Other Operating Systems** Unfortunately, this is an ongoing effort. If you'd like to package Let's Encrypt client for your distribution of choice please have a
The FreeBSD port for letsencrypt was [recently committed](https://svnweb.freebsd.org/changeset/ports/400885). Update the letsencrypt documentation (usage page) with user instructions for how to install it via ports or packages. - Rename "Distro's" to "Operating Systems" - Add instructions for FreeBSD port and package installation - Add "Other Operating System" header for the instructions to create packages
https://api.github.com/repos/certbot/certbot/pulls/1382
2015-11-06T08:56:27Z
2015-11-07T00:00:17Z
2015-11-07T00:00:17Z
2016-05-06T19:22:06Z
183
certbot/certbot
1,350
avoid crash if `checkpoint['epoch']` is undefined and logging enabled
diff --git a/timm/models/_helpers.py b/timm/models/_helpers.py index 530da0e1b2..079a4ddaee 100644 --- a/timm/models/_helpers.py +++ b/timm/models/_helpers.py @@ -136,8 +136,8 @@ def resume_checkpoint( if 'version' in checkpoint and checkpoint['version'] > 1: resume_epoch += 1 # start at the next epoch, old checkpoints incremented before save - if log_info: - _logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, checkpoint['epoch'])) + if log_info: + _logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, checkpoint['epoch'])) else: model.load_state_dict(checkpoint) if log_info:
https://api.github.com/repos/huggingface/pytorch-image-models/pulls/2002
2023-10-22T17:12:19Z
2023-10-23T04:36:24Z
2023-10-23T04:36:24Z
2023-10-23T07:07:31Z
178
huggingface/pytorch-image-models
16,363
Add `init_command` parameter to `MySqlHook`
diff --git a/airflow/providers/mysql/hooks/mysql.py b/airflow/providers/mysql/hooks/mysql.py index fa011ed35bc10..3fe86652cc881 100644 --- a/airflow/providers/mysql/hooks/mysql.py +++ b/airflow/providers/mysql/hooks/mysql.py @@ -58,6 +58,7 @@ class MySqlHook(DbApiHook): :param schema: The MySQL database schema to connect to. :param connection: The :ref:`MySQL connection id <howto/connection:mysql>` used for MySQL credentials. :param local_infile: Boolean flag determining if local_infile should be used + :param init_command: Initial command to issue to MySQL server upon connection """ conn_name_attr = "mysql_conn_id" @@ -71,6 +72,7 @@ def __init__(self, *args, **kwargs) -> None: self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) self.local_infile = kwargs.pop("local_infile", False) + self.init_command = kwargs.pop("init_command", None) def set_autocommit(self, conn: MySQLConnectionTypes, autocommit: bool) -> None: """ @@ -144,6 +146,8 @@ def _get_conn_config_mysql_client(self, conn: Connection) -> dict: conn_config["unix_socket"] = conn.extra_dejson["unix_socket"] if self.local_infile: conn_config["local_infile"] = 1 + if self.init_command: + conn_config["init_command"] = self.init_command return conn_config def _get_conn_config_mysql_connector_python(self, conn: Connection) -> dict: @@ -157,6 +161,8 @@ def _get_conn_config_mysql_connector_python(self, conn: Connection) -> dict: if self.local_infile: conn_config["allow_local_infile"] = True + if self.init_command: + conn_config["init_command"] = self.init_command # Ref: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html for key, value in conn.extra_dejson.items(): if key.startswith("ssl_"): diff --git a/tests/providers/mysql/hooks/test_mysql.py b/tests/providers/mysql/hooks/test_mysql.py index 81773e9e3f1ea..2b6c81df5d4ab 100644 --- a/tests/providers/mysql/hooks/test_mysql.py +++ b/tests/providers/mysql/hooks/test_mysql.py @@ -181,6 +181,15 @@ def test_get_conn_rds_iam(self, mock_client, mock_connect): read_default_group="enable-cleartext-plugin", ) + @mock.patch("MySQLdb.connect") + def test_get_conn_init_command(self, mock_connect): + self.db_hook.init_command = "SET time_zone = '+00:00';" + self.db_hook.get_conn() + assert mock_connect.call_count == 1 + args, kwargs = mock_connect.call_args + assert args == () + assert kwargs["init_command"] == "SET time_zone = '+00:00';" + class MockMySQLConnectorConnection: DEFAULT_AUTOCOMMIT = "default" diff --git a/tests/providers/mysql/hooks/test_mysql_connector_python.py b/tests/providers/mysql/hooks/test_mysql_connector_python.py index d4c9ffc0b39cf..5d2f0d1613b35 100644 --- a/tests/providers/mysql/hooks/test_mysql_connector_python.py +++ b/tests/providers/mysql/hooks/test_mysql_connector_python.py @@ -79,3 +79,14 @@ def test_get_ssl_mode(self, mock_connect): args, kwargs = mock_connect.call_args assert args == () assert kwargs["ssl_disabled"] == 1 + + @mock.patch("mysql.connector.connect") + def test_get_conn_init_command(self, mock_connect): + extra_dict = self.connection.extra_dejson + self.connection.extra = json.dumps(extra_dict) + self.db_hook.init_command = "SET time_zone = '+00:00';" + self.db_hook.get_conn() + assert mock_connect.call_count == 1 + args, kwargs = mock_connect.call_args + assert args == () + assert kwargs["init_command"] == "SET time_zone = '+00:00';"
This allows the addition of `init_command` as a `MySqlHook` parameter. `init_command` is a connection argument to set an initial command to issue to the MySQL server upon connection. It is available as both a `mysqlclient` connection attribute (https://mysqlclient.readthedocs.io/user_guide.html?highlight=init_command#functions-and-attributes) and a `mysql-connector-python` connection attribute (https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html). For example, to set the session's `time_zone` to UTC you can set in a `MySqlHook` an `init_command` parameter as shown: ```python MySqlHook(init_command="SET time_zone = '+00:00';") ``` or in a SQL operator shown using `hook_params` (which should return "+00:00"): ```python SQLExecuteQueryOperator( task_id="check_time_zone", conn_id="mysql_default", hook_params={"init_command": "SET time_zone = '+00:00';"}, sql=r"""SELECT @@SESSION.time_zone;""", autocommit=True, show_return_value_in_logs=True ) ``` closes: #33300 <!-- 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/33359
2023-08-13T01:51:06Z
2023-08-18T05:58:51Z
2023-08-18T05:58:51Z
2023-08-19T08:36:33Z
941
apache/airflow
14,050
Button-enable cars: common functions for button events
diff --git a/selfdrive/car/__init__.py b/selfdrive/car/__init__.py index 7bb91c40f71b4a..806a060f974de0 100644 --- a/selfdrive/car/__init__.py +++ b/selfdrive/car/__init__.py @@ -1,11 +1,40 @@ # functions common among cars +import capnp + from cereal import car from common.numpy_fast import clip -from typing import Dict +from typing import Dict, List # kg of standard extra cargo to count for drive, gas, etc... STD_CARGO_KG = 136. +ButtonType = car.CarState.ButtonEvent.Type +EventName = car.CarEvent.EventName + + +def create_button_event(cur_but: int, prev_but: int, buttons_dict: Dict[int, capnp.lib.capnp._EnumModule], + unpressed: int = 0) -> capnp.lib.capnp._DynamicStructBuilder: + if cur_but != unpressed: + be = car.CarState.ButtonEvent(pressed=True) + but = cur_but + else: + be = car.CarState.ButtonEvent(pressed=False) + but = prev_but + be.type = buttons_dict.get(but, ButtonType.unknown) + return be + + +def create_button_enable_events(buttonEvents: capnp.lib.capnp._DynamicListBuilder) -> List[int]: + events = [] + for b in buttonEvents: + # do enable on both accel and decel buttons + if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: + events.append(EventName.buttonEnable) + # do disable on button down + if b.type == ButtonType.cancel and b.pressed: + events.append(EventName.buttonCancel) + return events + def gen_empty_fingerprint(): return {i: {} for i in range(0, 4)} diff --git a/selfdrive/car/gm/interface.py b/selfdrive/car/gm/interface.py index d00708c336ba0f..b4265fc0bd0fc8 100755 --- a/selfdrive/car/gm/interface.py +++ b/selfdrive/car/gm/interface.py @@ -3,12 +3,15 @@ from math import fabs from common.conversions import Conversions as CV -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, create_button_enable_events, create_button_event, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config from selfdrive.car.gm.values import CAR, CruiseButtons, CarControllerParams from selfdrive.car.interfaces import CarInterfaceBase ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName +BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise, + CruiseButtons.MAIN: ButtonType.altButton3, CruiseButtons.CANCEL: ButtonType.cancel} + class CarInterface(CarInterfaceBase): @staticmethod @@ -159,29 +162,14 @@ def _update(self, c): ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - buttonEvents = [] - if self.CS.cruise_buttons != self.CS.prev_cruise_buttons and self.CS.prev_cruise_buttons != CruiseButtons.INIT: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons != CruiseButtons.UNPRESS: - be.pressed = True - but = self.CS.cruise_buttons - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == CruiseButtons.RES_ACCEL: - if not (ret.cruiseState.enabled and ret.standstill): - be.type = ButtonType.accelCruise # Suppress resume button if we're resuming from stop so we don't adjust speed. - elif but == CruiseButtons.DECEL_SET: - be.type = ButtonType.decelCruise - elif but == CruiseButtons.CANCEL: - be.type = ButtonType.cancel - elif but == CruiseButtons.MAIN: - be.type = ButtonType.altButton3 - buttonEvents.append(be) - - ret.buttonEvents = buttonEvents + be = create_button_event(self.CS.cruise_buttons, self.CS.prev_cruise_buttons, BUTTONS_DICT, CruiseButtons.UNPRESS) + + # Suppress resume button if we're resuming from stop so we don't adjust speed. + if be.type == ButtonType.accelCruise and (ret.cruiseState.enabled and ret.standstill): + be.type = ButtonType.unknown + + ret.buttonEvents = [be] events = self.create_common_events(ret, pcm_enable=False) @@ -193,13 +181,7 @@ def _update(self, c): events.add(car.CarEvent.EventName.belowSteerSpeed) # handle button presses - for b in ret.buttonEvents: - # do enable on both accel and decel buttons - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - events.add(EventName.buttonEnable) - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) + events.events.extend(create_button_enable_events(ret.buttonEvents)) ret.events = events.to_msg() diff --git a/selfdrive/car/honda/interface.py b/selfdrive/car/honda/interface.py index 265175d94038ac..5b97b3389f6e75 100755 --- a/selfdrive/car/honda/interface.py +++ b/selfdrive/car/honda/interface.py @@ -4,7 +4,7 @@ from common.conversions import Conversions as CV from common.numpy_fast import interp from selfdrive.car.honda.values import CarControllerParams, CruiseButtons, HondaFlags, CAR, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL -from selfdrive.car import STD_CARGO_KG, CivicParams, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, CivicParams, create_button_enable_events, create_button_event, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase from selfdrive.car.disable_ecu import disable_ecu @@ -12,6 +12,8 @@ ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName TransmissionType = car.CarParams.TransmissionType +BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise, + CruiseButtons.MAIN: ButtonType.altButton3, CruiseButtons.CANCEL: ButtonType.cancel} class CarInterface(CarInterfaceBase): @@ -334,37 +336,11 @@ def _update(self, c): buttonEvents = [] if self.CS.cruise_buttons != self.CS.prev_cruise_buttons: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons != 0: - be.pressed = True - but = self.CS.cruise_buttons - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == CruiseButtons.RES_ACCEL: - be.type = ButtonType.accelCruise - elif but == CruiseButtons.DECEL_SET: - be.type = ButtonType.decelCruise - elif but == CruiseButtons.CANCEL: - be.type = ButtonType.cancel - elif but == CruiseButtons.MAIN: - be.type = ButtonType.altButton3 - buttonEvents.append(be) + buttonEvents.append(create_button_event(self.CS.cruise_buttons, self.CS.prev_cruise_buttons, BUTTONS_DICT)) if self.CS.cruise_setting != self.CS.prev_cruise_setting: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_setting != 0: - be.pressed = True - but = self.CS.cruise_setting - else: - be.pressed = False - but = self.CS.prev_cruise_setting - if but == 1: - be.type = ButtonType.altButton1 - # TODO: more buttons? - buttonEvents.append(be) + buttonEvents.append(create_button_event(self.CS.cruise_setting, self.CS.prev_cruise_setting, {1: ButtonType.altButton1})) + ret.buttonEvents = buttonEvents # events @@ -391,16 +367,7 @@ def _update(self, c): events.add(EventName.manualRestart) # handle button presses - for b in ret.buttonEvents: - - # do enable on both accel and decel buttons - if not self.CP.pcmCruise: - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - events.add(EventName.buttonEnable) - - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) + events.events.extend(create_button_enable_events(ret.buttonEvents)) ret.events = events.to_msg() diff --git a/selfdrive/car/hyundai/interface.py b/selfdrive/car/hyundai/interface.py index b4dc26c87acd8e..7299e29ba8cb87 100644 --- a/selfdrive/car/hyundai/interface.py +++ b/selfdrive/car/hyundai/interface.py @@ -4,7 +4,7 @@ from common.conversions import Conversions as CV from selfdrive.car.hyundai.values import CAR, DBC, HDA2_CAR, EV_CAR, HYBRID_CAR, LEGACY_SAFETY_MODE_CAR, Buttons, CarControllerParams from selfdrive.car.hyundai.radar_interface import RADAR_START_ADDR -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, create_button_enable_events, create_button_event, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase from selfdrive.car.disable_ecu import disable_ecu from selfdrive.controls.lib.latcontrol_torque import set_torque_tune @@ -12,6 +12,8 @@ ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName ENABLE_BUTTONS = (Buttons.RES_ACCEL, Buttons.SET_DECEL, Buttons.CANCEL) +BUTTONS_DICT = {Buttons.RES_ACCEL: ButtonType.accelCruise, Buttons.SET_DECEL: ButtonType.decelCruise, + Buttons.GAP_DIST: ButtonType.gapAdjustCruise, Buttons.CANCEL: ButtonType.cancel} class CarInterface(CarInterfaceBase): @@ -338,37 +340,10 @@ def _update(self, c): if self.CS.brake_error: events.add(EventName.brakeUnavailable) - if self.CS.CP.openpilotLongitudinalControl: - buttonEvents = [] - - if self.CS.cruise_buttons[-1] != self.CS.prev_cruise_buttons: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons[-1] != 0: - be.pressed = True - but = self.CS.cruise_buttons[-1] - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == Buttons.RES_ACCEL: - be.type = ButtonType.accelCruise - elif but == Buttons.SET_DECEL: - be.type = ButtonType.decelCruise - elif but == Buttons.GAP_DIST: - be.type = ButtonType.gapAdjustCruise - elif but == Buttons.CANCEL: - be.type = ButtonType.cancel - buttonEvents.append(be) - - ret.buttonEvents = buttonEvents - - for b in ret.buttonEvents: - # do enable on both accel and decel buttons - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - events.add(EventName.buttonEnable) - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) + if self.CS.CP.openpilotLongitudinalControl and self.CS.cruise_buttons[-1] != self.CS.prev_cruise_buttons: + ret.buttonEvents = [create_button_event(self.CS.cruise_buttons[-1], self.CS.prev_cruise_buttons, BUTTONS_DICT)] + + events.events.extend(create_button_enable_events(ret.buttonEvents)) # low speed steer alert hysteresis logic (only for cars with steer cut off above 10 m/s) if ret.vEgo < (self.CP.minSteerSpeed + 2.) and self.CP.minSteerSpeed > 10.:
https://api.github.com/repos/commaai/openpilot/pulls/24678
2022-05-29T21:00:11Z
2022-06-01T19:03:34Z
2022-06-01T19:03:34Z
2022-06-01T19:03:35Z
3,032
commaai/openpilot
9,101
docs: bump version number to 2.3.1, add changelog
diff --git a/fooocus_version.py b/fooocus_version.py index a4b8895b3..b20501966 100644 --- a/fooocus_version.py +++ b/fooocus_version.py @@ -1 +1 @@ -version = '2.3.0' +version = '2.3.1' diff --git a/update_log.md b/update_log.md index 4e22db0a4..62c4882bc 100644 --- a/update_log.md +++ b/update_log.md @@ -1,3 +1,10 @@ +# [2.3.1](https://github.com/lllyasviel/Fooocus/releases/tag/2.3.1) + +* Remove positive prompt from anime prefix to not reset prompt after switching presets +* Fix image number being reset to 1 when switching preset, now doesn't reset anymore +* Fix outpainting dimension calculation when extending left/right +* Fix LoRA compatibility for LoRAs in a1111 metadata scheme + # [2.3.0](https://github.com/lllyasviel/Fooocus/releases/tag/2.3.0) * Add performance "lightning" (based on [SDXL-Lightning 4 step LoRA](https://huggingface.co/ByteDance/SDXL-Lightning/blob/main/sdxl_lightning_4step_lora.safetensors))
https://api.github.com/repos/lllyasviel/Fooocus/pulls/2616
2024-03-23T15:56:10Z
2024-03-23T15:57:12Z
2024-03-23T15:57:11Z
2024-03-23T15:57:12Z
308
lllyasviel/Fooocus
7,074
ref(onboarding): fix cache when platforms are the same
diff --git a/static/app/components/onboardingWizard/useOnboardingDocs.tsx b/static/app/components/onboardingWizard/useOnboardingDocs.tsx index 99d1c97c4550d..29ddcb4e1a9b4 100644 --- a/static/app/components/onboardingWizard/useOnboardingDocs.tsx +++ b/static/app/components/onboardingWizard/useOnboardingDocs.tsx @@ -1,4 +1,4 @@ -import {useEffect, useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import * as Sentry from '@sentry/react'; import {loadDocs} from 'sentry/actionCreators/projects'; @@ -17,44 +17,44 @@ type Options = { }; function useOnboardingDocs({docKeys, isPlatformSupported, project}: Options) { - const organization = useOrganization(); const api = useApi(); + const organization = useOrganization(); + + const loadingDocsRef = useRef<Record<string, boolean>>(INITIAL_LOADING_DOCS); + const docContentsRef = useRef<Record<string, string>>(INITIAL_DOC_CONTENTS); - const [loadingDocs, setLoadingDocs] = - useState<Record<string, boolean>>(INITIAL_LOADING_DOCS); const [docContents, setDocContents] = useState<Record<string, string>>(INITIAL_DOC_CONTENTS); - const currentPlatform = project.platform - ? platforms.find(p => p.id === project.platform) - : undefined; + docContentsRef.current = docContents; useEffect(() => { if (!isPlatformSupported) { - if (loadingDocs !== INITIAL_LOADING_DOCS) { - setLoadingDocs(INITIAL_LOADING_DOCS); + if (loadingDocsRef.current !== INITIAL_LOADING_DOCS) { + loadingDocsRef.current = INITIAL_LOADING_DOCS; } - if (docContents !== INITIAL_DOC_CONTENTS) { + if (docContentsRef.current !== INITIAL_DOC_CONTENTS) { setDocContents(INITIAL_DOC_CONTENTS); } - return; + return undefined; } + let cancelRequest = false; + docKeys.forEach(docKey => { - if (docKey in loadingDocs) { + if (docKey in loadingDocsRef.current) { // If a documentation content is loading, we should not attempt to fetch it again. // otherwise, if it's not loading, we should only fetch at most once. // Any errors that occurred will be captured via Sentry. return; } - const setLoadingDoc = (loadingState: boolean) => - setLoadingDocs(prevState => { - return { - ...prevState, - [docKey]: loadingState, - }; - }); + const setLoadingDoc = (loadingState: boolean) => { + loadingDocsRef.current = { + ...loadingDocsRef.current, + [docKey]: loadingState, + }; + }; const setDocContent = (docContent: string | undefined) => setDocContents(prevState => { @@ -80,25 +80,33 @@ function useOnboardingDocs({docKeys, isPlatformSupported, project}: Options) { platform: docKey as any, }) .then(({html}) => { - setDocContent(html as string); + if (cancelRequest) { + return; + } setLoadingDoc(false); + setDocContent(html as string); }) .catch(error => { + if (cancelRequest) { + return; + } Sentry.captureException(error); - setDocContent(undefined); setLoadingDoc(false); + setDocContent(undefined); }); }); - }, [ - currentPlatform, - docKeys, - isPlatformSupported, - api, - loadingDocs, - organization.slug, - project.slug, - docContents, - ]); + + return () => { + cancelRequest = true; + for (const key of docKeys) { + delete loadingDocsRef.current[key]; + } + }; + }, [docKeys, isPlatformSupported, api, organization.slug, project]); + + const currentPlatform = project.platform + ? platforms.find(p => p.id === project.platform) + : undefined; if (!currentPlatform || !isPlatformSupported) { return { @@ -108,23 +116,20 @@ function useOnboardingDocs({docKeys, isPlatformSupported, project}: Options) { }; } - const isLoading = Boolean( - docKeys?.some(key => { - if (key in loadingDocs) { - return !!loadingDocs[key]; + const isLoading = + docKeys && + docKeys.some(key => { + if (key in loadingDocsRef.current) { + return !!loadingDocsRef.current[key]; } return true; - }) - ); - - const hasOnboardingContents = Boolean( - docKeys?.every(key => typeof docContents[key] === 'string') - ); + }); return { docKeys, isLoading, - hasOnboardingContents, + hasOnboardingContents: + docKeys && docKeys.every(key => typeof docContents[key] === 'string'), docContents, }; } diff --git a/static/app/components/performanceOnboarding/sidebar.tsx b/static/app/components/performanceOnboarding/sidebar.tsx index 8097cb0815feb..50451c1dd1f50 100644 --- a/static/app/components/performanceOnboarding/sidebar.tsx +++ b/static/app/components/performanceOnboarding/sidebar.tsx @@ -1,4 +1,4 @@ -import {Fragment, useEffect, useState} from 'react'; +import {Fragment, useEffect, useMemo, useState} from 'react'; import styled from '@emotion/styled'; import HighlightTopRightPattern from 'sentry-images/pattern/highlight-top-right.svg'; @@ -182,7 +182,10 @@ function OnboardingContent({currentProject}: {currentProject: Project}) { ? platforms.find(p => p.id === currentProject.platform) : undefined; - const docKeys = currentPlatform ? generateDocKeys(currentPlatform.id) : []; + const docKeys = useMemo(() => { + return currentPlatform ? generateDocKeys(currentPlatform.id) : []; + }, [currentPlatform]); + const {docContents, isLoading, hasOnboardingContents} = useOnboardingDocs({ project: currentProject, docKeys, diff --git a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingSidebar.tsx b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingSidebar.tsx index 2462f812209ba..ca703384591f3 100644 --- a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingSidebar.tsx +++ b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingSidebar.tsx @@ -214,9 +214,13 @@ function OnboardingContent({ }, [currentProject, previousProject]); const docKeysMap = useMemo(() => makeDocKeyMap(currentPlatform?.id), [currentPlatform]); + const docKeys = useMemo( + () => (docKeysMap ? Object.values(docKeysMap) : []), + [docKeysMap] + ); const {docContents, isLoading, hasOnboardingContents} = useOnboardingDocs({ - docKeys: docKeysMap ? Object.values(docKeysMap) : [], + docKeys, project: currentProject, isPlatformSupported: isSupported, }); diff --git a/static/app/components/replaysOnboarding/sidebar.tsx b/static/app/components/replaysOnboarding/sidebar.tsx index fecf2af34b024..be70a2c9c4313 100644 --- a/static/app/components/replaysOnboarding/sidebar.tsx +++ b/static/app/components/replaysOnboarding/sidebar.tsx @@ -154,7 +154,9 @@ function OnboardingContent({currentProject}: {currentProject: Project}) { ? platforms.find(p => p.id === currentProject.platform) : undefined; - const docKeys = currentPlatform ? generateDocKeys(currentPlatform.id) : []; + const docKeys = useMemo(() => { + return currentPlatform ? generateDocKeys(currentPlatform.id) : []; + }, [currentPlatform]); const {docContents, isLoading, hasOnboardingContents} = useOnboardingDocs({ project: currentProject,
The documentation needs to be re-fetched when the project changes so that they dsn in the response is updated. Fixes https://github.com/getsentry/sentry/issues/59965
https://api.github.com/repos/getsentry/sentry/pulls/60059
2023-11-15T23:10:03Z
2023-11-27T17:24:35Z
2023-11-27T17:24:35Z
2023-12-13T00:02:46Z
1,852
getsentry/sentry
44,481
youku: warn about segments skipped due to paywall
diff --git a/src/you_get/extractors/youku.py b/src/you_get/extractors/youku.py index 65fcbc2716..ff23e70652 100644 --- a/src/you_get/extractors/youku.py +++ b/src/you_get/extractors/youku.py @@ -295,9 +295,14 @@ def extract(self, **kwargs): for piece in pieces: segs = piece['segs'] streamfileid = piece['fileid'] - for no in range(0, len(segs)): + seg_count = len(segs) + for no in range(0, seg_count): k = segs[no]['key'] - if k == -1: break # we hit the paywall; stop here + if k == -1: + # we hit the paywall; stop here + log.w('Skipping %d out of %d segments due to paywall' % + (seg_count - no, seg_count)) + break fileid, ep = self.__class__.generate_ep(self, no, streamfileid, sid, token) q = parse.urlencode(dict(
This is especially helpful in cases where the entire video is blocked by paywall, resulting in an unhelpful error message ``` you-get: [Failed] Cannot extract video source. ``` I spent quite a few minutes debugging a URL like that,^ which could have been saved by the message ``` you-get: Skipping 27 out of 27 segments due to paywall ``` added by this commit. ^The video is completely region-blocked where I am, so I didn't know it was behind a paywall before feeding it to you-get — with a Mainland-based extractor proxy of course. That should explain my initial confusion — it would have been obvious if I checked its availability in a Unblock Youku-enabled browser session first. Still, more self-contained information should make you-get better. <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/soimort/you-get/1744) <!-- Reviewable:end -->
https://api.github.com/repos/soimort/you-get/pulls/1744
2017-03-09T01:58:58Z
2017-04-09T14:29:30Z
2017-04-09T14:29:30Z
2017-04-09T15:38:07Z
266
soimort/you-get
21,291
Move chat UI elements to the right on desktop
diff --git a/css/main.css b/css/main.css index 6c65854636..b4ec0589c3 100644 --- a/css/main.css +++ b/css/main.css @@ -689,6 +689,15 @@ div.svelte-362y77>*, div.svelte-362y77>.form>* { max-width: 300px; margin-left: calc(-0.5*(var(--document-width) - 880px - 14px - 16px * 2)); } + + #chat-controls { + position: absolute; + top: 16px; + right: 0; + width: calc(0.5*(var(--document-width) - 880px - 120px - 16px*2)); + max-width: 300px; + margin-right: calc(-0.5*(var(--document-width) - 880px - 14px - 16px * 2)); + } } /* ---------------------------------------------- diff --git a/modules/ui_chat.py b/modules/ui_chat.py index 7576628d5b..ad4a4f0fda 100644 --- a/modules/ui_chat.py +++ b/modules/ui_chat.py @@ -77,12 +77,16 @@ def create_ui(): shared.gradio['rename_to-confirm'] = gr.Button('Confirm', visible=False, elem_classes='refresh-button') shared.gradio['rename_to-cancel'] = gr.Button('Cancel', visible=False, elem_classes='refresh-button') - with gr.Row(): - shared.gradio['start_with'] = gr.Textbox(label='Start reply with', placeholder='Sure thing!', value=shared.settings['start_with']) + with gr.Row(elem_id='chat-controls', elem_classes=['pretty_scrollbar']): + with gr.Column(): + with gr.Row(): + shared.gradio['start_with'] = gr.Textbox(label='Start reply with', placeholder='Sure thing!', value=shared.settings['start_with'], elem_classes=['add_scrollbar']) - with gr.Row(): - shared.gradio['mode'] = gr.Radio(choices=['chat', 'chat-instruct', 'instruct'], value='chat', label='Mode', info='Defines how the chat prompt is generated. In instruct and chat-instruct modes, the instruction template selected under Parameters > Instruction template must match the current model.', elem_id='chat-mode') - shared.gradio['chat_style'] = gr.Dropdown(choices=utils.get_available_chat_styles(), label='Chat style', value=shared.settings['chat_style'], visible=shared.settings['mode'] != 'instruct') + with gr.Row(): + shared.gradio['mode'] = gr.Radio(choices=['chat', 'chat-instruct', 'instruct'], value='chat', label='Mode', info='Defines how the chat prompt is generated. In instruct and chat-instruct modes, the instruction template selected under Parameters > Instruction template must match the current model.', elem_id='chat-mode') + + with gr.Row(): + shared.gradio['chat_style'] = gr.Dropdown(choices=utils.get_available_chat_styles(), label='Chat style', value=shared.settings['chat_style'], visible=shared.settings['mode'] != 'instruct') def create_chat_settings_ui():
Preview: ![print](https://github.com/oobabooga/text-generation-webui/assets/112222186/8f77abd5-c113-4793-9c35-97b65384bca5)
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/5538
2024-02-18T17:28:35Z
2024-02-18T17:32:05Z
2024-02-18T17:32:05Z
2024-02-25T17:26:05Z
704
oobabooga/text-generation-webui
25,980
Add support for specifying source_address to ClientNetwork.
diff --git a/acme/acme/client.py b/acme/acme/client.py index 7807f0eceea..d4f5a4787e2 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -12,7 +12,9 @@ import josepy as jose import OpenSSL import re +from requests_toolbelt.adapters.source import SourceAddressAdapter import requests +from requests.adapters import HTTPAdapter import sys from acme import crypto_util @@ -857,9 +859,12 @@ class ClientNetwork(object): # pylint: disable=too-many-instance-attributes :param bool verify_ssl: Whether to verify certificates on SSL connections. :param str user_agent: String to send as User-Agent header. :param float timeout: Timeout for requests. + :param source_address: Optional source address to bind to when making requests. + :type source_address: str or tuple(str, int) """ def __init__(self, key, account=None, alg=jose.RS256, verify_ssl=True, - user_agent='acme-python', timeout=DEFAULT_NETWORK_TIMEOUT): + user_agent='acme-python', timeout=DEFAULT_NETWORK_TIMEOUT, + source_address=None): # pylint: disable=too-many-arguments self.key = key self.account = account @@ -869,6 +874,13 @@ def __init__(self, key, account=None, alg=jose.RS256, verify_ssl=True, self.user_agent = user_agent self.session = requests.Session() self._default_timeout = timeout + adapter = HTTPAdapter() + + if source_address is not None: + adapter = SourceAddressAdapter(source_address) + + self.session.mount("http://", adapter) + self.session.mount("https://", adapter) def __del__(self): # Try to close the session, but don't show exceptions to the diff --git a/acme/acme/client_test.py b/acme/acme/client_test.py index c17b8321002..f3018ed819e 100644 --- a/acme/acme/client_test.py +++ b/acme/acme/client_test.py @@ -1129,6 +1129,31 @@ def test_head_get_post_error_passthrough(self): self.assertRaises(requests.exceptions.RequestException, self.net.post, 'uri', obj=self.obj) +class ClientNetworkSourceAddressBindingTest(unittest.TestCase): + """Tests that if ClientNetwork has a source IP set manually, the underlying library has + used the provided source address.""" + + def setUp(self): + self.source_address = "8.8.8.8" + + def test_source_address_set(self): + from acme.client import ClientNetwork + net = ClientNetwork(key=None, alg=None, source_address=self.source_address) + for adapter in net.session.adapters.values(): + self.assertTrue(self.source_address in adapter.source_address) + + def test_behavior_assumption(self): + """This is a test that guardrails the HTTPAdapter behavior so that if the default for + a Session() changes, the assumptions here aren't violated silently.""" + from acme.client import ClientNetwork + # Source address not specified, so the default adapter type should be bound -- this + # test should fail if the default adapter type is changed by requests + net = ClientNetwork(key=None, alg=None) + session = requests.Session() + for scheme in session.adapters.keys(): + client_network_adapter = net.session.adapters.get(scheme) + default_adapter = session.adapters.get(scheme) + self.assertEqual(client_network_adapter.__class__, default_adapter.__class__) if __name__ == '__main__': unittest.main() # pragma: no cover diff --git a/acme/setup.py b/acme/setup.py index 72ab5919bfb..e91c36b3d65 100644 --- a/acme/setup.py +++ b/acme/setup.py @@ -19,6 +19,7 @@ 'pyrfc3339', 'pytz', 'requests[security]>=2.4.1', # security extras added in 2.4.1 + 'requests-toolbelt>=0.3.0', 'setuptools', 'six>=1.9.0', # needed for python_2_unicode_compatible ]
For certbot/certbot#3489 This also adds `requests-toolbelt` as a dependency to `acme` because py35 was unhappy without that on my box (py27 was mysteriously ok). This is my first time working within `certbot` -- please let me know if this was the wrong place to add this hook or if I missed someplace it should go (or anything else). Thanks!
https://api.github.com/repos/certbot/certbot/pulls/5990
2018-05-14T20:49:31Z
2018-05-14T21:43:43Z
2018-05-14T21:43:43Z
2018-06-06T21:46:29Z
963
certbot/certbot
336
Add additional property media_channel to media_player in squeezebox component
diff --git a/homeassistant/components/squeezebox/media_player.py b/homeassistant/components/squeezebox/media_player.py index 6a171ffe30f7..f9d25038674e 100644 --- a/homeassistant/components/squeezebox/media_player.py +++ b/homeassistant/components/squeezebox/media_player.py @@ -363,6 +363,11 @@ def media_title(self): """Title of current playing media.""" return self._player.title + @property + def media_channel(self): + """Channel (e.g. webradio name) of current playing media.""" + return self._player.remote_title + @property def media_artist(self): """Artist of current playing media."""
<!-- You are amazing! Thanks for contributing to our project! Please, DO NOT DELETE ANY TEXT from this template! (unless instructed). --> ## Proposed change <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue in the additional information section. --> This PR adds the `media_player` property `media_channel` to the squeezebox (Logitech Media Server) component and fills it with the corresponding field `remote_title` from the squeezebox server. The idea of this change is to provide some more information to home assistant. The `remote_title` field contains additional information for remote media, e.g. the name of a webradio station. ## Type of change <!-- What type of change does your PR introduce to Home Assistant? NOTE: Please, check only 1! box! If your PR requires multiple boxes to be checked, you'll most likely need to split it into multiple PRs. This makes things easier and faster to code review. --> - [ ] Dependency upgrade - [ ] Bugfix (non-breaking change which fixes an issue) - [ ] New integration (thank you!) - [x] New feature (which adds functionality to an existing integration) - [ ] Deprecation (breaking change to happen in the future) - [ ] Breaking change (fix/feature causing existing functionality to break) - [ ] Code quality improvements to existing code or addition of tests ## Additional information <!-- Details are important, and help maintainers processing your PR. Please be sure to fill out additional details, if applicable. --> / ## Checklist <!-- Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. --> - [x] The code change is tested and works locally. - [x] Local tests pass. **Your PR cannot be merged unless tests pass** - [x] There is no commented out code in this PR. - [x] I have followed the [development checklist][dev-checklist] - [x] The code has been formatted using Black (`black --fast homeassistant tests`) - [ ] Tests have been added to verify that the new code works. If user exposed functionality or configuration variables are added/changed: - [ ] Documentation added/updated for [www.home-assistant.io][docs-repository] If the code communicates with devices, web services, or third-party tools: - [ ] The [manifest file][manifest-docs] has all fields filled out correctly. Updated and included derived files by running: `python3 -m script.hassfest`. - [ ] New or updated dependencies have been added to `requirements_all.txt`. Updated by running `python3 -m script.gen_requirements_all`. - [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description. - [ ] Untested files have been added to `.coveragerc`. <!-- This project is very active and we have a high turnover of pull requests. Unfortunately, the number of incoming pull requests is higher than what our reviewers can review and merge so there is a long backlog of pull requests waiting for review. You can help here! By reviewing another pull request, you will help raise the code quality of that pull request and the final review will be faster. This way the general pace of pull request reviews will go up and your wait time will go down. When picking a pull request to review, try to choose one that hasn't yet been reviewed. Thanks for helping out! --> To help with the load of incoming pull requests: - [ ] I have reviewed two other [open pull requests][prs] in this repository. [prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure <!-- Thank you for contributing <3 Below, some useful links you could explore: --> [dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html [manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html [quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html [docs-repository]: https://github.com/home-assistant/home-assistant.io
https://api.github.com/repos/home-assistant/core/pulls/86402
2023-01-22T20:56:55Z
2023-01-24T16:16:52Z
2023-01-24T16:16:52Z
2023-01-25T17:02:07Z
158
home-assistant/core
39,616
Documentation Update
diff --git a/AUTHORS.rst b/AUTHORS.rst index dc73b64c0b..b1e8ec23e6 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -105,3 +105,7 @@ Patches and Suggestions - Danilo Bargen (gwrtheyrn) - Torsten Landschoff - Michael Holler (apotheos) +- Timnit Gebru +- Sarah Gonzalez +- Victoria Mo +- Leila Muhtasib diff --git a/docs/user/advanced.rst b/docs/user/advanced.rst index 31c676014e..adda9c7314 100644 --- a/docs/user/advanced.rst +++ b/docs/user/advanced.rst @@ -93,6 +93,23 @@ I don't have SSL setup on this domain, so it fails. Excellent. Github does thoug You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable. +Requests can also ignore verifying the SSL certficate if you set ``verify`` to False. :: + + >>> requests.get('https://kennethreitz.com', verify=False) + <Response [200]> + +By default, ``verify`` is set to True. Option ``verify`` only applies to host certs. + +You can also specify the local cert file either as a path or key value pair:: + + >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key')) + <Response [200]> + +If you specify a wrong path or an invalid cert:: + + >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem') + SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib + Body Content Workflow ---------------------
This is the documentation fix for issue #567 and issue #523. We tested and verified the behavior of the code in the examples.
https://api.github.com/repos/psf/requests/pulls/714
2012-07-10T22:39:43Z
2012-07-10T22:48:08Z
2012-07-10T22:48:08Z
2021-09-08T16:00:45Z
445
psf/requests
32,240
added nhtsa vin api
diff --git a/README.md b/README.md index 7e498c2a93..42ef60aa8d 100644 --- a/README.md +++ b/README.md @@ -446,7 +446,9 @@ For information on contributing to this project, please see the [contributing gu | API | Description | Auth | HTTPS | Link | |---|---|---|---|---| | Vehicles | Lot of vehicles informations | `apiKey` query string | No | [Go!](http://developer.edmunds.com/api-documentation/overview/) | -| Brazilian Vehicles and Prices | Vehicles information from Fundação Instituto de Pesquisas Econômicas - Fipe | No | Yes | [Go!](https://deividfortuna.github.io/fipe/) +| Brazilian Vehicles and Prices | Vehicles information from Fundação Instituto de Pesquisas Econômicas - Fipe | No | Yes | [Go!](https://deividfortuna.github.io/fipe/) | +| NHTSA Vehicles | NHTSA Product Information Catalog and Vehicle Listing | No | Yes | [Go!](https://vpic.nhtsa.dot.gov/api/) | + ### Video | API | Description | Auth | HTTPS | Link |
Free API by the U.S. DOT National Highway Traffic Safety Administration Office, lots of vehicle information especially VIN information. note: I have no affiliation with the NHTSA.
https://api.github.com/repos/public-apis/public-apis/pulls/301
2017-03-13T18:57:11Z
2017-03-13T20:20:01Z
2017-03-13T20:20:01Z
2017-03-13T20:20:01Z
265
public-apis/public-apis
35,338
Add smooth l1 loss algorithm
diff --git a/machine_learning/loss_functions.py b/machine_learning/loss_functions.py index 36a760326f3d..24d732fb0ed9 100644 --- a/machine_learning/loss_functions.py +++ b/machine_learning/loss_functions.py @@ -471,6 +471,62 @@ def perplexity_loss( return np.mean(perp_losses) +def smooth_l1_loss(y_true: np.ndarray, y_pred: np.ndarray, beta: float = 1.0) -> float: + """ + Calculate the Smooth L1 Loss between y_true and y_pred. + + The Smooth L1 Loss is less sensitive to outliers than the L2 Loss and is often used + in regression problems, such as object detection. + + Smooth L1 Loss = + 0.5 * (x - y)^2 / beta, if |x - y| < beta + |x - y| - 0.5 * beta, otherwise + + Reference: + https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html + + Args: + y_true: Array of true values. + y_pred: Array of predicted values. + beta: Specifies the threshold at which to change between L1 and L2 loss. + + Returns: + The calculated Smooth L1 Loss between y_true and y_pred. + + Raises: + ValueError: If the length of the two arrays is not the same. + + >>> y_true = np.array([3, 5, 2, 7]) + >>> y_pred = np.array([2.9, 4.8, 2.1, 7.2]) + >>> smooth_l1_loss(y_true, y_pred, 1.0) + 0.012500000000000022 + + >>> y_true = np.array([2, 4, 6]) + >>> y_pred = np.array([1, 5, 7]) + >>> smooth_l1_loss(y_true, y_pred, 1.0) + 0.5 + + >>> y_true = np.array([1, 3, 5, 7]) + >>> y_pred = np.array([1, 3, 5, 7]) + >>> smooth_l1_loss(y_true, y_pred, 1.0) + 0.0 + + >>> y_true = np.array([1, 3, 5]) + >>> y_pred = np.array([1, 3, 5, 7]) + >>> smooth_l1_loss(y_true, y_pred, 1.0) + Traceback (most recent call last): + ... + ValueError: The length of the two arrays should be the same. + """ + + if len(y_true) != len(y_pred): + raise ValueError("The length of the two arrays should be the same.") + + diff = np.abs(y_true - y_pred) + loss = np.where(diff < beta, 0.5 * diff**2 / beta, diff - 0.5 * beta) + return np.mean(loss) + + if __name__ == "__main__": import doctest
### Describe your change: - The [Smooth L1 Loss](https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html#torch.nn.SmoothL1Loss) is less sensitive to outliers than the L2 Loss and is often used in regression problems, such as object detection. * [x] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request. * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
https://api.github.com/repos/TheAlgorithms/Python/pulls/11239
2024-01-13T12:04:41Z
2024-01-30T08:18:56Z
2024-01-30T08:18:56Z
2024-01-30T08:18:56Z
715
TheAlgorithms/Python
29,694
Add Synapses - a neural network library in F#
diff --git a/README.md b/README.md index 98883a0c..da7fb015 100644 --- a/README.md +++ b/README.md @@ -811,6 +811,7 @@ on MNIST digits[DEEP LEARNING]. * [Infer.NET](https://dotnet.github.io/infer/) - Infer.NET is a framework for running Bayesian inference in graphical models. One can use Infer.NET to solve many different kinds of machine learning problems, from standard problems like classification, recommendation or clustering through to customised solutions to domain-specific problems. Infer.NET has been used in a wide variety of domains including information retrieval, bioinformatics, epidemiology, vision, and many others. * [ML.NET](https://github.com/dotnet/machinelearning) - ML.NET is a cross-platform open-source machine learning framework which makes machine learning accessible to .NET developers. ML.NET was originally developed in Microsoft Research and evolved into a significant framework over the last decade and is used across many product groups in Microsoft like Windows, Bing, PowerPoint, Excel and more. * [Neural Network Designer](https://sourceforge.net/projects/nnd/) - DBMS management system and designer for neural networks. The designer application is developed using WPF, and is a user interface which allows you to design your neural network, query the network, create and configure chat bots that are capable of asking questions and learning from your feed back. The chat bots can even scrape the internet for information to return in their output as well as to use for learning. +* [Synapses](https://github.com/mrdimosthenis/Synapses) - Neural network library in F#. * [Vulpes](https://github.com/fsprojects/Vulpes) - Deep belief and deep learning implementation written in F# and leverages CUDA GPU execution with Alea.cuBase. <a name="net-data-analysis"></a>
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/654
2019-11-30T10:21:20Z
2019-12-03T16:37:04Z
2019-12-03T16:37:04Z
2019-12-03T16:37:04Z
401
josephmisiti/awesome-machine-learning
51,776
Show warning to user and use skipkeys=True if json.dumps causes TypeError
diff --git a/lib/streamlit/DeltaGenerator.py b/lib/streamlit/DeltaGenerator.py index d0f85baf262f..b9952c68d21e 100644 --- a/lib/streamlit/DeltaGenerator.py +++ b/lib/streamlit/DeltaGenerator.py @@ -604,11 +604,19 @@ def json(self, element, body): height: 280px """ - element.json.body = ( - body - if isinstance(body, string_types) # noqa: F821 - else json.dumps(body, default=lambda o: str(type(o))) - ) + import streamlit as st + + if not isinstance(body, string_types): + try: + body = json.dumps(body, default=lambda o: str(type(o))) + except TypeError as err: + st.warning( + "Warning: this data structure was not fully serializable as " + "JSON due to one or more unexpected keys. (Error was: %s)" % err + ) + body = json.dumps(body, skipkeys=True, default=lambda o: str(type(o))) + + element.json.body = body @_with_element def title(self, element, body): diff --git a/lib/tests/streamlit/streamlit_test.py b/lib/tests/streamlit/streamlit_test.py index 549d338c13e9..a80cdc9af86c 100644 --- a/lib/tests/streamlit/streamlit_test.py +++ b/lib/tests/streamlit/streamlit_test.py @@ -389,6 +389,16 @@ def test_st_json(self): el = self.get_delta_from_queue().new_element self.assertEqual(el.json.body, '{"some": "json"}') + # Test that an object containing non-json-friendly keys can still + # be displayed. Resultant json body will be missing those keys. + + n = np.array([1, 2, 3, 4, 5]) + data = {n[0]: "this key will not render as JSON", "array": n} + st.json(data) + + el = self.get_delta_from_queue().new_element + self.assertEqual(el.json.body, '{"array": "<class \'numpy.ndarray\'>"}') + def test_st_line_chart(self): """Test st.line_chart.""" df = pd.DataFrame([[10, 20, 30]], columns=["a", "b", "c"])
**Issue:** #975 **Description:** Currently, st.json will trip over the use of a nonstandard key in a dictionary, resulting in a confusing and unhelpful traceback to the user. This PR wraps the conversion to JSON in a try-except block that catches the TypeError that arises from use of weird keys that json.dumps cannot handle. If triggered, we show a warning to the user that this happened, and then rerun json.dumps with skipkeys=True. The resultant data structure will not show the entire data, but the warning should be informative enough to the user to understand why. --- **Contribution License Agreement** By submiting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.
https://api.github.com/repos/streamlit/streamlit/pulls/1112
2020-02-18T21:49:59Z
2020-02-19T20:00:55Z
2020-02-19T20:00:55Z
2020-02-19T20:00:59Z
535
streamlit/streamlit
22,267
Fix #2279. Update layout css
diff --git a/docs/_templates/sidebarintro.html b/docs/_templates/sidebarintro.html index a5d5c7484d..e60cf4518e 100644 --- a/docs/_templates/sidebarintro.html +++ b/docs/_templates/sidebarintro.html @@ -17,12 +17,12 @@ <h3>Donate</h3> <p> - If you love Requests, consider supporting the author <a href="https://www.gittip.com/kennethreitz/">on Gratipay</a>: + If you love Requests, consider supporting the author <a href="https://gratipay.com/kennethreitz/">on Gratipay</a>: </p> <p> <iframe style="border: 0; margin: 0; padding: 0;" - src="https://www.gittip.com/kennethreitz/widget.html" - width="60pt" height="20pt"></iframe> + src="https://www.gratipay.com/kennethreitz/widget.html" + width="80pt" height="20pt"></iframe> </p> diff --git a/docs/_templates/sidebarlogo.html b/docs/_templates/sidebarlogo.html index 6aca76eb0e..930fdb3d41 100644 --- a/docs/_templates/sidebarlogo.html +++ b/docs/_templates/sidebarlogo.html @@ -17,12 +17,12 @@ <h3>Donate</h3> <p> - If you love Requests, consider supporting the author <a href="https://www.gittip.com/kennethreitz/">on Gittip</a>: + If you love Requests, consider supporting the author <a href="https://www.gratipay.com/kennethreitz/">on Gittip</a>: </p> <p> <iframe style="border: 0; margin: 0; padding: 0;" - src="https://www.gittip.com/kennethreitz/widget.html" - width="48pt" height="20pt"></iframe> + src="https://www.gratipay.com/kennethreitz/widget.html" + width="80pt" height="20pt"></iframe> </p> <h3>Get Updates</h3>
Updated gratipay widget iframe in both sidebarintro.html and sidebarlogo.html .
https://api.github.com/repos/psf/requests/pulls/2290
2014-10-19T08:39:50Z
2014-10-19T09:42:28Z
2014-10-19T09:42:28Z
2021-09-08T10:01:03Z
508
psf/requests
32,816
[pre-commit.ci] pre-commit autoupdate
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5d767e605b..7c5731f9eb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ repos: args: ["--application-directories", "src"] additional_dependencies: ["setuptools>60.9"] - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 22.8.0 hooks: - id: black - repo: https://github.com/PyCQA/flake8
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) <!--pre-commit.ci end-->
https://api.github.com/repos/pallets/flask/pulls/4806
2022-09-05T23:32:32Z
2022-09-07T19:07:21Z
2022-09-07T19:07:21Z
2022-09-22T00:08:39Z
149
pallets/flask
19,981
handleSubTypeAndParams -default value
diff --git a/js/base/Exchange.js b/js/base/Exchange.js index 17f250d1f716..15dc503505bb 100644 --- a/js/base/Exchange.js +++ b/js/base/Exchange.js @@ -2143,7 +2143,7 @@ module.exports = class Exchange { return [ type, params ]; } - handleSubTypeAndParams (methodName, market = undefined, params = {}) { + handleSubTypeAndParams (methodName, market = undefined, params = {}, defaultValue = 'linear') { let subType = undefined; // if set in params, it takes precedence const subTypeInParams = this.safeString2 (params, 'subType', 'defaultSubType'); @@ -2162,7 +2162,7 @@ module.exports = class Exchange { } // if it was not defined in market object if (subType === undefined) { - const values = this.handleOptionAndParams (undefined, methodName, 'subType', 'linear'); // no need to re-test params here + const values = this.handleOptionAndParams (undefined, methodName, 'subType', defaultValue); // no need to re-test params here subType = values[0]; } }
https://api.github.com/repos/ccxt/ccxt/pulls/15811
2022-11-23T18:26:09Z
2022-11-23T19:39:45Z
2022-11-23T19:39:45Z
2022-11-24T06:02:09Z
275
ccxt/ccxt
12,959
Add more doctest to intro_sort.py #9943
diff --git a/sorts/intro_sort.py b/sorts/intro_sort.py index f0e3645adbb7..908d2886533a 100644 --- a/sorts/intro_sort.py +++ b/sorts/intro_sort.py @@ -1,5 +1,5 @@ """ -Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort) +Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ @@ -9,7 +9,6 @@ def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ @@ -27,8 +26,7 @@ def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - - >>> heapify(array, len(array) // 2 ,len(array)) + >>> heapify(array, len(array) // 2, len(array)) """ largest = index left_index = 2 * index + 1 # Left Node @@ -47,9 +45,7 @@ def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap def heap_sort(array: list) -> list: """ - >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - - >>> heap_sort(array) + >>> heap_sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ n = len(array) @@ -69,9 +65,14 @@ def median_of_3( ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - - >>> median_of_3(array, 0, 0 + ((len(array) - 0) // 2) + 1, len(array) - 1) + >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) 12 + >>> array = [13, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] + >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) + 13 + >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 15, 14, 27, 79, 23, 45, 14, 16] + >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) + 14 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] @@ -88,7 +89,6 @@ def median_of_3( def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - >>> partition(array, 0, len(array), 12) 8 """ @@ -115,22 +115,16 @@ def sort(array: list) -> list: Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] - >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] - >>> sort([]) [] - >>> sort([5]) [5] - >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] - >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] - >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ @@ -146,9 +140,7 @@ def intro_sort( ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] - >>> max_depth = 2 * math.ceil(math.log2(len(array))) - >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ @@ -167,7 +159,6 @@ def intro_sort( import doctest doctest.testmod() - user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] - print(sort(unsorted)) + print(f"{sort(unsorted) = }")
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request. * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
https://api.github.com/repos/TheAlgorithms/Python/pulls/11068
2023-10-29T08:48:59Z
2023-10-29T09:37:08Z
2023-10-29T09:37:08Z
2023-10-29T09:37:11Z
1,694
TheAlgorithms/Python
29,674
Fix docs formatting
diff --git a/docs/guides/introducing_black_to_your_project.md b/docs/guides/introducing_black_to_your_project.md index 53bb0d9fcd..71a566fbda 100644 --- a/docs/guides/introducing_black_to_your_project.md +++ b/docs/guides/introducing_black_to_your_project.md @@ -46,5 +46,6 @@ $ git config blame.ignoreRevsFile .git-blame-ignore-revs **The one caveat is that some online Git-repositories like GitLab do not yet support ignoring revisions using their native blame UI.** So blame information will be cluttered with a reformatting commit on those platforms. (If you'd like this feature, there's an -open issue for [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423)). -[GitHub supports `.git-blame-ignore-revs`](https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view) by default in blame views however. +open issue for [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423)). +[GitHub supports `.git-blame-ignore-revs`](https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view) +by default in blame views however.
https://api.github.com/repos/psf/black/pulls/3704
2023-05-25T03:59:25Z
2023-05-25T04:06:08Z
2023-05-25T04:06:08Z
2023-05-25T04:06:11Z
309
psf/black
24,513
okcoin: update ratelimits
diff --git a/js/okcoin.js b/js/okcoin.js index 98bf954ef44f..3fde6a622de9 100644 --- a/js/okcoin.js +++ b/js/okcoin.js @@ -16,7 +16,9 @@ module.exports = class okcoin extends Exchange { 'name': 'OKCoin', 'countries': [ 'CN', 'US' ], 'version': 'v3', - 'rateLimit': 1000, // up to 3000 requests per 5 minutes ≈ 600 requests per minute ≈ 10 requests per second ≈ 100 ms + // cheapest endpoint is 100 requests per 2 seconds + // 50 requests per second => 1000 / 50 = 20ms + 'rateLimit': 20, 'pro': true, 'has': { 'CORS': undefined, @@ -85,91 +87,157 @@ module.exports = class okcoin extends Exchange { }, 'api': { 'general': { - 'get': [ - 'time', - ], + 'get': { + 'time': 8.3334, + }, }, 'account': { - 'get': [ - 'wallet', - 'sub-account', - 'asset-valuation', - 'wallet/{currency}', - 'withdrawal/history', - 'withdrawal/history/{currency}', - 'ledger', - 'deposit/address', - 'deposit/history', - 'deposit/history/{currency}', - 'currencies', - 'withdrawal/fee', - ], - 'post': [ - 'transfer', - 'withdrawal', - ], + 'get': { + 'wallet': 8.3334, + 'sub-account': 1000, + 'asset-valuation': 1000, + 'wallet/{currency}': 8.3334, + 'withdrawal/history': 8.3334, + 'withdrawal/history/{currency}': 8.3334, + 'ledger': 5, + 'deposit/address': 8.3334, + 'deposit/history': 8.3334, + 'deposit/history/{currency}': 8.3334, + 'currencies': 8.3334, + 'withdrawal/fee': 8.3334, + 'deposit-lightning': 50, + 'withdrawal-lightning': 50, + 'fiat/deposit/detail': 5, + 'fiat/deposit/details': 8.3334, + 'fiat/withdraw/detail': 5, + 'fiat/withdraw/details': 8.3334, + 'fiat/channel': 8.3334, + }, + 'post': { + 'transfer': 100, // 1 request per 2 seconds (per currency) + 'withdrawal': 8.3334, + 'fiat/cancel_deposit': 1, + 'fiat/deposit': 8.3334, + 'fiat/withdraw': 8.3334, + 'fiat/cancel_withdrawal': 1, + }, + }, + // TODO fix signing issue in sign () + // all other endpoints of the format + // api/account/v3/wallet + // otc endpoints actually of the format: (exchanged places) + // api/v3/otc/rfq/instruments + 'otc': { + 'get': { + 'rfq/instruments': 50, // represents: GET api/v3/otc/rfq/instruments + 'rfq/trade': 50, + 'rfq/history': 50, + }, + 'post': { + 'rfq/quote': 50, + 'rfq/trade': 50, + }, + }, + // TODO fix signing issue as above + 'users': { + 'get': { + 'subaccount-info': 20, + 'account-info': 20, + 'subaccount/apikey': 20, + }, + 'post': { + 'create-subaccount': 5, // represents: POST api/v3/users/create-subaccount + 'delete-subaccount': 5, + 'subaccount/apikey': 50, + 'subacount/delete-apikey': 20, + 'subacount/modify-apikey': 20, + }, + }, + 'earning': { + 'get': { + 'offers': 5, + 'orders': 5, + 'positions': 8.3334, + }, + 'post': { + 'purchase': 5, + 'redeem': 5, + 'cancel': 5, + }, }, 'spot': { - 'get': [ - 'accounts', - 'accounts/{currency}', - 'accounts/{currency}/ledger', - 'orders', - 'amend_order/{instrument_id}', - 'orders_pending', - 'orders/{order_id}', - 'orders/{client_oid}', - 'trade_fee', - 'fills', - 'algo', + 'get': { + 'accounts': 5, + 'accounts/{currency}': 5, + 'accounts/{currency}/ledger': 5, + 'orders': 10, + 'orders_pending': 5, + 'orders/{order_id}': 5, + 'orders/{client_oid}': 5, + 'trade_fee': 5, + 'fills': 10, + 'algo': 5, // public - 'instruments', - 'instruments/{instrument_id}/book', - 'instruments/ticker', - 'instruments/{instrument_id}/ticker', - 'instruments/{instrument_id}/trades', - 'instruments/{instrument_id}/candles', - 'instruments/{instrument_id}/history/candles', - ], - 'post': [ - 'order_algo', - 'orders', - 'batch_orders', - 'cancel_orders/{order_id}', - 'cancel_orders/{client_oid}', - 'cancel_batch_algos', - 'cancel_batch_orders', - ], + 'instruments': 5, + 'instruments/{instrument_id}/book': 5, + 'instruments/ticker': 5, + 'instruments/{instrument_id}/ticker': 5, + 'instruments/{instrument_id}/trades': 5, + 'instruments/{instrument_id}/candles': 5, + }, + 'post': { + 'order_algo': 2.5, + 'orders': 1, + 'batch_orders': 2, + 'cancel_orders/{order_id}': 1, + 'cancel_orders/{client_oid}': 1, + 'cancel_batch_algos': 5, + 'cancel_batch_orders': 5, + 'amend_order/{instrument_id}': 2.5, + 'amend_batch_orders': 5, + }, }, 'margin': { - 'get': [ - 'accounts', - 'accounts/{instrument_id}', - 'accounts/{instrument_id}/ledger', - 'accounts/availability', - 'accounts/{instrument_id}/availability', - 'accounts/borrowed', - 'accounts/{instrument_id}/borrowed', - 'orders', - 'accounts/{instrument_id}/leverage', - 'orders/{order_id}', - 'orders/{client_oid}', - 'orders_pending', - 'fills', + 'get': { + 'accounts': 5, + 'accounts/{instrument_id}': 5, + 'accounts/{instrument_id}/ledger': 5, + 'accounts/availability': 5, + 'accounts/{instrument_id}/availability': 5, + 'accounts/borrowed': 5, + 'accounts/{instrument_id}/borrowed': 5, + 'orders': 10, + 'accounts/{instrument_id}/leverage': 1, + 'orders/{order_id}': 5, + 'orders/{client_oid}': 5, + 'orders_pending': 5, + 'fills': 10, // public - 'instruments/{instrument_id}/mark_price', - ], - 'post': [ - 'accounts/borrow', - 'accounts/repayment', - 'orders', - 'batch_orders', - 'cancel_orders', - 'cancel_orders/{order_id}', - 'cancel_orders/{client_oid}', - 'cancel_batch_orders', - 'accounts/{instrument_id}/leverage', - ], + 'instruments/{instrument_id}/mark_price': 5, + }, + 'post': { + 'accounts/borrow': 1, + 'accounts/repayment': 1, + 'orders': 1, + 'batch_orders': 2, + 'cancel_orders': 1, + 'cancel_orders/{order_id}': 1, + 'cancel_orders/{client_oid}': 1, + 'cancel_batch_orders': 2, + 'amend_order/{instrument_id}': 2.5, + 'amend_batch_orders': 5, + 'accounts/{instrument_id}/leverage': 1, + }, + }, + 'system': { + 'get': { + 'status': 250, + }, + }, + 'market': { + 'get': { + 'oracle': 250, + }, }, 'futures': { 'get': [
https://api.github.com/repos/ccxt/ccxt/pulls/12224
2022-03-08T10:58:44Z
2022-03-11T11:44:00Z
2022-03-11T11:44:00Z
2022-04-22T13:54:23Z
2,192
ccxt/ccxt
13,364
Improvement made : by automating search engine configuration in example search_in_search_engine.py
diff --git a/examples/debate.py b/examples/debate.py index 72ab8796d..56df16b4f 100644 --- a/examples/debate.py +++ b/examples/debate.py @@ -5,6 +5,7 @@ @Modified By: mashenquan, 2023-11-1. In accordance with Chapter 2.1.3 of RFC 116, modify the data type of the `send_to` value of the `Message` object; modify the argument type of `get_by_actions`. """ + import asyncio import platform from typing import Any @@ -105,4 +106,4 @@ def main(idea: str, investment: float = 3.0, n_round: int = 10): if __name__ == "__main__": - fire.Fire(main) + fire.Fire(main) # run as python debate.py --idea="TOPIC" --investment=3.0 --n_round=5 diff --git a/examples/search_with_specific_engine.py b/examples/search_with_specific_engine.py index 97b1378ee..1eee762d5 100644 --- a/examples/search_with_specific_engine.py +++ b/examples/search_with_specific_engine.py @@ -4,21 +4,17 @@ """ import asyncio +from metagpt.config2 import Config from metagpt.roles import Searcher -from metagpt.tools.search_engine import SearchEngine, SearchEngineType +from metagpt.tools.search_engine import SearchEngine async def main(): question = "What are the most interesting human facts?" - kwargs = {"api_key": "", "cse_id": "", "proxy": None} - # Serper API - # await Searcher(search_engine=SearchEngine(engine=SearchEngineType.SERPER_GOOGLE, **kwargs)).run(question) - # SerpAPI - # await Searcher(search_engine=SearchEngine(engine=SearchEngineType.SERPAPI_GOOGLE, **kwargs)).run(question) - # Google API - # await Searcher(search_engine=SearchEngine(engine=SearchEngineType.DIRECT_GOOGLE, **kwargs)).run(question) - # DDG API - await Searcher(search_engine=SearchEngine(engine=SearchEngineType.DUCK_DUCK_GO, **kwargs)).run(question) + + search = Config.default().search + kwargs = {"api_key": search.api_key, "cse_id": search.cse_id, "proxy": None} + await Searcher(search_engine=SearchEngine(engine=search.api_type, **kwargs)).run(question) if __name__ == "__main__":
**Features** This is a change made for improving new user's experience. When the examples are run there can be some confusion. So when I went through the examples\search_with_specific_engine.py there is a need for adding the api key and cse id explicitly and also need to uncomment and comment the code snippets according to our search engine preference Through my updation i have made it easy by just using the config2.yaml configuration and doing the run The user just need to run the program no need to bother about the code changes according to configurations. **Influence** It can make the new users' experience great and ease the usage of examples and understanding the code
https://api.github.com/repos/geekan/MetaGPT/pulls/965
2024-03-05T19:59:19Z
2024-03-11T05:35:34Z
2024-03-11T05:35:34Z
2024-03-11T05:35:35Z
564
geekan/MetaGPT
16,489
README.md: fix mailto link
diff --git a/README.md b/README.md index 7be809371e..c548ce483c 100644 --- a/README.md +++ b/README.md @@ -1346,7 +1346,7 @@ Multiple contributions by: * [Luka Sterbic](mailto:[email protected]) * [Miguel Gaiowski](mailto:[email protected]) * [Miroslav Shubernetskiy](mailto:[email protected]) -* [Neraste]([email protected]) +* [Neraste](mailto:[email protected]) * [Osaetin Daniel](mailto:[email protected]) * [Peter Bengtsson](mailto:[email protected]) * [Stavros Korokithakis](mailto:[email protected])
https://api.github.com/repos/psf/black/pulls/660
2019-01-05T11:58:51Z
2019-01-05T18:46:07Z
2019-01-05T18:46:07Z
2019-01-05T18:46:07Z
195
psf/black
23,710
Fix get_dns_facts on inexistent resolv.conf
diff --git a/lib/ansible/module_utils/facts.py b/lib/ansible/module_utils/facts.py index bc611b41d0fa83..d7105b5a87ec8a 100644 --- a/lib/ansible/module_utils/facts.py +++ b/lib/ansible/module_utils/facts.py @@ -727,7 +727,7 @@ def get_env_facts(self): def get_dns_facts(self): self.facts['dns'] = {} - for line in get_file_lines('/etc/resolv.conf'): + for line in get_file_content('/etc/resolv.conf', '').splitlines(): if line.startswith('#') or line.startswith(';') or line.strip() == '': continue tokens = line.split()
This fixes the get_dns_facts function when /etc/resolv.conf is not present or unreadable.
https://api.github.com/repos/ansible/ansible/pulls/13100
2015-11-09T20:02:51Z
2015-11-09T21:10:15Z
2015-11-09T21:10:15Z
2019-04-26T16:04:32Z
162
ansible/ansible
48,785
Fix minor issues with har_extractor
diff --git a/examples/har_extractor.py b/examples/har_extractor.py index 4e905438e8..e7718fe803 100644 --- a/examples/har_extractor.py +++ b/examples/har_extractor.py @@ -127,11 +127,11 @@ def response(context, flow): tz=utc).isoformat() request_query_string = [{"name": k, "value": v} - for k, v in flow.request.get_query()] + for k, v in flow.request.query] request_http_version = flow.request.http_version # Cookies are shaped as tuples by MITMProxy. request_cookies = [{"name": k.strip(), "value": v[0]} - for k, v in (flow.request.get_cookies() or {}).iteritems()] + for k, v in flow.request.cookies.items()] request_headers = [{"name": k, "value": v} for k, v in flow.request.headers] request_headers_size = len(str(flow.request.headers)) request_body_size = len(flow.request.content) @@ -139,7 +139,7 @@ def response(context, flow): response_http_version = flow.response.http_version # Cookies are shaped as tuples by MITMProxy. response_cookies = [{"name": k.strip(), "value": v[0]} - for k, v in (flow.response.get_cookies() or {}).iteritems()] + for k, v in flow.response.cookies.items()] response_headers = [{"name": k, "value": v} for k, v in flow.response.headers] response_headers_size = len(str(flow.response.headers))
Fixes #766
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/967
2016-02-20T15:35:20Z
2016-02-21T21:09:28Z
2016-02-21T21:09:28Z
2016-06-04T10:54:41Z
347
mitmproxy/mitmproxy
27,815
Fix typos
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 69348619cf..c220a52db2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,7 +61,7 @@ See [Translations](TRANSLATIONS.md). ### Adding translations to new languages -Translations to new languages are always welcome! Keep in mind a transation must be maintained. +Translations to new languages are always welcome! Keep in mind a translation must be maintained. * Do you have time to be a maintainer for a new language? Please see the list of [translations](TRANSLATIONS.md) and tell us so we know we can count on you in the future. * Check the [translations](TRANSLATIONS.md), issues, and pull requests to see if a translation is in progress or stalled. If it's in progress, offer to help. If it's stalled, consider becoming the maintainer if you can commit to it. diff --git a/README.md b/README.md index 54edea4b1b..eb07eb7b64 100644 --- a/README.md +++ b/README.md @@ -1673,7 +1673,7 @@ Handy metrics based on numbers above: | Design an online multiplayer card game | [indieflashblog.com](https://web.archive.org/web/20180929181117/http://www.indieflashblog.com/how-to-create-an-asynchronous-multiplayer-game.html)<br/>[buildnewgames.com](http://buildnewgames.com/real-time-multiplayer/) | | Design a garbage collection system | [stuffwithstuff.com](http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/)<br/>[washington.edu](http://courses.cs.washington.edu/courses/csep521/07wi/prj/rick.pdf) | | Design an API rate limiter | [https://stripe.com/blog/](https://stripe.com/blog/rate-limiters) | -| Design a Stock Exchange (like NASDAQ or Binance) | [Jane Street](https://youtu.be/b1e4t2k2KJY)<br/>[Golang Implementation](https://around25.com/blog/building-a-trading-engine-for-a-crypto-exchange/)<br/>[Go Implemenation](http://bhomnick.net/building-a-simple-limit-order-in-go/) | +| Design a Stock Exchange (like NASDAQ or Binance) | [Jane Street](https://youtu.be/b1e4t2k2KJY)<br/>[Golang Implementation](https://around25.com/blog/building-a-trading-engine-for-a-crypto-exchange/)<br/>[Go Implementation](http://bhomnick.net/building-a-simple-limit-order-in-go/) | | Add a system design question | [Contribute](#contributing) | ### Real world architectures diff --git a/generate-epub.sh b/generate-epub.sh index 18690fbb52..a6bfe05b50 100755 --- a/generate-epub.sh +++ b/generate-epub.sh @@ -34,7 +34,7 @@ generate () { cat $name.md | generate_from_stdin $name.epub $language } -# Check if depencies exist +# Check if dependencies exist check_dependencies () { for dependency in "${dependencies[@]}" do
https://api.github.com/repos/donnemartin/system-design-primer/pulls/661
2022-04-17T16:01:57Z
2022-04-23T13:14:45Z
2022-04-23T13:14:45Z
2023-02-25T12:48:28Z
750
donnemartin/system-design-primer
36,715
[RLlib] Remove checking config[no_local_replay_buffer]
diff --git a/rllib/algorithms/algorithm.py b/rllib/algorithms/algorithm.py index bbfcdfa5623ae..44c69355c8712 100644 --- a/rllib/algorithms/algorithm.py +++ b/rllib/algorithms/algorithm.py @@ -2690,7 +2690,7 @@ def _create_local_replay_buffer_if_necessary( None, if local replay buffer is not needed. """ if not config.get("replay_buffer_config") or config["replay_buffer_config"].get( - "no_local_replay_buffer" or config.get("no_local_replay_buffer") + "no_local_replay_buffer" ): return
## Why are these changes needed? Removes a redundant check for config["no_local_replay_buffer"]. This check never worked, but is redundant anyway, because we copy over `config["no_local_replay_buffer"]` to `config["replay_buffer_config"]["no_local_replay_buffer"]` in the config validation anyways. ## Related issue number Closes https://github.com/ray-project/ray/issues/32905
https://api.github.com/repos/ray-project/ray/pulls/33137
2023-03-08T19:16:09Z
2023-03-09T21:09:19Z
2023-03-09T21:09:19Z
2023-03-09T21:09:20Z
150
ray-project/ray
19,640
Update CppCoreGuidelines.md
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 6b9ea4626..5ecf48334 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -12008,7 +12008,7 @@ Never allow an error to be reported from a destructor, a resource deallocation f class nefarious { public: nefarious() { /* code that could throw */ } // ok - ~nefarious() { /* code that could throw */ } // BAD, should be noexcept + ~nefarious() { /* code that could throw */ } // BAD, should not throw // ... }; ```
Destructors are always marked as noexcept (unless noexcept(false)) using this word here is ambigious.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/158
2015-09-26T22:46:52Z
2015-09-26T23:52:16Z
2015-09-26T23:52:16Z
2015-09-26T23:52:22Z
158
isocpp/CppCoreGuidelines
15,945
add docs badge to readme
diff --git a/README.md b/README.md index e6a682ec35..7cac0788c4 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ <div align="center"> <a href="https://github.com/LAION-AI/Open-Assistant/stargazers">![GitHub Repo stars](https://img.shields.io/github/stars/LAION-AI/Open-Assistant?style=social)</a> +<a href="https://laion-ai.github.io/Open-Assistant/">![Docs](https://img.shields.io/badge/docs-laion--ai.github.io%2FOpen--Assistant%2F-green)</a> <a href="https://github.com/LAION-AI/Open-Assistant/actions/workflows/build-frontend.yaml">![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/LAION-AI/Open-Assistant/build-frontend.yaml?label=frontend)</a> <a href="https://github.com/LAION-AI/Open-Assistant/actions/workflows/pre-commit.yaml">![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/LAION-AI/Open-Assistant/pre-commit.yaml?label=pre-commit)</a> <a href="https://github.com/LAION-AI/Open-Assistant/actions/workflows/test-api-contract.yaml">![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/LAION-AI/Open-Assistant/test-api-contract.yaml?label=api)</a>
small one to just add a docs badge to the readme. can add something more clearer into text of main readme once docs site all up and looking good.
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/462
2023-01-06T23:09:20Z
2023-01-07T21:54:02Z
2023-01-07T21:54:02Z
2023-01-07T22:03:57Z
335
LAION-AI/Open-Assistant
37,574
Fix indentation in example
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 047ce0711..d91e8244a 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -9789,7 +9789,7 @@ The following should not pass code review: f(*g_p); // BAD: same reason, just passing it as a "this" pointer - g_p->func(); + g_p->func(); } The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1339
2019-02-20T13:30:56Z
2019-02-20T23:11:54Z
2019-02-20T23:11:54Z
2019-03-09T00:24:00Z
139
isocpp/CppCoreGuidelines
16,116
New Answer
diff --git a/README.md b/README.md index 8c423122f..8d9330db4 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,11 @@ Note: cross-dependency is when you have two or more changes to separate projects <details> <summary>What is Jenkins? What have you used it for?</summary><br><b> + +Jenkins is an open source automation tool written in Java with plugins built for Continuous Integration purpose. Jenkins is used to build and test your software projects continuously making it easier for developers to integrate changes to the project, and making it easier for users to obtain a fresh build. It also allows you to continuously deliver your software by integrating with a large number of testing and deployment technologies. + +Jenkins integrates development life-cycle processes of all kinds, including build, document, test, package, stage, deploy, static analysis and much more. + </b></details> <details>
https://api.github.com/repos/bregman-arie/devops-exercises/pulls/78
2020-02-14T19:30:13Z
2020-02-14T19:40:22Z
2020-02-14T19:40:21Z
2020-02-14T19:40:22Z
212
bregman-arie/devops-exercises
17,655
fix #1830
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py index b8b6093f5c..dd5b745dff 100644 --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -145,9 +145,9 @@ def store_count(self): def inbounds(self, index: int) -> bool: """ - Is this index >= 0 and < len(self) + Is this 0 <= index < len(self) """ - return index >= 0 and index < len(self) + return 0 <= index < len(self) def _rev(self, idx: int) -> int: """ @@ -359,7 +359,7 @@ def index(self) -> typing.Optional[int]: return self.view.index(self.flow) @index.setter - def index(self, idx) -> typing.Optional[int]: + def index(self, idx): if idx < 0 or idx > len(self.view) - 1: raise ValueError("Index out of view bounds") self.flow = self.view[idx] diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py index d7c312e5e6..fee215c610 100644 --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -355,9 +355,11 @@ def keypress(self, size, key): elif key == "e": self.master.toggle_eventlog() elif key == "g": - self.master.view.focus.index = 0 + if len(self.master.view): + self.master.view.focus.index = 0 elif key == "G": - self.master.view.focus.index = len(self.master.view) - 1 + if len(self.master.view): + self.master.view.focus.index = len(self.master.view) - 1 elif key == "f": signals.status_prompt.send( prompt = "Filter View",
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/1839
2016-12-11T12:11:22Z
2016-12-11T13:50:14Z
2016-12-11T13:50:14Z
2016-12-11T13:50:16Z
452
mitmproxy/mitmproxy
27,590
update README
diff --git a/README.rst b/README.rst index c51168216d9..ff6fafe3635 100644 --- a/README.rst +++ b/README.rst @@ -96,18 +96,10 @@ ACME spec: http://ietf-wg-acme.github.io/acme/ ACME working area in github: https://github.com/ietf-wg-acme/acme - -Mailing list: `client-dev`_ (to subscribe without a Google account, send an -email to [email protected]) - |build-status| |coverage| |docs| |container| .. _Freenode: https://webchat.freenode.net?channels=%23letsencrypt -.. _OFTC: https://webchat.oftc.net?channels=%23certbot - -.. _client-dev: https://groups.google.com/a/letsencrypt.org/forum/#!forum/client-dev - .. |build-status| image:: https://travis-ci.org/certbot/certbot.svg?branch=master :target: https://travis-ci.org/certbot/certbot :alt: Travis CI status @@ -141,7 +133,7 @@ Current Features * Supports multiple web servers: - apache/2.x (beta support for auto-configuration) - - nginx/0.8.48+ (alpha support for auto-configuration) + - nginx/0.8.48+ (alpha support for auto-configuration, beta support in 0.14.0) - webroot (adds files to webroot directories in order to prove control of domains and obtain certs) - standalone (runs its own simple webserver to prove you control a domain) @@ -157,7 +149,7 @@ Current Features runs https only (Apache only) * Fully automated. * Configuration changes are logged and can be reverted. -* Supports ncurses and text (-t) UI, or can be driven entirely from the +* Supports an interactive text UI, or can be driven entirely from the command line. * Free and Open Source Software, made with Python.
fixes #4622
https://api.github.com/repos/certbot/certbot/pulls/4623
2017-05-05T20:45:47Z
2017-05-08T17:54:20Z
2017-05-08T17:54:20Z
2017-05-08T17:54:26Z
468
certbot/certbot
787
Fix HiDiveIE.
diff --git a/yt_dlp/extractor/hidive.py b/yt_dlp/extractor/hidive.py index a5aa0853ce1..90457b77ea1 100644 --- a/yt_dlp/extractor/hidive.py +++ b/yt_dlp/extractor/hidive.py @@ -1,12 +1,13 @@ # coding: utf-8 from __future__ import unicode_literals +import re from .common import InfoExtractor -from ..compat import compat_str from ..utils import ( ExtractorError, int_or_none, + try_get, url_or_none, urlencode_postdata, ) @@ -57,48 +58,51 @@ def _real_extract(self, url): mobj = self._match_valid_url(url) title, key = mobj.group('title', 'key') video_id = '%s/%s' % (title, key) + webpage = self._download_webpage(url, video_id, fatal=False) + data_videos = re.findall(r'data-video=\"([^\"]+)\"\s?data-captions=\"([^\"]+)\"', webpage) + formats = [] + subtitles = {} + for data_video in data_videos: + _, _, _, version, audio, _, extra = data_video[0].split('_') + caption = data_video[1] - settings = self._download_json( - 'https://www.hidive.com/play/settings', video_id, - data=urlencode_postdata({ - 'Title': title, - 'Key': key, - 'PlayerId': 'f4f895ce1ca713ba263b91caeb1daa2d08904783', - })) + settings = self._download_json( + 'https://www.hidive.com/play/settings', video_id, + data=urlencode_postdata({ + 'Title': title, + 'Key': key, + 'PlayerId': 'f4f895ce1ca713ba263b91caeb1daa2d08904783', + 'Version': version, + 'Audio': audio, + 'Captions': caption, + 'Extra': extra, + })) - restriction = settings.get('restrictionReason') - if restriction == 'RegionRestricted': - self.raise_geo_restricted() + restriction = settings.get('restrictionReason') + if restriction == 'RegionRestricted': + self.raise_geo_restricted() - if restriction and restriction != 'None': - raise ExtractorError( - '%s said: %s' % (self.IE_NAME, restriction), expected=True) + if restriction and restriction != 'None': + raise ExtractorError( + '%s said: %s' % (self.IE_NAME, restriction), expected=True) - formats = [] - subtitles = {} - for rendition_id, rendition in settings['renditions'].items(): - bitrates = rendition.get('bitrates') - if not isinstance(bitrates, dict): - continue - m3u8_url = url_or_none(bitrates.get('hls')) - if not m3u8_url: - continue - formats.extend(self._extract_m3u8_formats( - m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native', - m3u8_id='%s-hls' % rendition_id, fatal=False)) - cc_files = rendition.get('ccFiles') - if not isinstance(cc_files, list): - continue - for cc_file in cc_files: - if not isinstance(cc_file, list) or len(cc_file) < 3: - continue - cc_lang = cc_file[0] - cc_url = url_or_none(cc_file[2]) - if not isinstance(cc_lang, compat_str) or not cc_url: + for rendition_id, rendition in settings['renditions'].items(): + m3u8_url = url_or_none(try_get(rendition, lambda x: x['bitrates']['hls'])) + if not m3u8_url: continue - subtitles.setdefault(cc_lang, []).append({ - 'url': cc_url, - }) + frmt = self._extract_m3u8_formats( + m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native', + m3u8_id='%s-%s-%s-%s' % (version, audio, extra, caption), fatal=False) + for f in frmt: + f['language'] = audio + formats.extend(frmt) + + for cc_file in rendition.get('ccFiles', []): + cc_url = url_or_none(try_get(cc_file, lambda x: x[2])) + # name is used since we cant distinguish subs with same language code + cc_lang = try_get(cc_file, (lambda x: x[1].replace(' ', '-').lower(), lambda x: x[0]), str) + if cc_url and cc_lang: + subtitles.setdefault(cc_lang, []).append({'url': cc_url}) self._sort_formats(formats) season_number = int_or_none(self._search_regex( @@ -114,4 +118,5 @@ def _real_extract(self, url): 'series': title, 'season_number': season_number, 'episode_number': episode_number, + 'http_headers': {'Referer': url} }
## Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) sections - [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) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Bug fix - [x] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information Closes https://github.com/yt-dlp/yt-dlp/issues/952 and maybe https://github.com/yt-dlp/yt-dlp/issues/408 aswell
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/958
2021-09-13T04:49:36Z
2021-09-15T02:04:54Z
2021-09-15T02:04:54Z
2021-12-30T09:46:41Z
1,218
yt-dlp/yt-dlp
7,886
Pro.bounds: Correct impact wording (minor)
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 40dcc3b08..4a154e588 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -20376,7 +20376,7 @@ Bounds safety profile summary: Bounds safety implies that access to an object - notably arrays - does not access beyond the object's memory allocation. This eliminates a large class of insidious and hard-to-find errors, including the (in)famous "buffer overflow" errors. This closes security loopholes as well as a prominent source of memory corruption (when writing out of bounds). -Even an out-of-bounds access is "just a read", it can lead to invariant violations (when the accessed isn't of the assumed type) +Even if an out-of-bounds access is "just a read", it can lead to invariant violations (when the accessed isn't of the assumed type) and "mysterious values."
Missing "if", I believe.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1316
2019-01-15T00:47:38Z
2019-01-17T00:01:17Z
2019-01-17T00:01:17Z
2019-01-17T00:01:17Z
210
isocpp/CppCoreGuidelines
15,328
Added visualize_ML
diff --git a/README.md b/README.md index f86e3669..3344da2b 100644 --- a/README.md +++ b/README.md @@ -860,6 +860,7 @@ on MNIST digits[DEEP LEARNING] * [Ruffus](http://www.ruffus.org.uk) - Computation Pipeline library for python. * [SOMPY](https://github.com/sevamoo/SOMPY) - Self Organizing Map written in Python (Uses neural networks for data analysis). * [HDBScan](https://github.com/lmcinnes/hdbscan) - implementation of the hdbscan algorithm in Python - used for clustering +* [visualize_ML](https://github.com/ayush1997/visualize_ML) - A python package for data exploration and data analysis. <a name="python-misc" /> #### Misc Scripts / iPython Notebooks / Codebases
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/319
2016-10-17T21:11:27Z
2016-10-17T21:18:38Z
2016-10-17T21:18:38Z
2016-10-17T21:18:41Z
207
josephmisiti/awesome-machine-learning
52,140
Bump slsa-framework/slsa-github-generator from 1.7.0 to 1.9.0
diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 3f368ebe08..dcc7a42ca2 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -33,7 +33,7 @@ jobs: id-token: write contents: write # Can't pin with hash due to how this workflow works. - uses: slsa-framework/slsa-github-generator/.github/workflows/[email protected] + uses: slsa-framework/slsa-github-generator/.github/workflows/[email protected] with: base64-subjects: ${{ needs.build.outputs.hash }} create-release:
Bumps [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator) from 1.7.0 to 1.9.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/slsa-framework/slsa-github-generator/releases">slsa-framework/slsa-github-generator's releases</a>.</em></p> <blockquote> <h2>v1.9.0</h2> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md">CHANGELOG</a> for details.</p> <h2>v1.9.0-rc.0</h2> <p><strong>This is an un-finalized pre-release.</strong></p> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md">CHANGELOG</a> for details.</p> <h2>v1.8.0</h2> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md#v180">CHANGELOG</a> for details.</p> <h2>v1.8.0-rc.2</h2> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md">CHANGELOG</a> for details.</p> <h2>v1.8.0-rc.1</h2> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md">CHANGELOG</a> for details.</p> <h2>v1.8.0-rc.0</h2> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/blob/HEAD/CHANGELOG.md">CHANGELOG</a> for details.</p> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/slsa-framework/slsa-github-generator/blob/main/CHANGELOG.md">slsa-framework/slsa-github-generator's changelog</a>.</em></p> <blockquote> <h2>v1.9.0</h2> <p>Release [v1.9.0] includes bug fixes and new features.</p> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/compare/v1.8.0...v1.9.0">full change list</a>.</p> <h3>v1.9.0: BYOB framework (beta)</h3> <ul> <li><strong>New</strong>: A <a href="https://github.com/slsa-framework/slsa-github-generator/blob/main/BYOB.md">new framework</a> to turn GitHub Actions into SLSA compliant builders.</li> </ul> <h3>v1.9.0: Maven builder (beta)</h3> <ul> <li><strong>New</strong>: A <a href="https://github.com/slsa-framework/slsa-github-generator/tree/main/internal/builders/maven">Maven builder</a> to build Java projects and publish to Maven central.</li> </ul> <h3>v1.9.0: Gradle builder (beta)</h3> <ul> <li><strong>New</strong>: A <a href="https://github.com/slsa-framework/slsa-github-generator/tree/main/internal/builders/gradle">Gradle builder</a> to build Java projects and publish to Maven central.</li> </ul> <h3>v1.9.0: JReleaser builder</h3> <ul> <li><strong>New</strong>: A <a href="https://github.com/jreleaser/release-action/tree/v1.0.0-java">JReleaser builder</a> that wraps the official <a href="https://github.com/jreleaser/release-action/tree/v1.0.0-java">JReleaser Action</a>.</li> </ul> <h2>v1.8.0</h2> <p>Release [v1.8.0] includes bug fixes and new features.</p> <p>See the <a href="https://github.com/slsa-framework/slsa-github-generator/compare/v1.7.0...v1.8.0">full change list</a>.</p> <h3>v1.8.0: Generic Generator</h3> <ul> <li><strong>Added</strong>: A new <a href="https://github.com/slsa-framework/slsa-github-generator/blob/v1.8.0/internal/builders/generic/README.md#workflow-inputs"><code>base64-subjects-as-file</code></a> was added to allow for specifying a large subject list.</li> </ul> <h3>v1.8.0: Node.js Builder (beta)</h3> <ul> <li><strong>Fixed</strong>: Publishing for non-scoped packages was fixed (See <a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2359">#2359</a>)</li> <li><strong>Fixed</strong>: Documentation was updated to clarify that the GitHub Actions <code>deployment</code> event is not supported.</li> <li><strong>Changed</strong>: The file extension for the generated provenance file was changed from <code>.sigstore</code> to <code>.build.slsa</code> in order to make it easier to identify provenance files regardless of file format.</li> <li><strong>Fixed</strong>: The publish action was fixed to address an issue with the package name when using Node 16.</li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/07e64b653f10a80b6510f4568f685f8b7b9ea830"><code>07e64b6</code></a> chore: v1.9.0 ref updates (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2673">#2673</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/9bc0d59bb73add013a8982b76767b428491524a7"><code>9bc0d59</code></a> chore: v1.9.0-rc.0 (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2669">#2669</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/72aeffddb180dc2b7ad16c4578f263f20ccac773"><code>72aeffd</code></a> fix: typo in maven builder (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2668">#2668</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/b6d7cbf16d3703646612f15dddf69869f0479457"><code>b6d7cbf</code></a> chore: make build dirs of java builders unique (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2665">#2665</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/7e31fad1e6c846162e8b794a6ca0d04417a17e0d"><code>7e31fad</code></a> docs: v1.9.0-rc.0 changelogs (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2648">#2648</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/5952cf4439308e9d5efb54a4b814d02fb1c9626b"><code>5952cf4</code></a> docs: Update BYOB versions in docs (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2647">#2647</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/da5bdc7cd7ddb0a53ea3e22683ce3302a79928bb"><code>da5bdc7</code></a> chore: fix wrong output in gradle builder (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2646">#2646</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/180a89c64d423565407a13e7bef4e933b50e51cc"><code>180a89c</code></a> chore: fix nits in Gradle builder (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2645">#2645</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/f89a0f4d6b7420e70a20742834490633e2e414b1"><code>f89a0f4</code></a> feat: update Gradle builder to accomodate for e2e test (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2636">#2636</a>)</li> <li><a href="https://github.com/slsa-framework/slsa-github-generator/commit/324ff12a1e3b69d9c9f586a51b8bf3f2c8067109"><code>324ff12</code></a> feat: Add directory input to Maven builder (<a href="https://redirect.github.com/slsa-framework/slsa-github-generator/issues/2538">#2538</a>)</li> <li>Additional commits viewable in <a href="https://github.com/slsa-framework/slsa-github-generator/compare/v1.7.0...v1.9.0">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=slsa-framework/slsa-github-generator&package-manager=github_actions&previous-version=1.7.0&new-version=1.9.0)](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/pallets/flask/pulls/5247
2023-09-01T16:30:32Z
2023-09-05T21:02:29Z
2023-09-05T21:02:29Z
2023-09-20T00:05:41Z
179
pallets/flask
20,120
Revise config
diff --git a/manimlib/config.py b/manimlib/config.py index 88c6632df6..3937b6338f 100644 --- a/manimlib/config.py +++ b/manimlib/config.py @@ -13,7 +13,6 @@ def parse_cli(): parser = argparse.ArgumentParser() parser.add_argument( "file", - nargs="+", help="path to file holding the python code for the scene", ) parser.add_argument(
https://api.github.com/repos/3b1b/manim/pulls/987
2020-04-17T09:51:14Z
2020-04-17T09:51:25Z
2020-04-17T09:51:25Z
2020-04-17T09:51:30Z
107
3b1b/manim
18,166
cryptocom fetchMarkets enhancement
diff --git a/js/cryptocom.js b/js/cryptocom.js index 383866f42957..2cf3b34d0ebb 100644 --- a/js/cryptocom.js +++ b/js/cryptocom.js @@ -329,7 +329,12 @@ module.exports = class cryptocom extends Exchange { // margin_trading_enabled_5x: true, // margin_trading_enabled_10x: true, // max_quantity: '100000000', - // min_quantity: '0.01' + // min_quantity: '0.01', + // max_price:'1', + // min_price:'0.00000001', + // last_update_date:1667263094857, + // quantity_tick_size:'0.1', + // price_tick_size:'0.00000001' // }, // ] // } @@ -345,8 +350,7 @@ module.exports = class cryptocom extends Exchange { const quoteId = this.safeString (market, 'quote_currency'); const base = this.safeCurrencyCode (baseId); const quote = this.safeCurrencyCode (quoteId); - const priceDecimals = this.safeString (market, 'price_decimals'); - const minPrice = this.parsePrecision (priceDecimals); + const minPrice = this.safeString (market, 'min_price'); const minQuantity = this.safeString (market, 'min_quantity'); let maxLeverage = this.parseNumber ('1'); const margin_trading_enabled_5x = this.safeValue (market, 'margin_trading_enabled_5x'); @@ -382,8 +386,8 @@ module.exports = class cryptocom extends Exchange { 'strike': undefined, 'optionType': undefined, 'precision': { - 'amount': this.parseNumber (this.parsePrecision (this.safeString (market, 'quantity_decimals'))), - 'price': this.parseNumber (this.parsePrecision (priceDecimals)), + 'amount': this.safeNumber (market, 'quantity_tick_size'), + 'price': this.safeNumber (market, 'price_tick_size'), }, 'limits': { 'leverage': { @@ -396,7 +400,7 @@ module.exports = class cryptocom extends Exchange { }, 'price': { 'min': this.parseNumber (minPrice), - 'max': undefined, + 'max': this.safeNumber (market, 'max_price'), }, 'cost': { 'min': this.parseNumber (Precise.stringMul (minQuantity, minPrice)),
https://github.com/ccxt/ccxt/issues/15546 https://api.crypto.com/v2/public/get-instruments
https://api.github.com/repos/ccxt/ccxt/pulls/15791
2022-11-22T17:11:26Z
2022-11-24T16:14:55Z
2022-11-24T16:14:55Z
2022-11-24T16:14:55Z
575
ccxt/ccxt
13,246
ua-UK translation improvements
diff --git a/website/public/locales/uk-UA/chat.json b/website/public/locales/uk-UA/chat.json index 569dc120dc..d92574f48f 100644 --- a/website/public/locales/uk-UA/chat.json +++ b/website/public/locales/uk-UA/chat.json @@ -1,13 +1,13 @@ { - "back_to_chat_list": "Повернутись до діалогів", + "back_to_chat_list": "Повернутись до чатів", "chat_date": "{{val, datetime}}", - "config_title": "Налаштування діалогу", + "config_title": "Налаштування чату", "empty": "(порожньо)", - "login_message": "Щоб користуватись діалогами, вам необхідно знову увійти в систему. Використайте один з способів нижче:", + "login_message": "Щоб користуватись чатами, вам необхідно знову увійти в систему. Використайте один з способів нижче:", "model": "Модель", "preset": "Пресет", "preset_custom": "Власний пресет", "queue_info": "Ваше повідомлення знаходиться в черзі, ви на позиції {{ queuePosition, number, integer }}.", - "you_are_logged_in": "Ви увійшли в систему діалогів", - "your_chats": "Ваші діалоги" + "you_are_logged_in": "Ви увійшли в чат-сервіс.", + "your_chats": "Ваші чати" } diff --git a/website/public/locales/uk-UA/common.json b/website/public/locales/uk-UA/common.json index 9598613fd2..1813f48a40 100644 --- a/website/public/locales/uk-UA/common.json +++ b/website/public/locales/uk-UA/common.json @@ -1,17 +1,17 @@ { "about": "Про проєкт", - "account_settings": "Аккаунт", + "account_settings": "Акаунт", "admin_dashboard": "Панель адміністратора", "back_to_dashboard": "Повернутися до панелі", "bug_button": "Повідомити про помилку", "bug_description": "Якщо ви намагалися внести дані, але опинилися тут, повідомте про помилку.", "cancel": "Скасувати", "confirm": "Підтвердити", - "connect": "Приєднати", + "connect": "Долучитись", "conversational": "Розмовний ШІ для кожного.", "copied": "Скопійовано", - "create_chat": "Створити діалог", - "chat": "Діалог", + "create_chat": "Створити чат", + "chat": "Чат", "dark_mode": "Темний режим", "dashboard_home": "Головна панель", "dashboard": "Головна", @@ -21,7 +21,7 @@ "edit": "Редагувати", "faq": "FAQ", "github": "GitHub", - "guidelines": "Рекомендації (англ.)", + "guidelines": "Рекомендації", "leaderboard": "Рейтинг лідерів", "legal": "Юридична інформація", "submit_your_answer": "Надішліть свою відповідь", @@ -34,14 +34,15 @@ "send": "Надіслати", "sorry_404": "Вибачте, сторінку не знайдено.", "submit": "Надіслати", - "output": "Висновок", + "output": "Результат", "parameters": "Параметр", "skip": "Пропустити", - "prompt": "Підказка", + "prompt": "Запит", "privacy_policy": "Політика конфіденційності", "report_a_bug": "Сповістити про помилку", + "retry": "Повторити", "review": "Огляд", - "sign_in": "Війти", + "sign_in": "Увійти", "sign_out": "Вийти", "status_dashboard": "Панель статусів", "status": "Статус", diff --git a/website/public/locales/uk-UA/index.json b/website/public/locales/uk-UA/index.json index e06a38faba..36ae7e1122 100644 --- a/website/public/locales/uk-UA/index.json +++ b/website/public/locales/uk-UA/index.json @@ -17,7 +17,9 @@ "a5": "Буде випущено версії, запуск яких буде можливий на споживчому обладнанні." }, "faq_title": "Поширені питання", - "join_us_description": "Усі проєкти з відкритим кодом починаються з таких людей, як ви. Відкритий код - це віра в те, що якщо ми будемо співпрацювати разом, ми зможемо поділитися своїми знаннями та технологіями зі світом на благо людства. Ви з нами? Знайди нас тут:", + "help_us_improve": "Допоможіть нам покращитись", + "join_us_description": "Усі проєкти з відкритим кодом починаються з таких людей, як ви. Відкритий код - це віра в те, що якщо ми будемо співпрацювати разом, ми зможемо поділитися своїми знаннями та технологіями зі світом на благо людства. Ви з нами? Знайдіть нас тут:", "join_us_title": "Приєднуйтесь до нас", - "subtitle": "Розмовний ШІ для всіх." + "subtitle": "Розмовний ШІ для всіх.", + "try_our_assistant": "Спробуйте нашого асистента" } diff --git a/website/public/locales/uk-UA/labelling.json b/website/public/locales/uk-UA/labelling.json index 2a9a9db34f..901f7f5b38 100644 --- a/website/public/locales/uk-UA/labelling.json +++ b/website/public/locales/uk-UA/labelling.json @@ -1,36 +1,36 @@ { - "accurate": "Точний", - "apolitical": "Аполітичний", - "appropriate": "Відповідний", - "boring": "Нудний", - "clean": "Чистий", + "accurate": "Точне", + "apolitical": "Аполітичне", + "appropriate": "Доречне", + "boring": "Нудне", + "clean": "Чисте", "contains_pii": "Містить PII", - "contains_pii.one_desc": "Містить ідентифікуючу особу інформацію", - "creative": "Творчий", + "contains_pii.one_desc": "Містить персональні дані", + "creative": "Творче", "creative.one_desc.line_1": "Наскільки рідкісне це запитання? Чи потребує воно творчого мислення від асистента?", "creative.one_desc.line_2": "Чи містить запитання багато контексту? З боку асистента, чи є відповідь простою, чи вона містить унікальний підхід до проблеми?", "fails_task": "Не вдається виконати завдання", "fails_task.one_desc": "Не вдається виконати правильну інструкцію / завдання", "fails_task.question": "Чи є це поганою відповіддю, у відповідності до поставленого завдання?", "follows_instructions": "Дотримуватися інструкції", - "harmful": "Шкідливий", + "harmful": "Шкідливе", "harmful.one_desc.line_1": "Вміст, який може завдати надмірної шкоди, не виправданий у контексті", "harmful.one_desc.line_2": "Шкода відноситься до фізичної чи психічної шкоди або травмування когось чи чогось. Надмірне відноситься до розумного порогу шкоди в даному контексті, наприклад, пошкодження шкіри не є надмірним в контексті хірургічного втручання.", - "harmless": "Нешкідливий", + "harmless": "Нешкідливе", "hate_speech": "Розпалювання ненависті", "hate_speech.explanation": "Контент є образливим або погрозливим і виражає упередження щодо захищеної ознаки. Упередження - це упереджені погляди, що не ґрунтуються на розумінні. До захищених ознак належать стать, етнічна приналежність, релігія, сексуальна орієнтація та подібні характеристики.", - "hateful": "Ненависний", + "hateful": "Ненависне", "hateful.one_desc.line_1": "Вміст є образливим або загрозливим і виражає упередження щодо захищеної характеристики", "hateful.one_desc.line_2": "Упередження стосується упереджених поглядів, не заснованих на розумі. Захищені характеристики включають стать, етнічну приналежність, релігію, сексуальну орієнтацію та подібні характеристики.", - "helpful": "Корисний", + "helpful": "Корисне", "helpful.one_desc": "Виконує завдання на високому рівні", - "ordinary": "Звичайний", + "ordinary": "Звичайне", "high_quality": "Висока якість", - "humorous": "Гумористичний", + "humorous": "Гумористичне", "humorous.one_desc": "Містить гумористичний контент, включаючи сарказм", - "inappropriate": "Недоречно", - "inappropriate.one_desc": "Не підходить для помічника по роботі з клієнтами", - "judgemental": "Який засуджує", + "inappropriate": "Недоречне", + "inappropriate.one_desc": "Недоречне для помічника (Асистента)", + "judgemental": "Засуджуюче", "judgemental.one_desc": "Висловлює моральне судження", "label_highlighted_flag_instruction": "Виберіть те, що підходить для виділеного повідомлення:", "label_highlighted_likert_instruction": "Оцініть виділене повідомлення:", @@ -42,39 +42,39 @@ "lang_mismatch.explanation": "Не записано такою мовою: {{language}}.", "low_quality": "Низька якість", "misleading": "Вводить в оману", - "non_judgemental": "Неупереджений", - "non_sexual": "Несексуальний", - "not_spam": "Нi спам", + "non_judgemental": "Неупереджене", + "non_sexual": "Несексуальне", + "not_spam": "Не спам", "not_spam.explanation": "Підходить для навчання Open Assistant.", "misleading.one_desc": "Містить текст, який є неправильним або вводить в оману", "moral_judgement": "Моральне судження", "moral_judgement.explanation": "Висловлює моральне судження.", - "not_appropriate": "Недоречно", + "not_appropriate": "Недоречне", "not_appropriate.explanation": "Недоречно для асистента.", "pii": "Містить особисті дані", "pii.explanation": "Містить інформацію, що ідентифікує особу. Приклади включають особисті контактні дані, деталі паспорта та інших документів, що посвідчують особу, а також банківські реквізити.", - "polite": "Ввічливий", + "polite": "Ввічливе", "political_content": "Політичне", "political_content.explanation": "Висловлює політичні погляди.", "sexual_content": "Зміст сексуального характеру", "sexual_content.explanation": "Містить матеріали сексуального характеру.", "spam.question": "Це повідомлення є спамом?", - "rude": "Грубий", - "political": "Політичний", + "rude": "Грубе", + "political": "Політичне", "rude.one_desc": "Містить грубий, образливий, непристойний або образливий контент", - "safe": "Безпечно", - "serious": "Серйозний", + "safe": "Безпечне", + "serious": "Серйозне", "spam": "Спам", "political.one_desc": "Висловлює політичні погляди", "spam.one_desc.line_1": "Здається навмисно неякісним або недоречним", "spam.one_desc.line_2": "Ми розглядаємо наступний небажаний вміст як спам: тролінг, навмисне підрив нашої мети, незаконні матеріали, матеріали, що порушують наш кодекс поведінки, та інші речі, які не підходять для нашого набору даних. Ми збираємо їх під загальним заголовком 'спам'.", "spam.one_desc.line_3": "Це не оцінка того, чи є це повідомлення найкращою можливою відповіддю. Особливо для запитів або відповідей користувачів, ми дуже хочемо зберегти всі види відповідей у наборі даних, щоб помічник міг навчитися відповідати відповідним чином.", "spam.one_desc.line_4": "Будь ласка, позначте цей текст як спам, лише якщо він явно не підходить для включення до нашого набору даних, як описано вище, і намагайтеся не робити жодних суб'єктивних оціночних суджень.", - "sexual": "Сексуальний", + "sexual": "Сексуальне", "sexual.one_desc": "Містить сексуальний зміст", - "threatening": "Загрозливий", + "threatening": "Загрозливе", "threatening.one_desc": "Містить погрозу щодо особи чи осіб", - "unhelpful": "Марний", - "violent": "Насильницький", + "unhelpful": "Марне", + "violent": "Насильницьке", "violent.one_desc": "Заохочує або не перешкоджає насильству/жорстокому поводженню/тероризму/заподіянню собі шкоди" } diff --git a/website/public/locales/uk-UA/leaderboard.json b/website/public/locales/uk-UA/leaderboard.json index 749830514c..f491c53a4c 100644 --- a/website/public/locales/uk-UA/leaderboard.json +++ b/website/public/locales/uk-UA/leaderboard.json @@ -1,7 +1,7 @@ { "accepted": "↪ Прийнято", - "accepted_prompts": "Прийняті підказки", - "daily": "Щодня", + "accepted_prompts": "Прийняті запити", + "daily": "За день", "day": "День", "good_rankings": "Хороші рейтинги", "label": "Маркувань", @@ -32,8 +32,8 @@ "total": "Всього", "username": "Ім'я користувача", "week": "Тиждень", - "weekly": "Щотижня", + "weekly": "За тиждень", "xp_progress_message": "Вам потрібно {{need, number, integer}} балів щоб досягти наступного рівня!", - "your_account": "Ваш аккаунт", + "your_account": "Ваш акаунт", "your_stats": "Ваша статистика" }
Improve wording and fix mistakes in ua-UK locale strings. Translate new strings.
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/2442
2023-04-10T11:54:29Z
2023-04-10T14:47:34Z
2023-04-10T14:47:34Z
2023-04-10T14:47:34Z
3,906
LAION-AI/Open-Assistant
37,015
Py3k minor fixes
diff --git a/letsencrypt/cli.py b/letsencrypt/cli.py index 3551d5a1072..d8b1a60395b 100644 --- a/letsencrypt/cli.py +++ b/letsencrypt/cli.py @@ -19,6 +19,7 @@ import configargparse import OpenSSL +import six import zope.component import zope.interface.exceptions import zope.interface.verify @@ -842,7 +843,7 @@ def _restore_plugin_configs(config, renewalparams): if renewalparams.get("installer", None) is not None: plugin_prefixes.append(renewalparams["installer"]) for plugin_prefix in set(plugin_prefixes): - for config_item, config_value in renewalparams.iteritems(): + for config_item, config_value in six.iteritems(renewalparams): if config_item.startswith(plugin_prefix + "_") and not _set_by_cli(config_item): # Values None, True, and False need to be treated specially, # As they don't get parsed correctly based on type @@ -1159,10 +1160,10 @@ class HelpfulArgumentParser(object): # List of topics for which additional help can be provided HELP_TOPICS = ["all", "security", - "paths", "automation", "testing"] + VERBS.keys() + "paths", "automation", "testing"] + list(six.iterkeys(VERBS)) def __init__(self, args, plugins, detect_defaults=False): - plugin_names = [name for name, _p in plugins.iteritems()] + plugin_names = list(six.iterkeys(plugins)) self.help_topics = self.HELP_TOPICS + plugin_names + [None] usage, short_usage = usage_strings(plugins) self.parser = configargparse.ArgParser( @@ -1432,7 +1433,7 @@ def add_plugin_args(self, plugins): may or may not be displayed as help topics. """ - for name, plugin_ep in plugins.iteritems(): + for name, plugin_ep in six.iteritems(plugins): parser_or_group = self.add_group(name, description=plugin_ep.description) #print(parser_or_group) plugin_ep.plugin_cls.inject_parser_options(parser_or_group, name) @@ -1827,7 +1828,7 @@ def _process_domain(args_or_config, domain_arg, webroot_path=None): class WebrootMapProcessor(argparse.Action): # pylint: disable=missing-docstring def __call__(self, parser, args, webroot_map_arg, option_string=None): webroot_map = json.loads(webroot_map_arg) - for domains, webroot_path in webroot_map.iteritems(): + for domains, webroot_path in six.iteritems(webroot_map): _process_domain(args, domains, [webroot_path]) diff --git a/letsencrypt/plugins/webroot_test.py b/letsencrypt/plugins/webroot_test.py index 7a34b3fcc0e..8c1427340b6 100644 --- a/letsencrypt/plugins/webroot_test.py +++ b/letsencrypt/plugins/webroot_test.py @@ -1,4 +1,7 @@ """Tests for letsencrypt.plugins.webroot.""" + +from __future__ import print_function + import errno import os import shutil @@ -74,7 +77,7 @@ def test_prepare_reraises_other_errors(self): os.chmod(self.path, 0o000) try: open(permission_canary, "r") - print "Warning, running tests as root skips permissions tests..." + print("Warning, running tests as root skips permissions tests...") except IOError: # ok, permissions work, test away... self.assertRaises(errors.PluginError, self.auth.prepare) diff --git a/letsencrypt/reporter.py b/letsencrypt/reporter.py index 81106be34de..147928e3c02 100644 --- a/letsencrypt/reporter.py +++ b/letsencrypt/reporter.py @@ -4,10 +4,10 @@ import collections import logging import os -import Queue import sys import textwrap +from six.moves import queue # pylint: disable=import-error import zope.interface from letsencrypt import interfaces @@ -21,7 +21,7 @@ class Reporter(object): """Collects and displays information to the user. - :ivar `Queue.PriorityQueue` messages: Messages to be displayed to + :ivar `queue.PriorityQueue` messages: Messages to be displayed to the user. """ @@ -36,7 +36,7 @@ class Reporter(object): _msg_type = collections.namedtuple('ReporterMsg', 'priority text on_crash') def __init__(self): - self.messages = Queue.PriorityQueue() + self.messages = queue.PriorityQueue() def add_message(self, msg, priority, on_crash=True): """Adds msg to the list of messages to be printed. diff --git a/letsencrypt/storage.py b/letsencrypt/storage.py index 6786ac7450b..cff2d53e178 100644 --- a/letsencrypt/storage.py +++ b/letsencrypt/storage.py @@ -694,7 +694,7 @@ def new_lineage(cls, lineagename, cert, privkey, chain, cli_config): for i in (cli_config.renewal_configs_dir, cli_config.archive_dir, cli_config.live_dir): if not os.path.exists(i): - os.makedirs(i, 0700) + os.makedirs(i, 0o700) logger.debug("Creating directory %s.", i) config_file, config_filename = le_util.unique_lineage_name( cli_config.renewal_configs_dir, lineagename) diff --git a/letsencrypt/tests/cli_test.py b/letsencrypt/tests/cli_test.py index aef3447c3ec..64d6beaae84 100644 --- a/letsencrypt/tests/cli_test.py +++ b/letsencrypt/tests/cli_test.py @@ -1,15 +1,18 @@ """Tests for letsencrypt.cli.""" + +from __future__ import print_function + import argparse import functools import itertools import os import shutil -import StringIO import traceback import tempfile import unittest import mock +import six from acme import jose @@ -81,7 +84,7 @@ def test_no_flags(self): def _help_output(self, args): "Run a command, and return the ouput string for scrutiny" - output = StringIO.StringIO() + output = six.StringIO() with mock.patch('letsencrypt.cli.sys.stdout', new=output): self.assertRaises(SystemExit, self._call_stdout, args) out = output.getvalue() @@ -580,7 +583,7 @@ def _test_renewal_common(self, due_for_renewal, extra_args, log_out=None, try: ret, _, _, _ = self._call(args) if ret: - print "Returned", ret + print("Returned", ret) raise AssertionError(ret) assert not error_expected, "renewal should have errored" except: # pylint: disable=bare-except @@ -628,8 +631,8 @@ def test_certonly_renewal_triggers(self): def _dump_log(self): with open(os.path.join(self.logs_dir, "letsencrypt.log")) as lf: - print "Logs:" - print lf.read() + print("Logs:") + print(lf.read()) def _make_test_renewal_conf(self, testfile): diff --git a/letsencrypt/tests/colored_logging_test.py b/letsencrypt/tests/colored_logging_test.py index 5b49ec82067..4080157fce8 100644 --- a/letsencrypt/tests/colored_logging_test.py +++ b/letsencrypt/tests/colored_logging_test.py @@ -1,8 +1,9 @@ """Tests for letsencrypt.colored_logging.""" import logging -import StringIO import unittest +import six + from letsencrypt import le_util @@ -12,7 +13,7 @@ class StreamHandlerTest(unittest.TestCase): def setUp(self): from letsencrypt import colored_logging - self.stream = StringIO.StringIO() + self.stream = six.StringIO() self.stream.isatty = lambda: True self.handler = colored_logging.StreamHandler(self.stream) diff --git a/letsencrypt/tests/le_util_test.py b/letsencrypt/tests/le_util_test.py index 87894f837b9..191b70801ab 100644 --- a/letsencrypt/tests/le_util_test.py +++ b/letsencrypt/tests/le_util_test.py @@ -4,11 +4,11 @@ import os import shutil import stat -import StringIO import tempfile import unittest import mock +import six from letsencrypt import errors @@ -307,14 +307,14 @@ def test_warning_with_arg(self): self.assertTrue("--old-option is deprecated" in stderr) def _get_argparse_warnings(self, args): - stderr = StringIO.StringIO() + stderr = six.StringIO() with mock.patch("letsencrypt.le_util.sys.stderr", new=stderr): self.parser.parse_args(args) return stderr.getvalue() def test_help(self): self._call("--old-option", 2) - stdout = StringIO.StringIO() + stdout = six.StringIO() with mock.patch("letsencrypt.le_util.sys.stdout", new=stdout): try: self.parser.parse_args(["-h"]) diff --git a/letsencrypt/tests/reporter_test.py b/letsencrypt/tests/reporter_test.py index c848b1cabcd..26a1105c847 100644 --- a/letsencrypt/tests/reporter_test.py +++ b/letsencrypt/tests/reporter_test.py @@ -1,8 +1,9 @@ """Tests for letsencrypt.reporter.""" -import StringIO import sys import unittest +import six + class ReporterTest(unittest.TestCase): """Tests for letsencrypt.reporter.Reporter.""" @@ -12,7 +13,7 @@ def setUp(self): self.reporter = reporter.Reporter() self.old_stdout = sys.stdout - sys.stdout = StringIO.StringIO() + sys.stdout = six.StringIO() def tearDown(self): sys.stdout = self.old_stdout diff --git a/letshelp-letsencrypt/letshelp_letsencrypt/apache.py b/letshelp-letsencrypt/letshelp_letsencrypt/apache.py index ac4e9b83132..d7cb05b70d7 100755 --- a/letshelp-letsencrypt/letshelp_letsencrypt/apache.py +++ b/letshelp-letsencrypt/letshelp_letsencrypt/apache.py @@ -1,5 +1,8 @@ #!/usr/bin/env python """Let's Encrypt Apache configuration submission script""" + +from __future__ import print_function + import argparse import atexit import contextlib @@ -48,20 +51,20 @@ def make_and_verify_selection(server_root, temp_dir): """ copied_files, copied_dirs = copy_config(server_root, temp_dir) - print textwrap.fill("A secure copy of the files that have been selected " + print(textwrap.fill("A secure copy of the files that have been selected " "for submission has been created under {0}. All " "comments have been removed and the files are only " "accessible by the current user. A list of the files " "that have been included is shown below. Please make " "sure that this selection does not contain private " "keys, passwords, or any other sensitive " - "information.".format(temp_dir)) - print "\nFiles:" + "information.".format(temp_dir))) + print("\nFiles:") for copied_file in copied_files: - print copied_file - print "Directories (including all contained files):" + print(copied_file) + print("Directories (including all contained files):") for copied_dir in copied_dirs: - print copied_dir + print(copied_dir) sys.stdout.write("\nIs it safe to submit these files? ") while True:
A small bundle of Python 3 compatibility fixes. This represents all the small and simple Python 3 touchups required to get `letsencrypt --help` up and running. There's some slightly larger changes, but they will be in a separate PR.
https://api.github.com/repos/certbot/certbot/pulls/2513
2016-02-20T09:20:03Z
2016-03-02T00:11:47Z
2016-03-02T00:11:47Z
2016-08-28T21:58:40Z
2,674
certbot/certbot
636
Add additional path separator normalization
diff --git a/keras/saving/saving_lib.py b/keras/saving/saving_lib.py index c8fcde56b17..7342bcc8f22 100644 --- a/keras/saving/saving_lib.py +++ b/keras/saving/saving_lib.py @@ -245,8 +245,12 @@ def _write_to_zip_recursively(zipfile_to_save, system_path, zip_path): zipfile_to_save.write(system_path, zip_path) else: for file_name in file_utils.listdir(system_path): - system_file_path = file_utils.join(system_path, file_name) - zip_file_path = file_utils.join(zip_path, file_name) + system_file_path = file_utils.join(system_path, file_name).replace( + "\\", "/" + ) + zip_file_path = file_utils.join(zip_path, file_name).replace( + "\\", "/" + ) _write_to_zip_recursively( zipfile_to_save, system_file_path, zip_file_path ) @@ -308,7 +312,9 @@ def _save_state( child_obj, weights_store, assets_store, - inner_path=file_utils.join(inner_path, child_attr), + inner_path=file_utils.join(inner_path, child_attr).replace( + "\\", "/" + ), visited_trackables=visited_trackables, ) elif isinstance(child_obj, (list, dict, tuple, set)): @@ -316,7 +322,9 @@ def _save_state( child_obj, weights_store, assets_store, - inner_path=file_utils.join(inner_path, child_attr), + inner_path=file_utils.join(inner_path, child_attr).replace( + "\\", "/" + ), visited_trackables=visited_trackables, ) @@ -370,7 +378,9 @@ def _load_state( child_obj, weights_store, assets_store, - inner_path=file_utils.join(inner_path, child_attr), + inner_path=file_utils.join(inner_path, child_attr).replace( + "\\", "/" + ), skip_mismatch=skip_mismatch, visited_trackables=visited_trackables, ) @@ -379,7 +389,9 @@ def _load_state( child_obj, weights_store, assets_store, - inner_path=file_utils.join(inner_path, child_attr), + inner_path=file_utils.join(inner_path, child_attr).replace( + "\\", "/" + ), skip_mismatch=skip_mismatch, visited_trackables=visited_trackables, ) @@ -407,7 +419,7 @@ def _save_container_state( trackable, weights_store, assets_store, - inner_path=file_utils.join(inner_path, name), + inner_path=file_utils.join(inner_path, name).replace("\\", "/"), visited_trackables=visited_trackables, ) @@ -436,7 +448,7 @@ def _load_container_state( trackable, weights_store, assets_store, - inner_path=file_utils.join(inner_path, name), + inner_path=file_utils.join(inner_path, name).replace("\\", "/"), skip_mismatch=skip_mismatch, visited_trackables=visited_trackables, ) @@ -461,7 +473,9 @@ def __init__(self, root_path, archive=None, mode=None): self.tmp_dir = get_temp_dir() if self.mode == "r": self.archive.extractall(path=self.tmp_dir) - self.working_dir = file_utils.join(self.tmp_dir, self.root_path) + self.working_dir = file_utils.join( + self.tmp_dir, self.root_path + ).replace("\\", "/") if self.mode == "w": file_utils.makedirs(self.working_dir) else: @@ -469,13 +483,15 @@ def __init__(self, root_path, archive=None, mode=None): self.working_dir = root_path else: self.tmp_dir = get_temp_dir() - self.working_dir = file_utils.join(self.tmp_dir, self.root_path) + self.working_dir = file_utils.join( + self.tmp_dir, self.root_path + ).replace("\\", "/") file_utils.makedirs(self.working_dir) def make(self, path): if not path: return self.working_dir - path = file_utils.join(self.working_dir, path) + path = file_utils.join(self.working_dir, path).replace("\\", "/") if not file_utils.exists(path): file_utils.makedirs(path) return path @@ -483,7 +499,7 @@ def make(self, path): def get(self, path): if not path: return self.working_dir - path = file_utils.join(self.working_dir, path) + path = file_utils.join(self.working_dir, path).replace("\\", "/") if file_utils.exists(path): return path return None
These extend off of #18579, adding more path normalization for full coverage in saving_lib.py.
https://api.github.com/repos/keras-team/keras/pulls/18588
2023-10-10T21:47:55Z
2023-10-10T22:38:21Z
2023-10-10T22:38:21Z
2023-10-13T17:30:31Z
1,075
keras-team/keras
47,206
DOC: how to revert MultiIndex.to_flat_index
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index c80dadcc42022..ad10b41093f27 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1787,6 +1787,10 @@ def to_flat_index(self): pd.Index Index with the MultiIndex data represented in Tuples. + See Also + -------- + MultiIndex.from_tuples : Convert flat index back to MultiIndex. + Notes ----- This method will simply return the caller if called by anything other
Took me way too long to figure this out. Hopefully this benefits someone else!
https://api.github.com/repos/pandas-dev/pandas/pulls/38911
2021-01-02T23:28:30Z
2021-01-04T01:12:07Z
2021-01-04T01:12:07Z
2021-01-04T01:12:59Z
142
pandas-dev/pandas
45,528
[AIRFLOW-3370] Add stdout output options to Elasticsearch task log ha…
diff --git a/airflow/utils/log/es_task_handler.py b/airflow/utils/log/es_task_handler.py index bc2c38aacd615..ae2025ce03708 100644 --- a/airflow/utils/log/es_task_handler.py +++ b/airflow/utils/log/es_task_handler.py @@ -53,7 +53,7 @@ class ElasticsearchTaskHandler(FileTaskHandler, LoggingMixin): def __init__(self, base_log_folder, filename_template, log_id_template, end_of_log_mark, - write_stdout, json_format, record_labels, + write_stdout, json_format, json_fields, host='localhost:9200'): """ :param base_log_folder: base folder to store logs locally @@ -73,7 +73,7 @@ def __init__(self, base_log_folder, filename_template, self.end_of_log_mark = end_of_log_mark self.write_stdout = write_stdout self.json_format = json_format - self.record_labels = [label.strip() for label in record_labels.split(",")] + self.json_fields = [label.strip() for label in json_fields.split(",")] self.handler = None def _render_log_id(self, ti, try_number): diff --git a/tests/utils/log/test_es_task_handler.py b/tests/utils/log/test_es_task_handler.py index 7b501a2c8e93c..56428ec82548b 100644 --- a/tests/utils/log/test_es_task_handler.py +++ b/tests/utils/log/test_es_task_handler.py @@ -230,6 +230,15 @@ def test_set_context(self): self.es_task_handler.set_context(self.ti) self.assertTrue(self.es_task_handler.mark_end_on_close) + def test_set_context_w_json_format_and_write_stdout(self): + self.es_task_handler.formatter = mock.MagicMock() + self.es_task_handler.formatter._fmt = mock.MagicMock() + self.es_task_handler.formatter._fmt.find = mock.MagicMock(return_value=1) + self.es_task_handler.writer = mock.MagicMock() + self.es_task_handler.write_stdout = True + self.es_task_handler.json_format = True + self.es_task_handler.set_context(self.ti) + def test_close(self): self.es_task_handler.set_context(self.ti) self.es_task_handler.close()
### Jira - [x] My PR addresses the following [Airflow Jira](https://issues.apache.org/jira/browse/AIRFLOW/) issues and references them in the PR title. For example, "\[AIRFLOW-3370\] My Airflow PR" - https://issues.apache.org/jira/browse/AIRFLOW-3370 ### Description Fix inconsistency in ElasticsearchTaskHandler class. Rename `record_labels` to `json_fields` - [x] Here are some details about my PR, including screenshots of any UI changes: ### Code Quality - [x] Passes `flake8`
https://api.github.com/repos/apache/airflow/pulls/5667
2019-07-26T18:49:32Z
2019-07-26T20:55:08Z
2019-07-26T20:55:08Z
2019-07-26T20:55:09Z
506
apache/airflow
14,839
Update start
diff --git a/start b/start index 8e7053030f..57cf2726b6 100755 --- a/start +++ b/start @@ -71,7 +71,7 @@ function createDesktopStartup() { echo "$DESKFILE already exists" return else - echo "$DESKFILE does not exist,ctreat a new one" + echo "$DESKFILE does not exist,create a new one" fi NAME="XX-Net" EXEC="$SCRIPTPATH/start > /dev/null"
correct typo
https://api.github.com/repos/XX-net/XX-Net/pulls/5401
2017-05-01T13:39:51Z
2017-05-03T01:25:37Z
2017-05-03T01:25:37Z
2017-05-03T01:25:37Z
121
XX-net/XX-Net
17,186
[rllib] Add type annotations to Trainer class
diff --git a/rllib/agents/trainer.py b/rllib/agents/trainer.py index 5b4221d6878a8..696f63b5cc3bb 100644 --- a/rllib/agents/trainer.py +++ b/rllib/agents/trainer.py @@ -6,25 +6,29 @@ import pickle import time import tempfile +from typing import Callable, List, Dict, Union, Any import ray from ray.exceptions import RayError from ray.rllib.agents.callbacks import DefaultCallbacks +from ray.rllib.env import EnvType from ray.rllib.env.normalize_actions import NormalizeActionWrapper from ray.rllib.models import MODEL_DEFAULTS +from ray.rllib.policy import Policy, PolicyID from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.evaluation.metrics import collect_metrics from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.utils import FilterManager, deep_update, merge_dicts -from ray.rllib.utils.framework import check_framework, try_import_tf +from ray.rllib.utils.framework import check_framework, try_import_tf, \ + TensorStructType from ray.rllib.utils.annotations import override, PublicAPI, DeveloperAPI from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning from ray.tune.registry import ENV_CREATOR, register_env, _global_registry from ray.tune.trainable import Trainable from ray.tune.trial import ExportFormat from ray.tune.resources import Resources -from ray.tune.logger import UnifiedLogger +from ray.tune.logger import Logger, UnifiedLogger from ray.tune.result import DEFAULT_RESULTS_DIR tf = try_import_tf() @@ -401,7 +405,10 @@ class Trainer(Trainable): _override_all_subkeys_if_type_changes = ["exploration_config"] @PublicAPI - def __init__(self, config=None, env=None, logger_creator=None): + def __init__(self, + config: dict = None, + env: str = None, + logger_creator: Callable[[], Logger] = None): """Initialize an RLLib trainer. Args: @@ -445,7 +452,7 @@ def default_logger_creator(config): @classmethod @override(Trainable) - def default_resource_request(cls, config): + def default_resource_request(cls, config: dict) -> Resources: cf = dict(cls._default_config, **config) Trainer._validate_config(cf) num_workers = cf["num_workers"] + cf["evaluation_num_workers"] @@ -463,7 +470,7 @@ def default_resource_request(cls, config): @override(Trainable) @PublicAPI - def train(self): + def train(self) -> dict: """Overrides super.train to synchronize global vars.""" if self._has_policy_optimizer(): @@ -524,14 +531,14 @@ def _sync_filters_if_needed(self, workers): workers.local_worker().filters)) @override(Trainable) - def _log_result(self, result): + def _log_result(self, result: dict): self.callbacks.on_train_result(trainer=self, result=result) # log after the callback is invoked, so that the user has a chance # to mutate the result Trainable._log_result(self, result) @override(Trainable) - def _setup(self, config): + def _setup(self, config: dict): env = self._env_id if env: config["env"] = env @@ -642,7 +649,7 @@ def _stop(self): self.optimizer.stop() @override(Trainable) - def _save(self, checkpoint_dir): + def _save(self, checkpoint_dir: str) -> str: checkpoint_path = os.path.join(checkpoint_dir, "checkpoint-{}".format(self.iteration)) pickle.dump(self.__getstate__(), open(checkpoint_path, "wb")) @@ -650,12 +657,14 @@ def _save(self, checkpoint_dir): return checkpoint_path @override(Trainable) - def _restore(self, checkpoint_path): + def _restore(self, checkpoint_path: str): extra_data = pickle.load(open(checkpoint_path, "rb")) self.__setstate__(extra_data) @DeveloperAPI - def _make_workers(self, env_creator, policy, config, num_workers): + def _make_workers(self, env_creator: Callable[[dict], EnvType], + policy: type, config: dict, + num_workers: int) -> WorkerSet: """Default factory method for a WorkerSet running under this Trainer. Override this method by passing a custom `make_workers` into @@ -689,7 +698,7 @@ def _init(self, config, env_creator): raise NotImplementedError @DeveloperAPI - def _evaluate(self): + def _evaluate(self) -> dict: """Evaluates current policy under `evaluation_config` settings. Note that this default implementation does not do anything beyond @@ -744,14 +753,14 @@ def _before_evaluate(self): @PublicAPI def compute_action(self, - observation, - state=None, - prev_action=None, - prev_reward=None, - info=None, - policy_id=DEFAULT_POLICY_ID, - full_fetch=False, - explore=None): + observation: TensorStructType, + state: List[Any] = None, + prev_action: TensorStructType = None, + prev_reward: int = None, + info: dict = None, + policy_id: PolicyID = DEFAULT_POLICY_ID, + full_fetch: bool = False, + explore: bool = None) -> TensorStructType: """Computes an action for the specified policy on the local Worker. Note that you can also access the policy object through @@ -804,17 +813,17 @@ def compute_action(self, return result[0] # backwards compatibility @property - def _name(self): + def _name(self) -> str: """Subclasses should override this to declare their name.""" raise NotImplementedError @property - def _default_config(self): + def _default_config(self) -> dict: """Subclasses should override this to declare their default config.""" raise NotImplementedError @PublicAPI - def get_policy(self, policy_id=DEFAULT_POLICY_ID): + def get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Policy: """Return policy for the specified id, or None. Arguments: @@ -823,7 +832,7 @@ def get_policy(self, policy_id=DEFAULT_POLICY_ID): return self.workers.local_worker().get_policy(policy_id) @PublicAPI - def get_weights(self, policies=None): + def get_weights(self, policies: List[PolicyID] = None) -> dict: """Return a dictionary of policy ids to weights. Arguments: @@ -833,7 +842,7 @@ def get_weights(self, policies=None): return self.workers.local_worker().get_weights(policies) @PublicAPI - def set_weights(self, weights): + def set_weights(self, weights: Dict[PolicyID, dict]): """Set policy weights by policy id. Arguments: @@ -859,9 +868,9 @@ def export_policy_model(self, export_dir, policy_id=DEFAULT_POLICY_ID): @DeveloperAPI def export_policy_checkpoint(self, - export_dir, - filename_prefix="model", - policy_id=DEFAULT_POLICY_ID): + export_dir: str, + filename_prefix: str = "model", + policy_id: PolicyID = DEFAULT_POLICY_ID): """Export tensorflow policy model checkpoint to local directory. Arguments: @@ -880,8 +889,8 @@ def export_policy_checkpoint(self, @DeveloperAPI def import_policy_model_from_h5(self, - import_file, - policy_id=DEFAULT_POLICY_ID): + import_file: str, + policy_id: PolicyID = DEFAULT_POLICY_ID): """Imports a policy's model with given policy_id from a local h5 file. Arguments: @@ -898,7 +907,8 @@ def import_policy_model_from_h5(self, import_file, policy_id) @DeveloperAPI - def collect_metrics(self, selected_workers=None): + def collect_metrics(self, + selected_workers: List["ActorHandle"] = None) -> dict: """Collects metrics from the remote workers of this agent. This is the same data as returned by a call to train(). @@ -909,14 +919,14 @@ def collect_metrics(self, selected_workers=None): selected_workers=selected_workers) @classmethod - def resource_help(cls, config): + def resource_help(cls, config: dict) -> str: return ("\n\nYou can adjust the resource requests of RLlib agents by " "setting `num_workers`, `num_gpus`, and other configs. See " "the DEFAULT_CONFIG defined by each agent for more info.\n\n" "The config of this agent is: {}".format(config)) @classmethod - def merge_trainer_configs(cls, config1, config2): + def merge_trainer_configs(cls, config1: dict, config2: dict) -> dict: config1 = copy.deepcopy(config1) # Error if trainer default has deprecated value. if config1["sample_batch_size"] != DEPRECATED_VALUE: @@ -943,7 +953,7 @@ def make_callbacks(): cls._override_all_subkeys_if_type_changes) @staticmethod - def _validate_config(config): + def _validate_config(config: dict): if "policy_graphs" in config["multiagent"]: logger.warning( "The `policy_graphs` config has been renamed to `policies`.") @@ -1030,7 +1040,8 @@ def _has_policy_optimizer(self): self.optimizer, PolicyOptimizer) @override(Trainable) - def _export_model(self, export_formats, export_dir): + def _export_model(self, export_formats: List[str], + export_dir: str) -> Dict[str, str]: ExportFormat.validate(export_formats) exported = {} if ExportFormat.CHECKPOINT in export_formats: @@ -1043,7 +1054,7 @@ def _export_model(self, export_formats, export_dir): exported[ExportFormat.MODEL] = path return exported - def import_model(self, import_file): + def import_model(self, import_file: str): """Imports a model from import_file. Note: Currently, only h5 files are supported. @@ -1068,7 +1079,7 @@ def import_model(self, import_file): else: return self.import_policy_model_from_h5(import_file) - def __getstate__(self): + def __getstate__(self) -> dict: state = {} if hasattr(self, "workers"): state["worker"] = self.workers.local_worker().save() @@ -1076,7 +1087,7 @@ def __getstate__(self): state["optimizer"] = self.optimizer.save() return state - def __setstate__(self, state): + def __setstate__(self, state: dict): if "worker" in state: self.workers.local_worker().restore(state["worker"]) remote_state = ray.put(state["worker"]) @@ -1085,7 +1096,7 @@ def __setstate__(self, state): if "optimizer" in state: self.optimizer.restore(state["optimizer"]) - def _register_if_needed(self, env_object): + def _register_if_needed(self, env_object: Union[str, EnvType]): if isinstance(env_object, str): return env_object elif isinstance(env_object, type): diff --git a/rllib/env/__init__.py b/rllib/env/__init__.py index a9483cb7f14fc..f0c87e79366d7 100644 --- a/rllib/env/__init__.py +++ b/rllib/env/__init__.py @@ -1,3 +1,5 @@ +from typing import Any + from ray.rllib.env.base_env import BaseEnv from ray.rllib.env.dm_env_wrapper import DMEnv from ray.rllib.env.multi_agent_env import MultiAgentEnv @@ -8,6 +10,9 @@ from ray.rllib.env.policy_client import PolicyClient from ray.rllib.env.policy_server_input import PolicyServerInput +# Represents one of the env types in this package. +EnvType = Any + __all__ = [ "BaseEnv", "MultiAgentEnv", diff --git a/rllib/utils/framework.py b/rllib/utils/framework.py index c427337898fb8..27770962c8a4a 100644 --- a/rllib/utils/framework.py +++ b/rllib/utils/framework.py @@ -1,7 +1,7 @@ import logging import os import sys -from typing import Any +from typing import Any, Union from ray.util import log_once @@ -10,6 +10,9 @@ # Represents a generic tensor type. TensorType = Any +# Either a plain tensor, or a dict or tuple of tensors (or StructTensors). +TensorStructType = Union[TensorType, dict, tuple] + def get_auto_framework(): """Returns the framework (str) when framework="auto" in the config.
https://api.github.com/repos/ray-project/ray/pulls/8642
2020-05-27T19:06:44Z
2020-06-03T19:47:36Z
2020-06-03T19:47:36Z
2020-06-03T19:47:36Z
2,971
ray-project/ray
19,359
[i18n-fr] Translate autoclass tutorial to French
diff --git a/docs/source/fr/_toctree.yml b/docs/source/fr/_toctree.yml index 1b5a7d4971972..12c2feb0a02eb 100755 --- a/docs/source/fr/_toctree.yml +++ b/docs/source/fr/_toctree.yml @@ -1,156 +1,30 @@ - sections: - - local: index - title: 🤗 Transformers - - local: quicktour - title: Visite rapide - - local: installation - title: Installation + - local: index + title: 🤗 Transformers + - local: quicktour + title: Visite rapide + - local: installation + title: Installation title: Démarrer - sections: - - local: in_translation - title: Pipelines pour l'inférence - - local: in_translation - title: Chargement d'instances pré-entraînées avec une AutoClass - - local: in_translation - title: Préparation des données - - local: in_translation - title: Fine-tune un modèle pré-entraîné - - local: in_translation - title: Entraînement distribué avec 🤗 Accelerate - - local: in_translation - title: Partager un modèle - title: Tutoriels -- sections: - - sections: - - local: in_translation - title: Créer votre architecture - - local: in_translation - title: Partager vos modèles - - local: in_translation - title: Entraînement avec un script - - local: in_translation - title: Entraînement avec Amazon SageMaker - - local: in_translation - title: Convertir depuis des checkpoints Tensorflow - - local: in_translation - title: Exporter vers ONNX - - local: in_translation - title: Exporter vers TorchScript - - local: in_translation - title: Aide au dépannage - title: Usage général - - sections: - - local: in_translation - title: Utiliser les tokenizers de 🤗 Tokenizers - - local: in_translation - title: Inférence avec les modèles multilingues - - local: in_translation - title: Stratégies de génération de texte - - sections: - - isExpanded: false - local: in_translation - title: Classification de texte - - local: in_translation - title: Classification de token - - local: in_translation - title: Système de question-réponse - - local: in_translation - title: Modélisation causale du langage - - local: in_translation - title: Modélisation du langage avec masque - - local: in_translation - title: Traduction - - local: in_translation - title: Génération de résumé - - local: in_translation - title: Question à choix multiple - title: Guides des tâches - title: Traitement automatique des langues - - sections: - - local: in_translation - title: Classification audio - - local: in_translation - title: Reconnaissance automatique de la parole - title: Audio - - sections: - local: in_translation - title: Classification d'images + title: Pipelines pour l'inférence + - local: autoclass_tutorial + title: Chargement d'instances pré-entraînées avec une AutoClass - local: in_translation - title: Segmentation sémantique + title: Préparation des données - local: in_translation - title: Classification de vidéos + title: Fine-tune un modèle pré-entraîné - local: in_translation - title: Détection d'objets - title: Vision par ordinateur - - sections: - - local: in_translation - title: Performance et extensibilité - - sections: - - local: in_translation - title: Comment contribuer à transformers? - - local: in_translation - title: Comment ajouter un modèle à 🤗 Transformers? - - local: in_translation - title: Comment convertir un modèle 🤗 Transformers vers TensorFlow? - - local: in_translation - title: Comment ajouter un pipeline à 🤗 Transformers? - - local: in_translation - title: Tester - - local: in_translation - title: Vérification pour une Pull Request - title: Contribuer - - local: in_translation - title: 🤗 Transformers Notebooks - - local: in_translation - title: Ressources communautaires - - local: in_translation - title: Benchmarks - - local: in_translation - title: Migration à partir de versions précédentes - title: Guides d'utilisation -- sections: - - local: in_translation - title: Philosophie - - local: in_translation - title: Glossaire - - local: in_translation - title: Qu'est ce 🤗 Transformers peut faire ? - - local: in_translation - title: Quelles tâches 🤗 Transformers peut résoudre ? - - local: in_translation - title: Résumé des modèles - - local: in_translation - title: Résumé des tokenizers - - local: in_translation - title: Remplissage et troncature - - local: in_translation - title: BERTology - - local: in_translation - title: Perplexité des modèles à longueur fixe - - local: in_translation - title: Pipelines pour inférence avec des serveurs web - title: Guides conceptuels -- sections: - - isExpanded: false - sections: - - local: in_translation - title: Classes principales - - local: in_translation - title: Modèles textuels - - local: in_translation - title: Modèles visuels - - local: in_translation - title: Modèles audio + title: Entraînement avec un script - local: in_translation - title: Modèles multimodal + title: Entraînement distribué avec 🤗 Accelerate - local: in_translation - title: Modèles d'apprentissage par renforcement + title: Chargement et entraînement des adaptateurs avec 🤗 PEFT - local: in_translation - title: Modèles de séries temporelles + title: Partager un modèle - local: in_translation - title: Graph models - title: Modèles - - sections: + title: Agents - local: in_translation - title: Utilitaires internes - title: API + title: Génération avec LLMs + title: Tutoriels diff --git a/docs/source/fr/autoclass_tutorial.md b/docs/source/fr/autoclass_tutorial.md new file mode 100644 index 0000000000000..392e2a6807e55 --- /dev/null +++ b/docs/source/fr/autoclass_tutorial.md @@ -0,0 +1,142 @@ +<!--Copyright 2022 The HuggingFace Team. All rights reserved. + +Licensed 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. + +⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be +rendered properly in your Markdown viewer. + +--> + +# Chargement d'instances pré-entraînées avec une AutoClass + +Avec autant d'architectures Transformer différentes, il peut être difficile d'en créer une pour votre ensemble de poids (aussi appelés "weights" ou "checkpoint" en anglais). Dans l'idée de créer une librairie facile, simple et flexible à utiliser, 🤗 Transformers fournit une `AutoClass` qui infère et charge automatiquement l'architecture correcte à partir d'un ensemble de poids donné. La fonction `from_pretrained()` vous permet de charger rapidement un modèle pré-entraîné pour n'importe quelle architecture afin que vous n'ayez pas à consacrer du temps et des ressources à l'entraînement d'un modèle à partir de zéro. Produire un tel code indépendant d'un ensemble de poids signifie que si votre code fonctionne pour un ensemble de poids, il fonctionnera avec un autre ensemble - tant qu'il a été entraîné pour une tâche similaire - même si l'architecture est différente. + +<Tip> + +Rappel, l'architecture fait référence au squelette du modèle et l'ensemble de poids contient les poids pour une architecture donnée. Par exemple, [BERT](https://huggingface.co/bert-base-uncased) est une architecture, tandis que `bert-base-uncased` est un ensemble de poids. Le terme modèle est général et peut signifier soit architecture soit ensemble de poids. + +</Tip> + +Dans ce tutoriel, vous apprendrez à: + + * Charger un tokenizer pré-entraîné. + * Charger un processeur d'image pré-entraîné. + * Charger un extracteur de caractéristiques pré-entraîné. + * Charger un processeur pré-entraîné. + * Charger un modèle pré-entraîné. + +## AutoTokenizer + +Quasiment toutes les tâches de traitement du langage (NLP) commencent avec un tokenizer. Un tokenizer convertit votre texte initial dans un format qui peut être traité par le modèle. + +Chargez un tokenizer avec [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") +``` + +Puis, transformez votre texte initial comme montré ci-dessous: + +```py +>>> sequence = "In a hole in the ground there lived a hobbit." +>>> print(tokenizer(sequence)) +{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +## AutoImageProcessor + +Pour les tâches de vision, un processeur d'image traite l'image pour la formater correctment. + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +## AutoFeatureExtractor + +Pour les tâches audio, un extracteur de caractéristiques (aussi appelés "features" en anglais) traite le signal audio pour le formater correctement. + +Chargez un extracteur de caractéristiques avec [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained( +... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +## AutoProcessor + +Les tâches multimodales nécessitent un processeur qui combine deux types d'outils de prétraitement. Par exemple, le modèle [LayoutLMV2](model_doc/layoutlmv2) nécessite un processeur d'image pour traiter les images et un tokenizer pour traiter le texte ; un processeur combine les deux. + +Chargez un processeur avec [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased") +``` + +## AutoModel + +<frameworkcontent> +<pt> +Enfin, les classes `AutoModelFor` vous permettent de charger un modèle pré-entraîné pour une tâche donnée (voir [ici](model_doc/auto) pour une liste complète des tâches disponibles). Par exemple, chargez un modèle pour la classification de séquence avec [`AutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased") +``` + +Réutilisez facilement le même ensemble de poids pour charger une architecture pour une tâche différente : + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased") +``` + +<Tip warning={true}> + +Pour les modèles PyTorch, la fonction `from_pretrained()` utilise `torch.load()` qui utilise `pickle` en interne et est connu pour être non sécurisé. En général, ne chargez jamais un modèle qui pourrait provenir d'une source non fiable, ou qui pourrait avoir été altéré. Ce risque de sécurité est partiellement atténué pour les modèles hébergés publiquement sur le Hugging Face Hub, qui sont [scannés pour les logiciels malveillants](https://huggingface.co/docs/hub/security-malware) à chaque modification. Consultez la [documentation du Hub](https://huggingface.co/docs/hub/security) pour connaître les meilleures pratiques comme la [vérification des modifications signées](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg) avec GPG. + +Les points de contrôle TensorFlow et Flax ne sont pas concernés, et peuvent être chargés dans des architectures PyTorch en utilisant les arguments `from_tf` et `from_flax` de la fonction `from_pretrained` pour contourner ce problème. + +</Tip> + +En général, nous recommandons d'utiliser les classes `AutoTokenizer` et `AutoModelFor` pour charger des instances pré-entraînées de tokenizers et modèles respectivement. Cela vous permettra de charger la bonne architecture à chaque fois. Dans le prochain [tutoriel](preprocessing), vous apprenez à utiliser un tokenizer, processeur d'image, extracteur de caractéristiques et processeur pour pré-traiter un jeu de données pour le fine-tuning. +</pt> +<tf> +Enfin, les classes `TFAutoModelFor` vous permettent de charger un modèle pré-entraîné pour une tâche donnée (voir [ici](model_doc/auto) pour une liste complète des tâches disponibles). Par exemple, chargez un modèle pour la classification de séquence avec [`TFAutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased") +``` + +Réutilisez facilement le même ensemble de poids pour charger une architecture pour une tâche différente : + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased") +``` + +En général, nous recommandons d'utiliser les classes `AutoTokenizer` et `TFAutoModelFor` pour charger des instances pré-entraînées de tokenizers et modèles respectivement. Cela vous permettra de charger la bonne architecture à chaque fois. Dans le prochain [tutoriel](preprocessing), vous apprenez à utiliser un tokenizer, processeur d'image, extracteur de caractéristiques et processeur pour pré-traiter un jeu de données pour le fine-tuning. +</tf> +</frameworkcontent>
# What does this PR do? Translated the autoclass_tutorial.md file of the documentation to French. Part of #21456 Thank you in advance for your review. ## 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. - [x] 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? French speaking contributors.
https://api.github.com/repos/huggingface/transformers/pulls/27659
2023-11-22T18:03:34Z
2023-12-07T06:44:14Z
2023-12-07T06:44:14Z
2023-12-07T06:44:23Z
3,894
huggingface/transformers
12,248
GH-108614: Remove non-debug uses of `#if TIER_ONE` and `#if TIER_TWO` from `_POP_FRAME` op.
diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 93926c03421eb7..7f398391c5dc34 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -768,24 +768,25 @@ dummy_func( // different frame, and it's accounted for by _PUSH_FRAME. op(_POP_FRAME, (retval --)) { assert(EMPTY()); - _PyFrame_SetStackPointer(frame, stack_pointer); - _Py_LeaveRecursiveCallPy(tstate); - // GH-99729: We need to unlink the frame *before* clearing it: - _PyInterpreterFrame *dying = frame; #if TIER_ONE assert(frame != &entry_frame); #endif + STORE_SP(); + _Py_LeaveRecursiveCallPy(tstate); + // GH-99729: We need to unlink the frame *before* clearing it: + _PyInterpreterFrame *dying = frame; frame = tstate->current_frame = dying->previous; _PyEval_FrameClearAndPop(tstate, dying); frame->prev_instr += frame->return_offset; _PyFrame_StackPush(frame, retval); - #if TIER_ONE - goto resume_frame; - #endif - #if TIER_TWO - stack_pointer = _PyFrame_GetStackPointer(frame); - ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; - #endif + LOAD_SP(); + LOAD_IP(); +#if LLTRACE && TIER_ONE + lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS()); + if (lltrace < 0) { + goto exit_unwind; + } +#endif } macro(RETURN_VALUE) = diff --git a/Python/ceval.c b/Python/ceval.c index a56d31ea073639..a22852ec13ea99 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -189,6 +189,34 @@ lltrace_resume_frame(_PyInterpreterFrame *frame) fflush(stdout); PyErr_SetRaisedException(exc); } + +static int +maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, _PyInterpreterFrame *skip_frame, PyObject *globals) +{ + if (globals == NULL) { + return 0; + } + if (frame == skip_frame) { + return 0; + } + int r = PyDict_Contains(globals, &_Py_ID(__lltrace__)); + if (r < 0) { + return -1; + } + int lltrace = r; + if (!lltrace) { + // When tracing executed uops, also trace bytecode + char *uop_debug = Py_GETENV("PYTHONUOPSDEBUG"); + if (uop_debug != NULL && *uop_debug >= '0') { + lltrace = (*uop_debug - '0') >= 5; // TODO: Parse an int and all that + } + } + if (lltrace) { + lltrace_resume_frame(frame); + } + return lltrace; +} + #endif static void monitor_raise(PyThreadState *tstate, @@ -576,6 +604,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) return _PyEval_EvalFrame(tstate, f->f_frame, throwflag); } +#define TIER_ONE 1 #include "ceval_macros.h" @@ -714,24 +743,9 @@ _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int SET_LOCALS_FROM_FRAME(); #ifdef LLTRACE - { - if (frame != &entry_frame && GLOBALS()) { - int r = PyDict_Contains(GLOBALS(), &_Py_ID(__lltrace__)); - if (r < 0) { - goto exit_unwind; - } - lltrace = r; - if (!lltrace) { - // When tracing executed uops, also trace bytecode - char *uop_debug = Py_GETENV("PYTHONUOPSDEBUG"); - if (uop_debug != NULL && *uop_debug >= '0') { - lltrace = (*uop_debug - '0') >= 5; // TODO: Parse an int and all that - } - } - } - if (lltrace) { - lltrace_resume_frame(frame); - } + lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS()); + if (lltrace < 0) { + goto exit_unwind; } #endif @@ -752,7 +766,6 @@ _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int #endif { -#define TIER_ONE 1 #include "generated_cases.c.h" /* INSTRUMENTED_LINE has to be here, rather than in bytecodes.c, diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index 635b8e501e523e..4b7c4448e0ea25 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -373,3 +373,39 @@ static inline int _Py_EnterRecursivePy(PyThreadState *tstate) { static inline void _Py_LeaveRecursiveCallPy(PyThreadState *tstate) { tstate->py_recursion_remaining++; } + + +/* Implementation of "macros" that modify the instruction pointer, + * stack pointer, or frame pointer. + * These need to treated differently by tier 1 and 2. */ + +#if TIER_ONE + +#define LOAD_IP() \ +do { next_instr = frame->prev_instr+1; } while (0) + +#define STORE_SP() \ +_PyFrame_SetStackPointer(frame, stack_pointer) + +#define LOAD_SP() \ +stack_pointer = _PyFrame_GetStackPointer(frame); + +#endif + + +#if TIER_TWO + +#define LOAD_IP() \ +do { ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; } while (0) + +#define STORE_SP() \ +_PyFrame_SetStackPointer(frame, stack_pointer) + +#define LOAD_SP() \ +stack_pointer = _PyFrame_GetStackPointer(frame); + +#endif + + + + diff --git a/Python/executor.c b/Python/executor.c index 0ff5106fe446ff..9b3262ed4165f1 100644 --- a/Python/executor.c +++ b/Python/executor.c @@ -17,6 +17,7 @@ #include "pycore_sliceobject.h" #include "pycore_uops.h" +#define TIER_TWO 2 #include "ceval_macros.h" @@ -83,7 +84,6 @@ _PyUopExecute(_PyExecutorObject *executor, _PyInterpreterFrame *frame, PyObject OBJECT_STAT_INC(optimization_uops_executed); switch (opcode) { -#define TIER_TWO 2 #include "executor_cases.c.h" default: diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 1283cc7ebbf9c4..e63a36d61579a4 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -690,24 +690,25 @@ retval = stack_pointer[-1]; STACK_SHRINK(1); assert(EMPTY()); - _PyFrame_SetStackPointer(frame, stack_pointer); - _Py_LeaveRecursiveCallPy(tstate); - // GH-99729: We need to unlink the frame *before* clearing it: - _PyInterpreterFrame *dying = frame; #if TIER_ONE assert(frame != &entry_frame); #endif + STORE_SP(); + _Py_LeaveRecursiveCallPy(tstate); + // GH-99729: We need to unlink the frame *before* clearing it: + _PyInterpreterFrame *dying = frame; frame = tstate->current_frame = dying->previous; _PyEval_FrameClearAndPop(tstate, dying); frame->prev_instr += frame->return_offset; _PyFrame_StackPush(frame, retval); - #if TIER_ONE - goto resume_frame; - #endif - #if TIER_TWO - stack_pointer = _PyFrame_GetStackPointer(frame); - ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; - #endif + LOAD_SP(); + LOAD_IP(); +#if LLTRACE && TIER_ONE + lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS()); + if (lltrace < 0) { + goto exit_unwind; + } +#endif break; } diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 5940c185817604..a7bf20b9d1c7f6 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -990,25 +990,27 @@ STACK_SHRINK(1); { assert(EMPTY()); - _PyFrame_SetStackPointer(frame, stack_pointer); - _Py_LeaveRecursiveCallPy(tstate); - // GH-99729: We need to unlink the frame *before* clearing it: - _PyInterpreterFrame *dying = frame; #if TIER_ONE assert(frame != &entry_frame); #endif + STORE_SP(); + _Py_LeaveRecursiveCallPy(tstate); + // GH-99729: We need to unlink the frame *before* clearing it: + _PyInterpreterFrame *dying = frame; frame = tstate->current_frame = dying->previous; _PyEval_FrameClearAndPop(tstate, dying); frame->prev_instr += frame->return_offset; _PyFrame_StackPush(frame, retval); - #if TIER_ONE - goto resume_frame; - #endif - #if TIER_TWO - stack_pointer = _PyFrame_GetStackPointer(frame); - ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; - #endif + LOAD_SP(); + LOAD_IP(); + #if LLTRACE && TIER_ONE + lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS()); + if (lltrace < 0) { + goto exit_unwind; + } + #endif } + DISPATCH(); } TARGET(INSTRUMENTED_RETURN_VALUE) { @@ -1055,25 +1057,27 @@ retval = value; { assert(EMPTY()); - _PyFrame_SetStackPointer(frame, stack_pointer); - _Py_LeaveRecursiveCallPy(tstate); - // GH-99729: We need to unlink the frame *before* clearing it: - _PyInterpreterFrame *dying = frame; #if TIER_ONE assert(frame != &entry_frame); #endif + STORE_SP(); + _Py_LeaveRecursiveCallPy(tstate); + // GH-99729: We need to unlink the frame *before* clearing it: + _PyInterpreterFrame *dying = frame; frame = tstate->current_frame = dying->previous; _PyEval_FrameClearAndPop(tstate, dying); frame->prev_instr += frame->return_offset; _PyFrame_StackPush(frame, retval); - #if TIER_ONE - goto resume_frame; - #endif - #if TIER_TWO - stack_pointer = _PyFrame_GetStackPointer(frame); - ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; - #endif + LOAD_SP(); + LOAD_IP(); + #if LLTRACE && TIER_ONE + lltrace = maybe_lltrace_resume_frame(frame, &entry_frame, GLOBALS()); + if (lltrace < 0) { + goto exit_unwind; + } + #endif } + DISPATCH(); } TARGET(INSTRUMENTED_RETURN_CONST) { @@ -3887,6 +3891,7 @@ ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; #endif } + DISPATCH(); } TARGET(CALL_PY_EXACT_ARGS) { @@ -3963,6 +3968,7 @@ ip_offset = (_Py_CODEUNIT *)_PyFrame_GetCode(frame)->co_code_adaptive; #endif } + DISPATCH(); } TARGET(CALL_PY_WITH_DEFAULTS) { diff --git a/Tools/cases_generator/stacking.py b/Tools/cases_generator/stacking.py index 2d006ba8e5934a..dcdfc7ec054248 100644 --- a/Tools/cases_generator/stacking.py +++ b/Tools/cases_generator/stacking.py @@ -369,8 +369,8 @@ def write_macro_instr( next_instr_is_set = write_components(parts, out, TIER_ONE, mac.cache_offset) except AssertionError as err: raise AssertionError(f"Error writing macro {mac.name}") from err - if not parts[-1].instr.always_exits and not next_instr_is_set: - if mac.cache_offset: + if not parts[-1].instr.always_exits: + if not next_instr_is_set and mac.cache_offset: out.emit(f"next_instr += {mac.cache_offset};") out.emit("DISPATCH();")
<!-- gh-issue-number: gh-108614 --> * Issue: gh-108614 <!-- /gh-issue-number -->
https://api.github.com/repos/python/cpython/pulls/108685
2023-08-30T14:23:59Z
2023-08-31T10:34:53Z
2023-08-31T10:34:53Z
2023-09-05T12:25:42Z
3,132
python/cpython
4,708
minor fixes
diff --git a/mitmproxy/console/flowview.py b/mitmproxy/console/flowview.py index 789066fc83..11c721512b 100644 --- a/mitmproxy/console/flowview.py +++ b/mitmproxy/console/flowview.py @@ -6,6 +6,7 @@ import traceback import urwid +from typing import Optional, Union # noqa from mitmproxy import contentviews from mitmproxy import controller @@ -105,7 +106,8 @@ def _mkhelp(): class FlowViewHeader(urwid.WidgetWrap): def __init__(self, master, f): - self.master, self.flow = master, f + self.master = master # type: "mitmproxy.console.master.ConsoleMaster" + self.flow = f # type: models.HTTPFlow self._w = common.format_flow( f, False, @@ -530,13 +532,6 @@ def change_this_display_mode(self, t): ) signals.flow_change.send(self, flow = self.flow) - def delete_body(self, t): - if self.tab_offset == TAB_REQ: - self.flow.request.content = None - else: - self.flow.response.content = None - signals.flow_change.send(self, flow = self.flow) - def keypress(self, size, key): key = super(self.__class__, self).keypress(size, key) @@ -545,6 +540,8 @@ def keypress(self, size, key): return key = common.shortcuts(key) + + conn = None # type: Optional[Union[models.HTTPRequest, models.HTTPResponse]] if self.tab_offset == TAB_REQ: conn = self.flow.request elif self.tab_offset == TAB_RESP: @@ -691,15 +688,8 @@ def keypress(self, size, key): args = (scope, self.flow, common.copy_to_clipboard_or_prompt) ) elif key == "x": - signals.status_prompt_onekey.send( - prompt = "Delete body", - keys = ( - ("completely", "c"), - ("mark as missing", "m"), - ), - callback = self.delete_body - ) - key = None + conn.content = None + signals.flow_change.send(self, flow=self.flow) elif key == "v": if conn.raw_content: t = conn.headers.get("content-type") @@ -713,7 +703,9 @@ def keypress(self, size, key): self.flow.backup() e = conn.headers.get("content-encoding", "identity") if e != "identity": - if not conn.decode(): + try: + conn.decode() + except ValueError: signals.status_message.send( message = "Could not decode - invalid data?" ) diff --git a/mitmproxy/contentviews.py b/mitmproxy/contentviews.py index afdaad7f55..e155bc01e5 100644 --- a/mitmproxy/contentviews.py +++ b/mitmproxy/contentviews.py @@ -20,6 +20,8 @@ import subprocess import sys +from typing import Mapping # noqa + import html2text import lxml.etree import lxml.html @@ -76,6 +78,7 @@ def pretty_json(s): def format_dict(d): + # type: (Mapping[Union[str,bytes], Union[str,bytes]]) -> Generator[Tuple[Union[str,bytes], Union[str,bytes]]] """ Helper function that transforms the given dictionary into a list of ("key", key ) @@ -85,7 +88,7 @@ def format_dict(d): max_key_len = max(len(k) for k in d.keys()) max_key_len = min(max_key_len, KEY_MAX) for key, value in d.items(): - key += ":" + key += b":" if isinstance(key, bytes) else u":" key = key.ljust(max_key_len + 2) yield [ ("header", key), @@ -106,12 +109,16 @@ class View(object): prompt = () content_types = [] - def __call__(self, data, **metadata): + def __call__( + self, + data, # type: bytes + **metadata + ): """ Transform raw data into human-readable output. Args: - data: the data to decode/format as bytes. + data: the data to decode/format. metadata: optional keyword-only arguments for metadata. Implementations must not rely on a given argument being present. @@ -278,6 +285,10 @@ class ViewURLEncoded(View): content_types = ["application/x-www-form-urlencoded"] def __call__(self, data, **metadata): + try: + data = data.decode("ascii", "strict") + except ValueError: + return None d = url.decode(data) return "URLEncoded form", format_dict(multidict.MultiDict(d)) diff --git a/netlib/http/url.py b/netlib/http/url.py index 2fc6e7eedb..1c8c007a7f 100644 --- a/netlib/http/url.py +++ b/netlib/http/url.py @@ -82,6 +82,7 @@ def unparse(scheme, host, port, path=""): def encode(s): + # type: (six.text_type, bytes) -> str """ Takes a list of (key, value) tuples and returns a urlencoded string. """ diff --git a/test/mitmproxy/test_contentview.py b/test/mitmproxy/test_contentview.py index 2db9ab40a5..aad53b3727 100644 --- a/test/mitmproxy/test_contentview.py +++ b/test/mitmproxy/test_contentview.py @@ -59,10 +59,10 @@ def test_view_auto(self): assert f[0] == "Query" def test_view_urlencoded(self): - d = url.encode([("one", "two"), ("three", "four")]) + d = url.encode([("one", "two"), ("three", "four")]).encode() v = cv.ViewURLEncoded() assert v(d) - d = url.encode([("adsfa", "")]) + d = url.encode([("adsfa", "")]).encode() v = cv.ViewURLEncoded() assert v(d)
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/1402
2016-07-22T03:35:05Z
2016-07-23T19:49:57Z
2016-07-23T19:49:57Z
2016-07-23T19:50:01Z
1,432
mitmproxy/mitmproxy
28,067
Refs #27753 -- Deprecated django.utils.text.unescape_entities().
diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 96e22f69b9301..fd8fce8b4d46a 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -8,6 +8,7 @@ import binascii import cgi import collections +import html from urllib.parse import unquote from django.conf import settings @@ -19,7 +20,6 @@ ) from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str -from django.utils.text import unescape_entities __all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted') @@ -209,7 +209,7 @@ def parse(self): file_name = disposition.get('filename') if file_name: file_name = force_str(file_name, encoding, errors='replace') - file_name = self.IE_sanitize(unescape_entities(file_name)) + file_name = self.IE_sanitize(html.unescape(file_name)) if not file_name: continue diff --git a/django/utils/text.py b/django/utils/text.py index 44007beb0f1f7..e9b7dcc72bc10 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -1,9 +1,11 @@ import html.entities import re import unicodedata +import warnings from gzip import GzipFile from io import BytesIO +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy from django.utils.translation import gettext as _, gettext_lazy, pgettext @@ -358,6 +360,11 @@ def _replace_entity(match): @keep_lazy_text def unescape_entities(text): + warnings.warn( + 'django.utils.text.unescape_entities() is deprecated in favor of ' + 'html.unescape().', + RemovedInDjango40Warning, stacklevel=2, + ) return _entity_re.sub(_replace_entity, str(text)) diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 93b6a04594a0f..7020a3341aa12 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -30,6 +30,8 @@ details on these changes. * ``alias=None`` will be required in the signature of ``django.db.models.Expression.get_group_by_cols()`` subclasses. +* ``django.utils.text.unescape_entities()`` will be removed. + .. _deprecation-removed-in-3.1: 3.1 diff --git a/docs/releases/3.0.txt b/docs/releases/3.0.txt index 1c222cfe7af37..f43a11938a9a3 100644 --- a/docs/releases/3.0.txt +++ b/docs/releases/3.0.txt @@ -411,6 +411,10 @@ Miscellaneous * ``alias=None`` is added to the signature of :meth:`.Expression.get_group_by_cols`. +* ``django.utils.text.unescape_entities()`` is deprecated in favor of + :func:`html.unescape`. Note that unlike ``unescape_entities()``, + ``html.unescape()`` evaluates lazy strings immediately. + .. _removed-features-3.0: Features removed in 3.0 diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py index 2d584c1cdd3a4..ee04f3062c313 100644 --- a/tests/utils_tests/test_text.py +++ b/tests/utils_tests/test_text.py @@ -1,8 +1,9 @@ import json import sys -from django.test import SimpleTestCase +from django.test import SimpleTestCase, ignore_warnings from django.utils import text +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy, override @@ -184,6 +185,7 @@ def test_slugify(self): # interning the result may be useful, e.g. when fed to Path. self.assertEqual(sys.intern(text.slugify('a')), 'a') + @ignore_warnings(category=RemovedInDjango40Warning) def test_unescape_entities(self): items = [ ('', ''), @@ -200,6 +202,14 @@ def test_unescape_entities(self): self.assertEqual(text.unescape_entities(value), output) self.assertEqual(text.unescape_entities(lazystr(value)), output) + def test_unescape_entities_deprecated(self): + msg = ( + 'django.utils.text.unescape_entities() is deprecated in favor of ' + 'html.unescape().' + ) + with self.assertWarnsMessage(RemovedInDjango40Warning, msg): + text.unescape_entities('foo') + def test_unescape_string_literal(self): items = [ ('"abc"', 'abc'),
The function was undocumented and only required for compatibility with Python 2. Use Python's html.unescape() instead -- available since Python 3.4. https://docs.python.org/3/library/html.html#html.unescape https://code.djangoproject.com/ticket/27753
https://api.github.com/repos/django/django/pulls/11277
2019-04-24T13:02:29Z
2019-05-08T06:27:11Z
2019-05-08T06:27:11Z
2019-05-09T14:01:55Z
1,132
django/django
51,126
Fix st.slider tests to address flakiness
diff --git a/e2e/specs/st_slider.spec.js b/e2e/specs/st_slider.spec.js index dfbe70d709ac..6974999e6e17 100644 --- a/e2e/specs/st_slider.spec.js +++ b/e2e/specs/st_slider.spec.js @@ -18,8 +18,6 @@ describe("st.slider", () => { beforeEach(() => { cy.visit("http://localhost:3000/"); - // Open sidebar expander - cy.get(".streamlit-expanderHeader").click(); }); it("looks right", () => { @@ -27,11 +25,15 @@ describe("st.slider", () => { cy.get("[data-testid='stDecoration']").invoke("css", "display", "none"); cy.get(".stSlider") - .eq(2) + .eq(1) .matchThemedSnapshots("slider"); }); it("shows labels", () => { + // Open sidebar expander + cy.get(".streamlit-expanderHeader").click(); + cy.get(".stSlider label").contains("Label B"); + cy.get(".stSlider label").should( "have.text", "Label A" + @@ -45,7 +47,7 @@ describe("st.slider", () => { it("shows full label when the label is long", () => { cy.get(".stSlider") - .eq(4) + .eq(3) .matchThemedSnapshots("slider_with_long_label"); }); @@ -56,12 +58,20 @@ describe("st.slider", () => { }); it("does not overlap expander container when thumb value is long", () => { + // Open sidebar expander + cy.get(".streamlit-expanderHeader").click(); + cy.get(".stSlider label").contains("Label B"); + cy.get(".stSlider") .eq(1) .matchThemedSnapshots("expander_thumb_value"); }); it("has correct values", () => { + // Open sidebar expander + cy.get(".streamlit-expanderHeader").click(); + cy.get(".stSlider label").contains("Label B"); + cy.get(".stMarkdown").should( "have.text", "Value A: 12345678" + @@ -80,40 +90,40 @@ describe("st.slider", () => { // trigger click in the center of the slider cy.get('.stSlider [role="slider"]') - .eq(2) + .eq(1) .parent() .click(); cy.get(".stMarkdown") - .eq(2) + .eq(1) .should("have.text", "Value 1: 50"); }); it("increments the value on right arrow key press", () => { cy.get('.stSlider [role="slider"]') - .eq(2) + .eq(1) .click() .type("{rightarrow}", { force: true }); cy.get(".stMarkdown") - .eq(2) + .eq(1) .should("have.text", "Value 1: 26"); }); it("decrements the value on left arrow key press", () => { cy.get('.stSlider [role="slider"]') - .eq(2) + .eq(1) .click() .type("{leftarrow}", { force: true }); cy.get(".stMarkdown") - .eq(2) + .eq(1) .should("have.text", "Value 1: 24"); }); it("maintains its state on rerun", () => { cy.get('.stSlider [role="slider"]') - .eq(2) + .eq(1) .click() .type("{leftarrow}", { force: true }); @@ -124,7 +134,7 @@ describe("st.slider", () => { }); cy.get(".stMarkdown") - .eq(2) + .eq(1) .should("have.text", "Value 1: 24"); });
## 📚 Context The `st.slider` cypress tests are exhibiting some flakiness. Sometimes the expander is not opened in time for the test, despite having a `.click()` command to open the expander before each test run. - What kind of change does this PR introduce? - [x] Refactoring ## 🧠 Description of Changes - Revised `st.slider` tests to only open expander when necessary - Added wait times to ensure expand `.click()` registers ## 🧪 Testing Done - [x] Added/Updated e2e tests --- **Contribution License Agreement** By submitting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.
https://api.github.com/repos/streamlit/streamlit/pulls/4107
2021-11-29T22:10:26Z
2021-11-30T10:01:07Z
2021-11-30T10:01:07Z
2021-11-30T10:01:11Z
936
streamlit/streamlit
22,398
ref(reprocessing-progressbar): Add a refresh button as a temp solution
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingProgress.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingProgress.tsx index 1fe5a3de0027d..0d5c47f9f8200 100644 --- a/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingProgress.tsx +++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/reprocessingProgress.tsx @@ -1,7 +1,9 @@ import React from 'react'; import styled from '@emotion/styled'; +import Button from 'app/components/button'; import ProgressBar from 'app/components/progressBar'; +import {IconRefresh} from 'app/icons'; import {t, tct, tn} from 'app/locale'; import space from 'app/styles/space'; @@ -15,6 +17,11 @@ function ReprocessingProgress({totalEvents, pendingEvents}: Props) { const remainingEventsToReprocessPercent = (remainingEventsToReprocess / totalEvents) * 100; + // this is a temp solution + function handleRefresh() { + window.location.reload(); + } + return ( <Wrapper> <Inner> @@ -31,6 +38,9 @@ function ReprocessingProgress({totalEvents, pendingEvents}: Props) { totalEvents, event: tn('event', 'events', totalEvents), })} + <Button icon={<IconRefresh />} onClick={handleRefresh}> + {t('Refresh')} + </Button> </Content> </Inner> </Wrapper> @@ -53,6 +63,7 @@ const Content = styled('div')` font-size: ${p => p.theme.fontSizeMedium}; display: grid; grid-gap: ${space(1.5)}; + justify-items: center; max-width: 402px; width: 100%; `;
depends on https://github.com/getsentry/sentry/pull/22422 ![image](https://user-images.githubusercontent.com/29228205/101386009-d7c5be80-38bc-11eb-869f-d8eb95d6f336.png)
https://api.github.com/repos/getsentry/sentry/pulls/22499
2020-12-07T17:49:44Z
2020-12-09T10:06:27Z
2020-12-09T10:06:27Z
2020-12-24T10:31:54Z
421
getsentry/sentry
44,273
Merge dev branch
diff --git a/api-examples/api-example-model.py b/api-examples/api-example-model.py old mode 100755 new mode 100644 diff --git a/modules/sampler_hijack.py b/modules/sampler_hijack.py index f02bea4ffe..447c878204 100644 --- a/modules/sampler_hijack.py +++ b/modules/sampler_hijack.py @@ -1,7 +1,11 @@ +import math + import torch import transformers from transformers import LogitsWarper -from transformers.generation.logits_process import LogitNormalization, LogitsProcessorList +from transformers.generation.logits_process import (LogitNormalization, + LogitsProcessorList, + TemperatureLogitsWarper) class TailFreeLogitsWarper(LogitsWarper): @@ -70,15 +74,67 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to return scores +class MirostatLogitsWarper(LogitsWarper): + def __init__(self, mirostat_mode: int, mirostat_tau: float, mirostat_eta: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1): + if mirostat_mode not in [2]: + raise ValueError(f"`mirostat` has to be a an integer 2, but is {mirostat_mode}") + self.mirostat_mode = mirostat_mode + self.mirostat_eta = mirostat_eta + self.mirostat_tau = mirostat_tau + self.filter_value = filter_value + self.min_tokens_to_keep = min_tokens_to_keep + self.mu = 2 * self.mirostat_tau + self.e = 0 + + def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: + logits = scores[0] + sorted_logits, sorted_indices = torch.sort(logits, descending=True) + prob_original = torch.softmax(sorted_logits, dim=-1).tolist() # candidates + + # Truncate the words with surprise values greater than mu + for i, candidate in enumerate(prob_original): + if candidate > 0 and -math.log2(candidate) > self.mu: + if (i == 0): + sorted_logits = sorted_logits[:1] + else: + sorted_logits = sorted_logits[:i] + break + + # Normalize the probabilities of the remaining words + prob_topk = torch.softmax(sorted_logits, dim=0) + + prev_i = torch.multinomial(prob_topk, num_samples=1, replacement=True).to('cuda') + + observed_surprise = -math.log2(prob_topk[prev_i]) + self.e = observed_surprise - self.mirostat_tau + + # Update mu using the learning rate and error + self.mu -= self.mirostat_eta * self.e + + sorted_indices_to_remove = torch.ones_like(scores[0], dtype=torch.bool) + sorted_indices_to_remove[prev_i] = False + + indices_to_remove = sorted_indices_to_remove.unsqueeze(0).scatter(1, sorted_indices.unsqueeze(0), sorted_indices_to_remove.unsqueeze(0)) + scores = scores.masked_fill(indices_to_remove, self.filter_value) + return scores + + def get_logits_warper_patch(self, generation_config): warpers = self._get_logits_warper_old(generation_config) warpers_to_add = LogitsProcessorList() min_tokens_to_keep = 2 if generation_config.num_beams > 1 else 1 - if generation_config.tfs is not None and 0.0 <= generation_config.tfs <= 1.0: - warpers_to_add.append(TailFreeLogitsWarper(tfs=generation_config.tfs, min_tokens_to_keep=min_tokens_to_keep)) - if generation_config.top_a is not None and 0.0 <= generation_config.top_a <= 1.0: - warpers_to_add.append(TopALogitsWarper(top_a=generation_config.top_a, min_tokens_to_keep=min_tokens_to_keep)) + if generation_config.mirostat_mode is not None and generation_config.mirostat_mode == 2: + warpers_to_add.append(MirostatLogitsWarper(mirostat_mode=generation_config.mirostat_mode, mirostat_eta=generation_config.mirostat_eta, mirostat_tau=generation_config.mirostat_tau, min_tokens_to_keep=min_tokens_to_keep)) + # We need to disable samplers other than temperature + for warper in warpers: + if not isinstance(warper, TemperatureLogitsWarper): + warpers.remove(warper) + else: + if generation_config.tfs is not None and 0.0 <= generation_config.tfs <= 1.0: + warpers_to_add.append(TailFreeLogitsWarper(tfs=generation_config.tfs, min_tokens_to_keep=min_tokens_to_keep)) + if generation_config.top_a is not None and 0.0 <= generation_config.top_a <= 1.0: + warpers_to_add.append(TopALogitsWarper(top_a=generation_config.top_a, min_tokens_to_keep=min_tokens_to_keep)) if warpers and isinstance(warpers[-1], LogitNormalization): warpers = warpers[:-1] + warpers_to_add + [warpers[-1]] @@ -92,6 +148,9 @@ def generation_config_init_patch(self, **kwargs): self.__init___old(**kwargs) self.tfs = kwargs.pop("tfs", 1.0) self.top_a = kwargs.pop("top_a", 0.0) + self.mirostat_mode = kwargs.pop("mirostat_mode", 0) + self.mirostat_eta = kwargs.pop("mirostat_eta", 0.1) + self.mirostat_tau = kwargs.pop("mirostat_tau", 5) def hijack_samplers(): diff --git a/modules/text_generation.py b/modules/text_generation.py index 00b7cc7b2c..2dd7d38a0b 100644 --- a/modules/text_generation.py +++ b/modules/text_generation.py @@ -193,7 +193,7 @@ def _generate_reply(question, state, eos_token=None, stopping_strings=None, is_c def generate_reply_HF(question, original_question, seed, state, eos_token=None, stopping_strings=None, is_chat=False): generate_params = {} - for k in ['max_new_tokens', 'do_sample', 'temperature', 'top_p', 'typical_p', 'repetition_penalty', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping', 'tfs', 'top_a']: + for k in ['max_new_tokens', 'do_sample', 'temperature', 'top_p', 'typical_p', 'repetition_penalty', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping', 'tfs', 'top_a', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta']: generate_params[k] = state[k] for k in ['epsilon_cutoff', 'eta_cutoff']: diff --git a/server.py b/server.py index 25dbae8e9a..a507cf775a 100644 --- a/server.py +++ b/server.py @@ -504,7 +504,7 @@ def create_settings_menus(default_preset): shared.gradio['early_stopping'] = gr.Checkbox(value=generate_params['early_stopping'], label='early_stopping') with gr.Column(): - gr.Markdown('Mirostat (for llama.cpp)') + gr.Markdown('Mirostat (mode=1 is only for llama.cpp)') shared.gradio['mirostat_mode'] = gr.Slider(0, 2, step=1, value=generate_params['mirostat_mode'], label='mirostat_mode') shared.gradio['mirostat_tau'] = gr.Slider(0, 10, step=0.01, value=generate_params['mirostat_tau'], label='mirostat_tau') shared.gradio['mirostat_eta'] = gr.Slider(0, 1, step=0.01, value=generate_params['mirostat_eta'], label='mirostat_eta')
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/2616
2023-06-11T00:55:31Z
2023-06-11T00:55:59Z
2023-06-11T00:55:59Z
2023-06-11T00:56:22Z
1,893
oobabooga/text-generation-webui
26,205
Merge dev branch
diff --git a/modules/text_generation.py b/modules/text_generation.py index 3a4c55b36b..c5bfceb78e 100644 --- a/modules/text_generation.py +++ b/modules/text_generation.py @@ -93,9 +93,10 @@ def _generate_reply(question, state, stopping_strings=None, is_chat=False, escap last_update = time.time() yield reply - # Limit updates to 24 per second to not stress low latency networks + # Limit updates to 24 or 5 per second to avoid lag else: - if cur_time - last_update > 0.041666666666666664: + min_update_interval = 0.2 if (shared.args.listen or shared.args.share) else 0.0417 + if cur_time - last_update > min_update_interval: last_update = cur_time yield reply @@ -218,20 +219,6 @@ def fix_galactica(s): return s -def get_reply_from_output_ids(output_ids, input_ids, original_question, state, is_chat=False): - if shared.is_seq2seq: - reply = decode(output_ids, state['skip_special_tokens']) - else: - new_tokens = len(output_ids) - len(input_ids[0]) - reply = decode(output_ids[-new_tokens:], state['skip_special_tokens']) - # Prevent LlamaTokenizer from skipping a space - if type(shared.tokenizer) in [transformers.LlamaTokenizer, transformers.LlamaTokenizerFast] and len(output_ids) > 0: - if shared.tokenizer.convert_ids_to_tokens(int(output_ids[-new_tokens])).startswith('▁'): - reply = ' ' + reply - - return reply - - def set_manual_seed(seed): seed = int(seed) if seed == -1: @@ -242,6 +229,7 @@ def set_manual_seed(seed): torch.cuda.manual_seed_all(seed) elif is_torch_xpu_available(): torch.xpu.manual_seed_all(seed) + return seed @@ -274,6 +262,19 @@ def apply_stopping_strings(reply, all_stop_strings): return reply, stop_found +def get_reply_from_output_ids(output_ids, state, starting_from=0): + if shared.is_seq2seq: + reply = decode(output_ids, state['skip_special_tokens']) + else: + reply = decode(output_ids[starting_from:], state['skip_special_tokens']) + # Prevent LlamaTokenizer from skipping a space + if type(shared.tokenizer) in [transformers.LlamaTokenizer, transformers.LlamaTokenizerFast] and len(output_ids) > 0: + if shared.tokenizer.convert_ids_to_tokens(int(output_ids[starting_from])).startswith('▁'): + reply = ' ' + reply + + return reply + + def generate_reply_HF(question, original_question, seed, state, stopping_strings=None, is_chat=False): generate_params = {} for k in ['max_new_tokens', 'do_sample', 'temperature', 'temperature_last', 'top_p', 'min_p', 'typical_p', 'repetition_penalty', 'presence_penalty', 'frequency_penalty', 'repetition_penalty_range', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping', 'tfs', 'top_a', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta', 'guidance_scale']: @@ -341,7 +342,7 @@ def generate_reply_HF(question, original_question, seed, state, stopping_strings if cuda: output = output.cuda() - yield get_reply_from_output_ids(output, input_ids, original_question, state, is_chat=is_chat) + yield get_reply_from_output_ids(output, state, starting_from=len(input_ids[0])) # Stream the reply 1 token at a time. # This is based on the trick of using 'stopping_criteria' to create an iterator. @@ -357,11 +358,15 @@ def generate_with_streaming(**kwargs): return Iteratorize(generate_with_callback, [], kwargs, callback=None) with generate_with_streaming(**generate_params) as generator: + cumulative_reply = '' + starting_from = len(input_ids[0]) for output in generator: if output[-1] in eos_token_ids: break - yield get_reply_from_output_ids(output, input_ids, original_question, state, is_chat=is_chat) + cumulative_reply += get_reply_from_output_ids(output, state, starting_from=starting_from) + starting_from = len(output) + yield cumulative_reply except Exception: traceback.print_exc()
## Checklist: - [ ] I have read the [Contributing guidelines](https://github.com/oobabooga/text-generation-webui/wiki/Contributing-guidelines).
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/4815
2023-12-05T04:30:46Z
2023-12-05T04:30:58Z
2023-12-05T04:30:57Z
2023-12-05T04:30:58Z
1,035
oobabooga/text-generation-webui
26,398
build(deps): bump twilio from 8.12.0 to 9.0.0
diff --git a/requirements_with_versions.txt b/requirements_with_versions.txt index 76a0f06da6..995d950548 100644 --- a/requirements_with_versions.txt +++ b/requirements_with_versions.txt @@ -28,7 +28,7 @@ requests==2.31.0 quo==2023.5.1 PyPDF2==3.0.1 pyserial==3.5 -twilio==8.12.0 +twilio==9.0.0 tabula==1.0.5 nltk==3.8.1 Pillow==10.2.0
Bumps [twilio](https://github.com/twilio/twilio-python) from 8.12.0 to 9.0.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/twilio/twilio-python/releases">twilio's releases</a>.</em></p> <blockquote> <h2>9.0.0</h2> <h2><strong>Release Notes</strong></h2> <p><strong>Note:</strong> This release contains breaking changes, check our <a href="https://github.com/twilio/twilio-python/blob/HEAD/UPGRADE.md###-2024-02-20-8xx-to-9xx">upgrade guide</a> for detailed migration notes.</p> <p><strong>Library - Feature</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/767">#767</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/767">twilio/twilio-python#767</a>): Merge branch '9.0.0-rc' into main. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>! <strong>(breaking change)</strong></li> </ul> <p><strong>Library - Chore</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/771">#771</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/771">twilio/twilio-python#771</a>): added check for unset values. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>!</li> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/768">#768</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/768">twilio/twilio-python#768</a>): cluster tests enabled. Thanks to <a href="https://github.com/sbansla"><code>@​sbansla</code></a>!</li> </ul> <p><strong>Api</strong></p> <ul> <li>remove feedback and feedback summary from call resource</li> </ul> <p><strong>Flex</strong></p> <ul> <li>Adding <code>routing_properties</code> to Interactions Channels Participant</li> </ul> <p><strong>Lookups</strong></p> <ul> <li>Add new <code>line_status</code> package to the lookup response</li> <li>Remove <code>live_activity</code> package from the lookup response <strong>(breaking change)</strong></li> </ul> <p><strong>Messaging</strong></p> <ul> <li>Add tollfree multiple rejection reasons response array</li> </ul> <p><strong>Trusthub</strong></p> <ul> <li>Add ENUM for businessRegistrationAuthority in compliance_registration. <strong>(breaking change)</strong></li> <li>Add new field in isIsvEmbed in compliance_registration.</li> <li>Add additional optional fields in compliance_registration for Individual business type.</li> </ul> <p><strong>Twiml</strong></p> <ul> <li>Add support for new Amazon Polly and Google voices (Q1 2024) for <code>Say</code> verb</li> </ul> <p><strong><a href="https://twilio.com/docs/libraries/reference/twilio-python/9.0.0/index.html">Docs</a></strong></p> <h2>9.0.0-rc.2</h2> <h2><strong>Release Notes</strong></h2> <p><strong>Library - Chore</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/765">#765</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/765">twilio/twilio-python#765</a>): disables cluster test. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>!</li> </ul> <p><strong>Flex</strong></p> <ul> <li>Adding <code>flex_instance_sid</code> to Flex Configuration</li> </ul> <p><strong>Insights</strong></p> <ul> <li>add flag to restrict access to unapid customers</li> </ul> <p><strong>Lookups</strong></p> <ul> <li>Remove <code>carrier</code> field from <code>sms_pumping_risk</code> and leave <code>carrier_risk_category</code> <strong>(breaking change)</strong></li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/twilio/twilio-python/blob/main/CHANGES.md">twilio's changelog</a>.</em></p> <blockquote> <h2>[2024-02-27] Version 9.0.0</h2> <p><strong>Note:</strong> This release contains breaking changes, check our <a href="https://github.com/twilio/twilio-python/blob/main/UPGRADE.md###-2024-02-20-8xx-to-9xx">upgrade guide</a> for detailed migration notes.</p> <p><strong>Library - Feature</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/767">#767</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/767">twilio/twilio-python#767</a>): Merge branch '9.0.0-rc' into main. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>! <strong>(breaking change)</strong></li> </ul> <p><strong>Library - Chore</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/771">#771</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/771">twilio/twilio-python#771</a>): added check for unset values. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>!</li> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/768">#768</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/768">twilio/twilio-python#768</a>): cluster tests enabled. Thanks to <a href="https://github.com/sbansla"><code>@​sbansla</code></a>!</li> </ul> <p><strong>Api</strong></p> <ul> <li>remove feedback and feedback summary from call resource</li> </ul> <p><strong>Flex</strong></p> <ul> <li>Adding <code>routing_properties</code> to Interactions Channels Participant</li> </ul> <p><strong>Lookups</strong></p> <ul> <li>Add new <code>line_status</code> package to the lookup response</li> <li>Remove <code>live_activity</code> package from the lookup response <strong>(breaking change)</strong></li> </ul> <p><strong>Messaging</strong></p> <ul> <li>Add tollfree multiple rejection reasons response array</li> </ul> <p><strong>Trusthub</strong></p> <ul> <li>Add ENUM for businessRegistrationAuthority in compliance_registration. <strong>(breaking change)</strong></li> <li>Add new field in isIsvEmbed in compliance_registration.</li> <li>Add additional optional fields in compliance_registration for Individual business type.</li> </ul> <p><strong>Twiml</strong></p> <ul> <li>Add support for new Amazon Polly and Google voices (Q1 2024) for <code>Say</code> verb</li> </ul> <h2>[2024-02-09] Version 8.13.0</h2> <p><strong>Library - Fix</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/753">#753</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/753">twilio/twilio-python#753</a>): added boolean_to_string converter. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>!</li> </ul> <p><strong>Library - Chore</strong></p> <ul> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/758">#758</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/758">twilio/twilio-python#758</a>): disable cluster test. Thanks to <a href="https://github.com/sbansla"><code>@​sbansla</code></a>!</li> <li>[PR <a href="https://redirect.github.com/twilio/twilio-python/issues/760">#760</a>](<a href="https://redirect.github.com/twilio/twilio-python/pull/760">twilio/twilio-python#760</a>): run make prettier. Thanks to <a href="https://github.com/tiwarishubham635"><code>@​tiwarishubham635</code></a>!</li> </ul> <p><strong>Api</strong></p> <ul> <li>Updated service base url for connect apps and authorized connect apps APIs <strong>(breaking change)</strong></li> <li>Update documentation to reflect RiskCheck GA</li> <li>Added optional parameter <code>CallToken</code> for create participant api</li> </ul> <p><strong>Events</strong></p> <ul> <li>Marked as GA</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Upgrade guide</summary> <p><em>Sourced from <a href="https://github.com/twilio/twilio-python/blob/main/UPGRADE.md">twilio's upgrade guide</a>.</em></p> <blockquote> <h1>Upgrade Guide</h1> <p><em><code>MAJOR</code> version bumps will have upgrade notes posted here.</em></p> <h2>[2024-02-20] 8.x.x to 9.x.x</h2> <h3>Overview</h3> <h5>Twilio Python Helper Library’s major version 9.0.0 is now available. We ensured that you can upgrade to Python helper Library 9.0.0 version without any breaking changes of existing apis</h5> <p>Behind the scenes Python Helper is now auto-generated via OpenAPI with this release. This enables us to rapidly add new features and enhance consistency across versions and languages. We're pleased to inform you that version 9.0.0 adds support for the application/json content type in the request body.</p> <h2>[2023-04-05] 7.x.x to 8.x.x</h2> <ul> <li> <p><strong>Supported Python versions updated</strong></p> <ul> <li>Dropped support for Python 3.6 (<a href="https://redirect.github.com/twilio/twilio-python/pull/632">#632</a>)</li> <li>Python 3.7 is the new required minimum version to use twilio-python helper library</li> </ul> </li> <li> <p><strong>Deletion of TwiML Voice Deprecated Methods (<a href="https://redirect.github.com/twilio/twilio-python/pull/643">#643</a>)</strong></p> <ul> <li> <p><a href="https://www.twilio.com/docs/voice/twiml/refer"><code>&lt;Refer&gt;</code></a></p> <ul> <li><code>Refer.refer_sip()</code> replaced by <code>Refer.sip()</code></li> </ul> </li> <li> <p><a href="https://www.twilio.com/docs/voice/twiml/say/text-speech#generating-ssml-via-helper-libraries"><code>&lt;Say&gt;</code></a></p> <ul> <li><code>Say.ssml_break()</code> replaced by <code>Say.break_()</code></li> <li><code>Say.ssml_emphasis()</code> replaced by <code>Say.emphasis()</code></li> <li><code>Say.ssml_lang()</code> replaced by <code>Say.lang()</code></li> <li><code>Say.ssml_p()</code> replaced by <code>Say.p()</code></li> <li><code>Say.ssml_phoneme()</code> replaced by <code>Say.phoneme()</code></li> <li><code>Say.ssml_prosody()</code> replaced by <code>Say.prosody()</code></li> <li><code>Say.ssml_s()</code> replaced by <code>Say.s()</code></li> <li><code>Say.ssml_say_as()</code> replaced by <code>Say.say_as()</code></li> <li><code>Say.ssml_sub()</code> replaced by <code>Say.sub()</code></li> <li><code>Say.ssml_w()</code> replaced by <code>Say.w()</code></li> </ul> <p>Old:</p> <pre lang="python"><code>from twilio.twiml.voice_response import VoiceResponse resp = VoiceResponse() say = resp.say(&quot;Hello&quot;) say.ssml_emphasis(&quot;you&quot;) </code></pre> <p>New:</p> <pre lang="python"><code>from twilio.twiml.voice_response import VoiceResponse resp = VoiceResponse() </code></pre> </li> </ul> </li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/twilio/twilio-python/commit/e4285a40a798fce3a0894b1f7e40bb0c3e8955ef"><code>e4285a4</code></a> Release 9.0.0</li> <li><a href="https://github.com/twilio/twilio-python/commit/af6547ffc7e94099915bcddffbb0489eacf87a7b"><code>af6547f</code></a> [Librarian] Regenerated @ f75e0fb81b57afeb6b457dc85e19644ebb530f9b</li> <li><a href="https://github.com/twilio/twilio-python/commit/7b52a49026a45bad6cb4e2840cb8f77d51a216f8"><code>7b52a49</code></a> * feat: json content type (<a href="https://redirect.github.com/twilio/twilio-python/issues/737">#737</a>)</li> <li><a href="https://github.com/twilio/twilio-python/commit/69441eb97ff9d9a36703a057ff88a49978d5a92f"><code>69441eb</code></a> chore: added check for unset values (<a href="https://redirect.github.com/twilio/twilio-python/issues/771">#771</a>)</li> <li><a href="https://github.com/twilio/twilio-python/commit/040d2eb487908cf973b5227f0b19693638985b4e"><code>040d2eb</code></a> chore: cluster tests enabled (<a href="https://redirect.github.com/twilio/twilio-python/issues/768">#768</a>)</li> <li><a href="https://github.com/twilio/twilio-python/commit/d8fa9e8e6859c0a163fbfa7e2796b1ef69676264"><code>d8fa9e8</code></a> Release 8.13.0</li> <li><a href="https://github.com/twilio/twilio-python/commit/ced068b4d8f6798f9e41822e8c1f50cf0ebbc6a3"><code>ced068b</code></a> [Librarian] Regenerated @ c3db20dd5f24647ef2bd3fb8b955496c59bb22bd</li> <li><a href="https://github.com/twilio/twilio-python/commit/2287a7b9f76e1cd4d1060e9febbbf8c4434e875d"><code>2287a7b</code></a> fix: added boolean_to_string converter (<a href="https://redirect.github.com/twilio/twilio-python/issues/753">#753</a>)</li> <li><a href="https://github.com/twilio/twilio-python/commit/f0a2548f11bcff4fcfcaa557ca3c1aa1f91105e8"><code>f0a2548</code></a> chore: disable cluster test (<a href="https://redirect.github.com/twilio/twilio-python/issues/758">#758</a>)</li> <li><a href="https://github.com/twilio/twilio-python/commit/98dab3184e220970c0ae1db899210d59c6df838f"><code>98dab31</code></a> chore: run make prettier (<a href="https://redirect.github.com/twilio/twilio-python/issues/760">#760</a>)</li> <li>See full diff in <a href="https://github.com/twilio/twilio-python/compare/8.12.0...9.0.0">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=twilio&package-manager=pip&previous-version=8.12.0&new-version=9.0.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/geekcomputers/Python/pulls/2139
2024-02-27T18:27:20Z
2024-03-02T11:36:35Z
2024-03-02T11:36:35Z
2024-03-02T11:36:42Z
139
geekcomputers/Python
31,215
Fix broken link in CAP theorem section
diff --git a/README.md b/README.md index 7bbee48736..99fe2d94f2 100644 --- a/README.md +++ b/README.md @@ -463,7 +463,7 @@ AP is a good choice if the business needs allow for [eventual consistency](#even ### Source(s) and further reading * [CAP theorem revisited](http://robertgreiner.com/2014/08/cap-theorem-revisited/) -* [A plain english introduction to CAP theorem](http://ksat.me/a-plain-english-introduction-to-cap-theorem/) +* [A plain english introduction to CAP theorem](http://ksat.me/a-plain-english-introduction-to-cap-theorem) * [CAP FAQ](https://github.com/henryr/cap-faq) ## Consistency patterns
https://api.github.com/repos/donnemartin/system-design-primer/pulls/348
2020-01-07T19:53:37Z
2020-02-17T02:00:45Z
2020-02-17T02:00:45Z
2020-12-20T11:10:05Z
186
donnemartin/system-design-primer
36,716
Update proxy.ini
diff --git a/code/default/gae_proxy/local/proxy.ini b/code/default/gae_proxy/local/proxy.ini index 9ceada8867..811afb0d01 100644 --- a/code/default/gae_proxy/local/proxy.ini +++ b/code/default/gae_proxy/local/proxy.ini @@ -71,8 +71,8 @@ ip = 127.0.0.1 port = 8086 file = proxy.pac gfwlist = https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt -;adblock = http://adblock-chinalist.googlecode.com/svn/trunk/adblock.txt -; this project have stopped. +adblock = https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt + expired = 86400 ;front proxy for connect to google ip
更新广告过滤地址
https://api.github.com/repos/XX-net/XX-Net/pulls/5151
2017-03-16T04:23:34Z
2017-03-21T02:41:38Z
2017-03-21T02:41:38Z
2017-03-21T02:41:38Z
189
XX-net/XX-Net
17,278
fix: allow mode as argument
diff --git a/gym/core.py b/gym/core.py index ffffb22000a..2b507322e45 100644 --- a/gym/core.py +++ b/gym/core.py @@ -43,7 +43,7 @@ def _deprecate_mode(render_func): # type: ignore def render( self: object, *args: Tuple[Any], **kwargs: Dict[str, Any] ) -> render_return: - if "mode" in kwargs.keys(): + if "mode" in kwargs.keys() or len(args) > 0: deprecation( "The argument mode in render method is deprecated; " "use render_mode during environment initialization instead.\n" @@ -386,9 +386,9 @@ def reset(self, **kwargs) -> Union[ObsType, Tuple[ObsType, dict]]: """Resets the environment with kwargs.""" return self.env.reset(**kwargs) - def render(self, **kwargs): - """Renders the environment with kwargs.""" - return self.env.render(**kwargs) + def render(self, *args, **kwargs): + """Renders the environment.""" + return self.env.render(*args, **kwargs) def close(self): """Closes the environment.""" diff --git a/gym/utils/passive_env_checker.py b/gym/utils/passive_env_checker.py index 147d360e8d0..41f97145002 100644 --- a/gym/utils/passive_env_checker.py +++ b/gym/utils/passive_env_checker.py @@ -290,7 +290,7 @@ def passive_env_step_check(env, action): return result -def passive_env_render_check(env, **kwargs): +def passive_env_render_check(env, *args, **kwargs): """A passive check of the `Env.render` that the declared render modes/fps in the metadata of the environment is decleared.""" render_modes = env.metadata.get("render_modes") if render_modes is None: @@ -307,4 +307,4 @@ def passive_env_render_check(env, **kwargs): "rendering may occur at inconsistent fps" ) - return env.render(**kwargs) + return env.render(*args, **kwargs) diff --git a/gym/wrappers/env_checker.py b/gym/wrappers/env_checker.py index 9c0b5d817fb..8a7570cc04b 100644 --- a/gym/wrappers/env_checker.py +++ b/gym/wrappers/env_checker.py @@ -48,10 +48,10 @@ def reset(self, **kwargs) -> Union[ObsType, Tuple[ObsType, dict]]: else: return self.env.reset(**kwargs) - def render(self, **kwargs): + def render(self, *args, **kwargs): """Renders the environment that on the first call will run the `passive_env_render_check`.""" if self.checked_render is False: self.checked_render = True - return passive_env_render_check(self.env, **kwargs) + return passive_env_render_check(self.env, *args, **kwargs) else: - return self.env.render(**kwargs) + return self.env.render(*args, **kwargs) diff --git a/gym/wrappers/order_enforcing.py b/gym/wrappers/order_enforcing.py index 4bb0720da9a..79cfb12abd7 100644 --- a/gym/wrappers/order_enforcing.py +++ b/gym/wrappers/order_enforcing.py @@ -41,11 +41,11 @@ def reset(self, **kwargs): self._has_reset = True return self.env.reset(**kwargs) - def render(self, **kwargs): + def render(self, *args, **kwargs): """Renders the environment with `kwargs`.""" if not self._disable_render_order_enforcing and not self._has_reset: raise ResetNeeded( "Cannot call `env.render()` before calling `env.reset()`, if this is a intended action, " "set `disable_render_order_enforcing=True` on the OrderEnforcer wrapper." ) - return self.env.render(**kwargs) + return self.env.render(*args, **kwargs)
# Description After https://github.com/openai/gym/pull/2706, render with Wrappers doesn't work anymore with mode as argument without keyword. For instance, the following will throw an error: ``` env = gym.make("FrozenLake-v1") env.reset() env.render('rgb_array') ``` This should fix this. ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) # Checklist: - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `pre-commit run --all-files` (see `CONTRIBUTING.md` instructions to set it up) - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] 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/2893
2022-06-14T21:29:10Z
2022-06-15T13:33:03Z
2022-06-15T13:33:03Z
2022-06-15T13:33:03Z
926
openai/gym
4,952
core: improve None value processing in merge_dicts()
diff --git a/libs/core/langchain_core/utils/_merge.py b/libs/core/langchain_core/utils/_merge.py index e21fdd96621fe1..13b91270c70d8a 100644 --- a/libs/core/langchain_core/utils/_merge.py +++ b/libs/core/langchain_core/utils/_merge.py @@ -19,11 +19,9 @@ def merge_dicts(left: Dict[str, Any], right: Dict[str, Any]) -> Dict[str, Any]: for k, v in right.items(): if k not in merged: merged[k] = v - elif merged[k] is None and v: + elif v is not None and merged[k] is None: merged[k] = v - elif v is None: - continue - elif merged[k] == v: + elif v is None or merged[k] == v: continue elif type(merged[k]) != type(v): raise TypeError( diff --git a/libs/core/tests/unit_tests/utils/test_utils.py b/libs/core/tests/unit_tests/utils/test_utils.py index e6dedb2a5a86bf..a69ea2510b41fa 100644 --- a/libs/core/tests/unit_tests/utils/test_utils.py +++ b/libs/core/tests/unit_tests/utils/test_utils.py @@ -1,9 +1,12 @@ -from typing import Dict, Optional, Tuple, Type +import re +from contextlib import AbstractContextManager, nullcontext +from typing import Dict, Optional, Tuple, Type, Union from unittest.mock import patch import pytest from langchain_core.utils import check_package_version +from langchain_core.utils._merge import merge_dicts @pytest.mark.parametrize( @@ -28,3 +31,74 @@ def test_check_package_version( else: with pytest.raises(expected[0], match=expected[1]): check_package_version(package, **check_kwargs) + + [email protected]( + ("left", "right", "expected"), + ( + # Merge `None` and `1`. + ({"a": None}, {"a": 1}, {"a": 1}), + # Merge `1` and `None`. + ({"a": 1}, {"a": None}, {"a": 1}), + # Merge `None` and a value. + ({"a": None}, {"a": 0}, {"a": 0}), + ({"a": None}, {"a": "txt"}, {"a": "txt"}), + # Merge equal values. + ({"a": 1}, {"a": 1}, {"a": 1}), + ({"a": 1.5}, {"a": 1.5}, {"a": 1.5}), + ({"a": True}, {"a": True}, {"a": True}), + ({"a": False}, {"a": False}, {"a": False}), + ({"a": "txt"}, {"a": "txt"}, {"a": "txt"}), + ({"a": [1, 2]}, {"a": [1, 2]}, {"a": [1, 2]}), + ({"a": {"b": "txt"}}, {"a": {"b": "txt"}}, {"a": {"b": "txt"}}), + # Merge strings. + ({"a": "one"}, {"a": "two"}, {"a": "onetwo"}), + # Merge dicts. + ({"a": {"b": 1}}, {"a": {"c": 2}}, {"a": {"b": 1, "c": 2}}), + ( + {"function_call": {"arguments": None}}, + {"function_call": {"arguments": "{\n"}}, + {"function_call": {"arguments": "{\n"}}, + ), + # Merge lists. + ({"a": [1, 2]}, {"a": [3]}, {"a": [1, 2, 3]}), + ({"a": 1, "b": 2}, {"a": 1}, {"a": 1, "b": 2}), + ({"a": 1, "b": 2}, {"c": None}, {"a": 1, "b": 2, "c": None}), + # + # Invalid inputs. + # + ( + {"a": 1}, + {"a": "1"}, + pytest.raises( + TypeError, + match=re.escape( + 'additional_kwargs["a"] already exists in this message, ' + "but with a different type." + ), + ), + ), + ( + {"a": (1, 2)}, + {"a": (3,)}, + pytest.raises( + TypeError, + match=( + "Additional kwargs key a already exists in left dict and value " + "has unsupported type .+tuple.+." + ), + ), + ), + ), +) +def test_merge_dicts( + left: dict, right: dict, expected: Union[dict, AbstractContextManager] +) -> None: + if isinstance(expected, AbstractContextManager): + err = expected + else: + err = nullcontext() + + with err: + actual = merge_dicts(left, right) + assert actual == expected
- **Description:** fix `None` and `0` merging in `merge_dicts()`, add tests. ```python from langchain_core.utils._merge import merge_dicts assert merge_dicts({"a": None}, {"a": 0}) == {"a": 0} ```
https://api.github.com/repos/langchain-ai/langchain/pulls/17462
2024-02-13T13:17:35Z
2024-02-13T16:48:02Z
2024-02-13T16:48:02Z
2024-02-13T16:48:02Z
1,181
langchain-ai/langchain
43,170
Add git_add_force rule
diff --git a/README.md b/README.md index 292431fd6..4b179e8b6 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ using the matched rule and runs it. Rules enabled by default are as follows: * `fix_file` &ndash; opens a file with an error in your `$EDITOR`; * `gem_unknown_command` &ndash; fixes wrong `gem` commands; * `git_add` &ndash; fixes *"pathspec 'foo' did not match any file(s) known to git."*; +* `git_add_force` &ndash; adds `--force` to `git add <pathspec>...` when paths are .gitignore'd; * `git_bisect_usage` &ndash; fixes `git bisect strt`, `git bisect goood`, `git bisect rset`, etc. when bisecting; * `git_branch_delete` &ndash; changes `git branch -d` to `git branch -D`; * `git_branch_exists` &ndash; offers `git branch -d foo`, `git branch -D foo` or `git checkout foo` when creating a branch that already exists; diff --git a/tests/rules/test_git_add_force.py b/tests/rules/test_git_add_force.py new file mode 100644 index 000000000..abe2bd79b --- /dev/null +++ b/tests/rules/test_git_add_force.py @@ -0,0 +1,22 @@ +import pytest +from thefuck.rules.git_add_force import match, get_new_command +from tests.utils import Command + + [email protected] +def stderr(): + return ('The following paths are ignored by one of your .gitignore files:\n' + 'dist/app.js\n' + 'dist/background.js\n' + 'dist/options.js\n' + 'Use -f if you really want to add them.\n') + + +def test_match(stderr): + assert match(Command('git add dist/*.js', stderr=stderr)) + assert not match(Command('git add dist/*.js')) + + +def test_get_new_command(stderr): + assert get_new_command(Command('git add dist/*.js', stderr=stderr)) \ + == "git add --force dist/*.js" diff --git a/thefuck/rules/git_add_force.py b/thefuck/rules/git_add_force.py new file mode 100644 index 000000000..9adc07255 --- /dev/null +++ b/thefuck/rules/git_add_force.py @@ -0,0 +1,13 @@ +from thefuck.utils import replace_argument +from thefuck.specific.git import git_support + + +@git_support +def match(command): + return ('add' in command.script_parts + and 'Use -f if you really want to add them.' in command.stderr) + + +@git_support +def get_new_command(command): + return replace_argument(command.script, 'add', 'add --force')
This adds `--force` to `git add` when needed. For example: $ git add dist/*.js The following paths are ignored by one of your .gitignore files: dist/app.js dist/background.js dist/options.js Use -f if you really want to add them. $ fuck git add --force dist/app.js dist/background.js dist/options.js [enter/↑/↓/ctrl+c] $
https://api.github.com/repos/nvbn/thefuck/pulls/598
2017-01-28T18:27:42Z
2017-01-30T12:02:20Z
2017-01-30T12:02:20Z
2017-01-30T12:02:21Z
668
nvbn/thefuck
30,913
Pickle raw tuples in FileData cache
diff --git a/CHANGES.md b/CHANGES.md index 1334efefe7..9fa14f3ebc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -32,6 +32,9 @@ <!-- Changes that improve Black's performance. --> +- Store raw tuples instead of NamedTuples in Black's cache, improving performance and + decreasing the size of the cache (#3877) + ### Output <!-- Changes to Black's terminal output and error messages --> diff --git a/src/black/cache.py b/src/black/cache.py index ff15da2a94..77f66cc34a 100644 --- a/src/black/cache.py +++ b/src/black/cache.py @@ -67,7 +67,8 @@ def read(cls, mode: Mode) -> Self: with cache_file.open("rb") as fobj: try: - file_data: Dict[str, FileData] = pickle.load(fobj) + data: Dict[str, Tuple[float, int, str]] = pickle.load(fobj) + file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) @@ -129,7 +130,12 @@ def write(self, sources: Iterable[Path]) -> None: with tempfile.NamedTemporaryFile( dir=str(self.cache_file.parent), delete=False ) as f: - pickle.dump(self.file_data, f, protocol=4) + # We store raw tuples in the cache because pickling NamedTuples + # doesn't work with mypyc on Python 3.8, and because it's faster. + data: Dict[str, Tuple[float, int, str]] = { + k: (*v,) for k, v in self.file_data.items() + } + pickle.dump(data, f, protocol=4) os.replace(f.name, self.cache_file) except OSError: pass
https://api.github.com/repos/psf/black/pulls/3877
2023-09-10T22:33:21Z
2023-09-10T23:16:24Z
2023-09-10T23:16:24Z
2023-09-11T00:28:42Z
442
psf/black
23,933
Bump peter-evans/create-or-update-comment from 2.0.0 to 2.0.1
diff --git a/.github/workflows/diff_shades_comment.yml b/.github/workflows/diff_shades_comment.yml index a5d213875c..76574d8058 100644 --- a/.github/workflows/diff_shades_comment.yml +++ b/.github/workflows/diff_shades_comment.yml @@ -41,7 +41,7 @@ jobs: - name: Create or update PR comment if: steps.metadata.outputs.needs-comment == 'true' - uses: peter-evans/create-or-update-comment@c9fcb64660bc90ec1cc535646af190c992007c32 + uses: peter-evans/create-or-update-comment@2b2c85d0bf1b8a7b4e7e344bd5c71dc4b9196e9f with: comment-id: ${{ steps.find-comment.outputs.comment-id }} issue-number: ${{ steps.metadata.outputs.pr-number }}
Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 2.0.0 to 2.0.1. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/peter-evans/create-or-update-comment/releases">peter-evans/create-or-update-comment's releases</a>.</em></p> <blockquote> <h2>Create or Update Comment v2.0.1</h2> <p>⚙️ Bumps <code>@actions/core</code> to transition away from <a href="https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/">deprecated runner commands</a>.</p> <h2>What's Changed</h2> <ul> <li>Add workflow permissions by <a href="https://github.com/peter-evans"><code>@​peter-evans</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/pull/120">peter-evans/create-or-update-comment#120</a></li> <li>9 dependency updates by <a href="https://github.com/github-actions"><code>@​github-actions</code></a> and <a href="https://github.com/dependabot">https://github.com/dependabot</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/peter-evans/create-or-update-comment/compare/v2.0.0...v2.0.1">https://github.com/peter-evans/create-or-update-comment/compare/v2.0.0...v2.0.1</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/2b2c85d0bf1b8a7b4e7e344bd5c71dc4b9196e9f"><code>2b2c85d</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/issues/129">#129</a> from peter-evans/update-distribution</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/f128ced803b0f4d17cd501a061346794ebdcb980"><code>f128ced</code></a> Update distribution</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/a43e0b1f8315bf8aa669f5f110e0f8f75c702dbe"><code>a43e0b1</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/issues/127">#127</a> from peter-evans/dependabot/npm_and_yarn/actions/gith...</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/26db07d4fe6774b5e90bfcebe69a1e53b7463a76"><code>26db07d</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/issues/128">#128</a> from peter-evans/update-distribution</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/ecf01f0a1e3b14687160b7e09c989223cd544896"><code>ecf01f0</code></a> Update distribution</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/fce1b53afe38a701421124a6541ad3c6a9f2da95"><code>fce1b53</code></a> Bump <code>@​actions/github</code> from 5.0.0 to 5.1.1</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/19c6b0636a2a27e091cdaa143668934c8ba0e531"><code>19c6b06</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/issues/126">#126</a> from peter-evans/dependabot/npm_and_yarn/actions/core...</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/b0aef464a48187ea85e6e3ed58fe287c08579a15"><code>b0aef46</code></a> Bump <code>@​actions/core</code> from 1.9.1 to 1.10.0</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/843e8555447930f29ef7560424a35a79589bd909"><code>843e855</code></a> Update dependabot</li> <li><a href="https://github.com/peter-evans/create-or-update-comment/commit/6fcd282399b3c9ad0bd9bd8025b8fb2c18b085dd"><code>6fcd282</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/peter-evans/create-or-update-comment/issues/122">#122</a> from peter-evans/dependabot/github_actions/actions/ch...</li> <li>Additional commits viewable in <a href="https://github.com/peter-evans/create-or-update-comment/compare/c9fcb64660bc90ec1cc535646af190c992007c32...2b2c85d0bf1b8a7b4e7e344bd5c71dc4b9196e9f">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=peter-evans/create-or-update-comment&package-manager=github_actions&previous-version=2.0.0&new-version=2.0.1)](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/psf/black/pulls/3354
2022-10-24T06:11:40Z
2022-10-24T18:40:19Z
2022-10-24T18:40:19Z
2022-10-24T18:40:24Z
210
psf/black
23,785
raise NotImplemented —> raise NotImplementedError
diff --git a/solutions/object_oriented_design/call_center/call_center.py b/solutions/object_oriented_design/call_center/call_center.py index a278559447..1d5e7bc6bc 100644 --- a/solutions/object_oriented_design/call_center/call_center.py +++ b/solutions/object_oriented_design/call_center/call_center.py @@ -66,7 +66,7 @@ def __init__(self, employee_id, name): super(Operator, self).__init__(employee_id, name, Rank.DIRECTOR) def escalate_call(self): - raise NotImplemented('Directors must be able to handle any call') + raise NotImplementedError('Directors must be able to handle any call') class CallState(Enum):
__flake8 . --count --exit-zero --max-complexity=10 --statistics__ ``` ./solutions/object_oriented_design/call_center/call_center.py:69:9: F901 'raise NotImplemented' should be 'raise NotImplementedError' ``` https://docs.python.org/3/library/exceptions.html#NotImplementedError
https://api.github.com/repos/donnemartin/system-design-primer/pulls/345
2019-12-26T08:06:00Z
2019-12-27T01:11:58Z
2019-12-27T01:11:58Z
2019-12-27T05:30:50Z
166
donnemartin/system-design-primer
36,794
py26reqs.txt needs to be path-relative
diff --git a/letsencrypt-auto b/letsencrypt-auto index 083de58c4fd..e9b7739d25f 100755 --- a/letsencrypt-auto +++ b/letsencrypt-auto @@ -14,6 +14,10 @@ XDG_DATA_HOME=${XDG_DATA_HOME:-~/.local/share} VENV_NAME="letsencrypt" VENV_PATH=${VENV_PATH:-"$XDG_DATA_HOME/$VENV_NAME"} VENV_BIN=${VENV_PATH}/bin +# The path to the letsencrypt-auto script. Everything that uses these might +# at some point be inlined... +LEA_PATH=`dirname "$0"` +BOOTSTRAP=${LEA_PATH}/bootstrap # This script takes the same arguments as the main letsencrypt program, but it # additionally responds to --verbose (more output) and --debug (allow support @@ -110,7 +114,6 @@ DeterminePythonVersion() { # later steps, causing "ImportError: cannot import name unpack_url" if [ ! -d $VENV_PATH ] then - BOOTSTRAP=`dirname $0`/bootstrap if [ ! -f $BOOTSTRAP/debian.sh ] ; then echo "Cannot find the letsencrypt bootstrap scripts in $BOOTSTRAP" exit 1 @@ -172,7 +175,7 @@ if [ "$VERBOSE" = 1 ] ; then echo $VENV_BIN/pip install -U setuptools $VENV_BIN/pip install -U pip - $VENV_BIN/pip install -r py26reqs.txt -U letsencrypt letsencrypt-apache + $VENV_BIN/pip install -r "$LEA_PATH"/py26reqs.txt -U letsencrypt letsencrypt-apache # nginx is buggy / disabled for now, but upgrade it if the user has # installed it manually if $VENV_BIN/pip freeze | grep -q letsencrypt-nginx ; then @@ -184,7 +187,7 @@ else $VENV_BIN/pip install -U pip > /dev/null printf . # nginx is buggy / disabled for now... - $VENV_BIN/pip install -r py26reqs.txt > /dev/null + $VENV_BIN/pip install -r "$LEA_PATH"/py26reqs.txt > /dev/null printf . $VENV_BIN/pip install -U letsencrypt > /dev/null printf .
Fixes: #1630
https://api.github.com/repos/certbot/certbot/pulls/1631
2015-11-27T18:33:34Z
2015-11-30T17:02:24Z
2015-11-30T17:02:24Z
2016-05-06T19:21:55Z
542
certbot/certbot
528
Refs #30997 -- Added HttpRequest.accepts().
diff --git a/django/http/request.py b/django/http/request.py index a0bdf49312863..790e4546d732c 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -20,6 +20,8 @@ from django.utils.http import is_same_domain, limited_parse_qsl from django.utils.regex_helper import _lazy_re_compile +from .multipartparser import parse_header + RAISE_ERROR = object() host_validation_re = _lazy_re_compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$") @@ -71,6 +73,17 @@ def __repr__(self): def headers(self): return HttpHeaders(self.META) + @cached_property + def accepted_types(self): + """Return a list of MediaType instances.""" + return parse_accept_header(self.headers.get('Accept', '*/*')) + + def accepts(self, media_type): + return any( + accepted_type.match(media_type) + for accepted_type in self.accepted_types + ) + def _set_content_type_params(self, meta): """Set content_type, content_params, and encoding.""" self.content_type, self.content_params = cgi.parse_header(meta.get('CONTENT_TYPE', '')) @@ -557,6 +570,40 @@ def encode(k, v): return '&'.join(output) +class MediaType: + def __init__(self, media_type_raw_line): + full_type, self.params = parse_header( + media_type_raw_line.encode('ascii') if media_type_raw_line else b'' + ) + self.main_type, _, self.sub_type = full_type.partition('/') + + def __str__(self): + params_str = ''.join( + '; %s=%s' % (k, v.decode('ascii')) + for k, v in self.params.items() + ) + return '%s%s%s' % ( + self.main_type, + ('/%s' % self.sub_type) if self.sub_type else '', + params_str, + ) + + def __repr__(self): + return '<%s: %s>' % (self.__class__.__qualname__, self) + + @property + def is_all_types(self): + return self.main_type == '*' and self.sub_type == '*' + + def match(self, other): + if self.is_all_types: + return True + other = MediaType(other) + if self.main_type == other.main_type and self.sub_type in {'*', other.sub_type}: + return True + return False + + # It's neither necessary nor appropriate to use # django.utils.encoding.force_str() for parsing URLs and form inputs. Thus, # this slightly more restricted function, used by QueryDict. @@ -612,3 +659,7 @@ def validate_host(host, allowed_hosts): Return ``True`` for a valid host, ``False`` otherwise. """ return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) + + +def parse_accept_header(header): + return [MediaType(token) for token in header.split(',') if token.strip()] diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index 370993444b419..2f9e78e358285 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -406,6 +406,29 @@ Methods Returns ``True`` if the request is secure; that is, if it was made with HTTPS. +.. method:: HttpRequest.accepts(mime_type) + + .. versionadded:: 3.1 + + Returns ``True`` if the request ``Accept`` header matches the ``mime_type`` + argument:: + + >>> request.accepts('text/html') + True + + Most browsers send ``Accept: */*`` by default, so this would return + ``True`` for all content types. Setting an explicit ``Accept`` header in + API requests can be useful for returning a different content type for those + consumers only. See :ref:`content-negotiation-example` of using + ``accepts()`` to return different content to API consumers. + + If a response varies depending on the content of the ``Accept`` header and + you are using some form of caching like Django's :mod:`cache middleware + <django.middleware.cache>`, you should decorate the view with + :func:`vary_on_headers('Accept') + <django.views.decorators.vary.vary_on_headers>` so that the responses are + properly cached. + .. method:: HttpRequest.is_ajax() Returns ``True`` if the request was made via an ``XMLHttpRequest``, by diff --git a/docs/releases/3.1.txt b/docs/releases/3.1.txt index 709c3917bc57e..3c88ecadd751c 100644 --- a/docs/releases/3.1.txt +++ b/docs/releases/3.1.txt @@ -282,6 +282,9 @@ Requests and Responses now allow using ``samesite='None'`` (string) to explicitly state that the cookie is sent with all same-site and cross-site requests. +* The new :meth:`.HttpRequest.accepts` method returns whether the request + accepts the given MIME type according to the ``Accept`` HTTP header. + Serialization ~~~~~~~~~~~~~ diff --git a/docs/topics/class-based-views/generic-editing.txt b/docs/topics/class-based-views/generic-editing.txt index c1e73fc2fb27e..7c61592142a9e 100644 --- a/docs/topics/class-based-views/generic-editing.txt +++ b/docs/topics/class-based-views/generic-editing.txt @@ -222,41 +222,43 @@ to edit, and override aren't logged in from accessing the form. If you omit that, you'll need to handle unauthorized users in :meth:`~.ModelFormMixin.form_valid()`. -AJAX example -============ +.. _content-negotiation-example: + +Content negotiation example +=========================== Here is an example showing how you might go about implementing a form that -works for AJAX requests as well as 'normal' form POSTs:: +works with an API-based workflow as well as 'normal' form POSTs:: from django.http import JsonResponse from django.views.generic.edit import CreateView from myapp.models import Author - class AjaxableResponseMixin: + class JsonableResponseMixin: """ - Mixin to add AJAX support to a form. + Mixin to add JSON support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) - if self.request.is_ajax(): - return JsonResponse(form.errors, status=400) - else: + if self.request.accepts('text/html'): return response + else: + return JsonResponse(form.errors, status=400) def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super().form_valid(form) - if self.request.is_ajax(): + if self.request.accepts('text/html'): + return response + else: data = { 'pk': self.object.pk, } return JsonResponse(data) - else: - return response - class AuthorCreate(AjaxableResponseMixin, CreateView): + class AuthorCreate(JsonableResponseMixin, CreateView): model = Author fields = ['name'] diff --git a/tests/requests/test_accept_header.py b/tests/requests/test_accept_header.py new file mode 100644 index 0000000000000..76559920af681 --- /dev/null +++ b/tests/requests/test_accept_header.py @@ -0,0 +1,101 @@ +from unittest import TestCase + +from django.http import HttpRequest +from django.http.request import MediaType + + +class MediaTypeTests(TestCase): + def test_empty(self): + for empty_media_type in (None, ''): + with self.subTest(media_type=empty_media_type): + media_type = MediaType(empty_media_type) + self.assertIs(media_type.is_all_types, False) + self.assertEqual(str(media_type), '') + self.assertEqual(repr(media_type), '<MediaType: >') + + def test_str(self): + self.assertEqual(str(MediaType('*/*; q=0.8')), '*/*; q=0.8') + self.assertEqual(str(MediaType('application/xml')), 'application/xml') + + def test_repr(self): + self.assertEqual(repr(MediaType('*/*; q=0.8')), '<MediaType: */*; q=0.8>') + self.assertEqual( + repr(MediaType('application/xml')), + '<MediaType: application/xml>', + ) + + def test_is_all_types(self): + self.assertIs(MediaType('*/*').is_all_types, True) + self.assertIs(MediaType('*/*; q=0.8').is_all_types, True) + self.assertIs(MediaType('text/*').is_all_types, False) + self.assertIs(MediaType('application/xml').is_all_types, False) + + def test_match(self): + tests = [ + ('*/*; q=0.8', '*/*'), + ('*/*', 'application/json'), + (' */* ', 'application/json'), + ('application/*', 'application/json'), + ('application/xml', 'application/xml'), + (' application/xml ', 'application/xml'), + ('application/xml', ' application/xml '), + ] + for accepted_type, mime_type in tests: + with self.subTest(accepted_type, mime_type=mime_type): + self.assertIs(MediaType(accepted_type).match(mime_type), True) + + def test_no_match(self): + tests = [ + (None, '*/*'), + ('', '*/*'), + ('; q=0.8', '*/*'), + ('application/xml', 'application/html'), + ('application/xml', '*/*'), + ] + for accepted_type, mime_type in tests: + with self.subTest(accepted_type, mime_type=mime_type): + self.assertIs(MediaType(accepted_type).match(mime_type), False) + + +class AcceptHeaderTests(TestCase): + def test_no_headers(self): + """Absence of Accept header defaults to '*/*'.""" + request = HttpRequest() + self.assertEqual( + [str(accepted_type) for accepted_type in request.accepted_types], + ['*/*'], + ) + + def test_accept_headers(self): + request = HttpRequest() + request.META['HTTP_ACCEPT'] = ( + 'text/html, application/xhtml+xml,application/xml ;q=0.9,*/*;q=0.8' + ) + self.assertEqual( + [str(accepted_type) for accepted_type in request.accepted_types], + [ + 'text/html', + 'application/xhtml+xml', + 'application/xml; q=0.9', + '*/*; q=0.8', + ], + ) + + def test_request_accepts_any(self): + request = HttpRequest() + request.META['HTTP_ACCEPT'] = '*/*' + self.assertIs(request.accepts('application/json'), True) + + def test_request_accepts_none(self): + request = HttpRequest() + request.META['HTTP_ACCEPT'] = '' + self.assertIs(request.accepts('application/json'), False) + self.assertEqual(request.accepted_types, []) + + def test_request_accepts_some(self): + request = HttpRequest() + request.META['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;q=0.9' + self.assertIs(request.accepts('text/html'), True) + self.assertIs(request.accepts('application/xhtml+xml'), True) + self.assertIs(request.accepts('application/xml'), True) + self.assertIs(request.accepts('application/json'), False)
ticket-30997
https://api.github.com/repos/django/django/pulls/12366
2020-01-24T10:11:59Z
2020-01-24T13:48:39Z
2020-01-24T13:48:39Z
2020-01-24T13:49:04Z
2,704
django/django
51,517
fix(hybridcloud) Don't use proxy for opsgenie
diff --git a/src/sentry/integrations/opsgenie/client.py b/src/sentry/integrations/opsgenie/client.py index 8c1d440985372..8eff6f5a391e6 100644 --- a/src/sentry/integrations/opsgenie/client.py +++ b/src/sentry/integrations/opsgenie/client.py @@ -4,11 +4,11 @@ from urllib.parse import quote from sentry.eventstore.models import Event, GroupEvent +from sentry.integrations.client import ApiClient from sentry.models.group import Group from sentry.models.integrations.integration import Integration from sentry.services.hybrid_cloud.integration.model import RpcIntegration from sentry.shared_integrations.client.base import BaseApiResponseX -from sentry.shared_integrations.client.proxy import IntegrationProxyClient OPSGENIE_API_VERSION = "v2" # Defaults to P3 if null, but we can be explicit - https://docs.opsgenie.com/docs/alert-api @@ -17,20 +17,20 @@ OpsgeniePriority = Literal["P1", "P2", "P3", "P4", "P5"] -class OpsgenieClient(IntegrationProxyClient): +class OpsgenieClient(ApiClient): integration_name = "opsgenie" def __init__( self, integration: RpcIntegration | Integration, integration_key: str, - org_integration_id: int | None, - keyid: str | None = None, + org_integration_id: int | None = None, # deprecated but still passed by getsentry + keyid: str | None = None, # deprecated but still passed by getsentry ) -> None: self.integration = integration self.base_url = f"{self.metadata['base_url']}{OPSGENIE_API_VERSION}" self.integration_key = integration_key - super().__init__(org_integration_id=org_integration_id, keyid=keyid) + super().__init__(integration_id=self.integration.id) @property def metadata(self): diff --git a/src/sentry/integrations/opsgenie/integration.py b/src/sentry/integrations/opsgenie/integration.py index c6efaa344c313..606b6d64e56e0 100644 --- a/src/sentry/integrations/opsgenie/integration.py +++ b/src/sentry/integrations/opsgenie/integration.py @@ -122,8 +122,6 @@ def get_keyring_client(self, keyid: str) -> OpsgenieClient: return OpsgenieClient( integration=self.model, integration_key=team["integration_key"], - org_integration_id=org_integration.id, - keyid=keyid, ) def get_client(self) -> Any: # type: ignore
Opsgenie doesn't use refresh tokens and gains no benefit from the integration proxy. To reduce failure points we can bypass the proxy. Refs HC-1125
https://api.github.com/repos/getsentry/sentry/pulls/65827
2024-02-26T21:30:08Z
2024-02-27T20:01:13Z
2024-02-27T20:01:13Z
2024-03-14T00:23:05Z
614
getsentry/sentry
44,143
Update link to hypercorn
diff --git a/docs/deploying/asgi.rst b/docs/deploying/asgi.rst index 36acff8ac5..1dc0aa2493 100644 --- a/docs/deploying/asgi.rst +++ b/docs/deploying/asgi.rst @@ -20,7 +20,7 @@ wrapping the Flask app, asgi_app = WsgiToAsgi(app) and then serving the ``asgi_app`` with the ASGI server, e.g. using -`Hypercorn <https://gitlab.com/pgjones/hypercorn>`_, +`Hypercorn <https://github.com/pgjones/hypercorn>`_, .. sourcecode:: text
<!-- 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. --> Update link to Hypercorn at https://flask.palletsprojects.com/en/3.0.x/deploying/asgi/ Deprecated link: https://gitlab.com/pgjones/hypercorn New link: https://github.com/pgjones/hypercorn <!-- Link to relevant issues or previous PRs, one per line. Use "fixes" to automatically close an issue. --> - fixes #5312
https://api.github.com/repos/pallets/flask/pulls/5313
2023-10-28T08:36:04Z
2023-10-28T15:42:54Z
2023-10-28T15:42:54Z
2023-11-12T00:06:11Z
154
pallets/flask
20,327
Add BackboneMixin
diff --git a/src/transformers/modeling_utils.py b/src/transformers/modeling_utils.py index fd96aacabc2ac..265b79dca13a8 100644 --- a/src/transformers/modeling_utils.py +++ b/src/transformers/modeling_utils.py @@ -15,6 +15,7 @@ # limitations under the License. import collections import gc +import inspect import json import os import re @@ -932,6 +933,15 @@ def floating_point_ops( return 6 * self.estimate_tokens(input_dict) * self.num_parameters(exclude_embeddings=exclude_embeddings) +class BackboneMixin: + def forward_with_filtered_kwargs(self, *args, **kwargs): + + signature = dict(inspect.signature(self.forward).parameters) + filtered_kwargs = {k: v for k, v in kwargs.items() if k in signature} + + return self(*args, **filtered_kwargs) + + class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin, PushToHubMixin): r""" Base class for all models. diff --git a/src/transformers/models/bit/modeling_bit.py b/src/transformers/models/bit/modeling_bit.py index ac88a704b4c45..3704b1d9872bb 100644 --- a/src/transformers/models/bit/modeling_bit.py +++ b/src/transformers/models/bit/modeling_bit.py @@ -30,7 +30,7 @@ BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) -from ...modeling_utils import PreTrainedModel +from ...modeling_utils import BackboneMixin, PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, @@ -842,7 +842,7 @@ def forward( """, BIT_START_DOCSTRING, ) -class BitBackbone(BitPreTrainedModel): +class BitBackbone(BitPreTrainedModel, BackboneMixin): def __init__(self, config): super().__init__(config) diff --git a/src/transformers/models/maskformer/modeling_maskformer_swin.py b/src/transformers/models/maskformer/modeling_maskformer_swin.py index 60410a36210de..05af1b90ff1b0 100644 --- a/src/transformers/models/maskformer/modeling_maskformer_swin.py +++ b/src/transformers/models/maskformer/modeling_maskformer_swin.py @@ -27,7 +27,7 @@ from ...activations import ACT2FN from ...file_utils import ModelOutput from ...modeling_outputs import BackboneOutput -from ...modeling_utils import PreTrainedModel +from ...modeling_utils import BackboneMixin, PreTrainedModel from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer from .configuration_maskformer_swin import MaskFormerSwinConfig @@ -837,7 +837,7 @@ def forward( ) -class MaskFormerSwinBackbone(MaskFormerSwinPreTrainedModel): +class MaskFormerSwinBackbone(MaskFormerSwinPreTrainedModel, BackboneMixin): """ MaskFormerSwin backbone, designed especially for the MaskFormer framework. diff --git a/src/transformers/models/resnet/modeling_resnet.py b/src/transformers/models/resnet/modeling_resnet.py index c3d65ddc05e6a..ebd134be5454f 100644 --- a/src/transformers/models/resnet/modeling_resnet.py +++ b/src/transformers/models/resnet/modeling_resnet.py @@ -28,7 +28,7 @@ BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) -from ...modeling_utils import PreTrainedModel +from ...modeling_utils import BackboneMixin, PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, @@ -431,7 +431,7 @@ def forward( """, RESNET_START_DOCSTRING, ) -class ResNetBackbone(ResNetPreTrainedModel): +class ResNetBackbone(ResNetPreTrainedModel, BackboneMixin): def __init__(self, config): super().__init__(config)
# What does this PR do? Add `BackboneMixin` with a method `forward_with_filtered_kwargs`.
https://api.github.com/repos/huggingface/transformers/pulls/20660
2022-12-07T18:48:00Z
2022-12-08T15:55:48Z
2022-12-08T15:55:48Z
2022-12-08T15:59:15Z
938
huggingface/transformers
12,617
fix update fail for Android
diff --git a/code/default/launcher/update_from_github.py b/code/default/launcher/update_from_github.py index d837bddcae..4a4b72e9dc 100644 --- a/code/default/launcher/update_from_github.py +++ b/code/default/launcher/update_from_github.py @@ -185,13 +185,15 @@ def overwrite(xxnet_version, xxnet_unzip_path): dst_file = os.path.join(top_path, target_relate_path, filename) if not os.path.isfile(dst_file) or hash_file_sum(src_file) != hash_file_sum(dst_file): xlog.info("copy %s => %s", src_file, dst_file) - if sys.platform != 'win32' and os.path.isfile(dst_file): + #modify by outofmemo, files in '/sdcard' are not allowed to chmod for Android + #and shutil.copy() will call shutil.copymode() + if sys.platform != 'win32' and os.path.isfile("/system/bin/dalvikvm")==False and os.path.isfile("/system/bin/dalvikvm64")==False and os.path.isfile(dst_file): st = os.stat(dst_file) shutil.copy(src_file, dst_file) if st.st_mode & stat.S_IEXEC: os.chmod(dst_file, st.st_mode) else: - shutil.copy(src_file, dst_file) + shutil.copyfile(src_file, dst_file) except Exception as e: xlog.warn("update over write fail:%r", e)
files in '/sdcard' are not allowed to chmod
https://api.github.com/repos/XX-net/XX-Net/pulls/5595
2017-05-26T12:30:27Z
2017-07-26T10:07:08Z
2017-07-26T10:07:08Z
2017-07-26T10:07:08Z
328
XX-net/XX-Net
17,370
Removed GoodReads
diff --git a/README.md b/README.md index 2bbfdfc2ed..41fccd20db 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,6 @@ API | Description | Auth | HTTPS | CORS | |---|---|---|---|---| | [Bhagavad Gita](https://bhagavadgita.io/api) | Bhagavad Gita text | `OAuth` | Yes | Yes | | [British National Bibliography](http://bnb.data.bl.uk/) | Books | No | No | Unknown | -| [Goodreads](https://www.goodreads.com/api) | Books | `apiKey` | Yes | Unknown | | [Google Books](https://developers.google.com/books/) | Books | `OAuth` | Yes | Unknown | | [LibGen](https://garbage.world/posts/libgen/) | Library Genesis search engine | No | No | Unknown | | [Open Library](https://openlibrary.org/developers/api) | Books, book covers and related data | No | Yes | No |
Goodreads API being phased out https://www.goodreads.com/api "As of December 8th 2020, Goodreads is no longer issuing new developer keys for our public developer API and plans to retire these tools." <!-- 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: --> - [ ] My submission is formatted according to the guidelines in the [contributing guide](CONTRIBUTING.md) - [ ] My addition is ordered alphabetically - [ ] My submission has a useful description - [ ] The description does not end with punctuation - [ ] Each table column is padded with one space on either side - [ ] I have searched the repository for any relevant issues or pull requests - [ ] Any category I am creating has the minimum requirement of 3 items - [ ] 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/1486
2020-12-14T03:04:52Z
2020-12-14T16:07:52Z
2020-12-14T16:07:52Z
2020-12-14T16:07:52Z
234
public-apis/public-apis
35,207
Changed cors for urlHaus
diff --git a/README.md b/README.md index e77ff0700b..c8875252b8 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ API | Description | Auth | HTTPS | CORS | | [Metacert](https://metacert.com/) | Metacert Link Flagging | `apiKey` | Yes | Unknown | | [Phisherman](https://phisherman.gg/) | IP/domain/URL reputation | `apiKey` | Yes | Unknown | | [Scanii](https://docs.scanii.com/) | Simple REST API that can scan submitted documents/files for the presence of threats | `apiKey` | Yes | Yes | -| [URLhaus](https://urlhaus-api.abuse.ch/) | Bulk queries and Download Malware Samples | No | Yes | Unknown | +| [URLhaus](https://urlhaus-api.abuse.ch/) | Bulk queries and Download Malware Samples | No | Yes | Yes | | [URLScan.io](https://urlscan.io/about-api/) | Scan and Analyse URLs | `apiKey` | Yes | Unknown | | [VirusTotal](https://www.virustotal.com/en/documentation/public-api/) | VirusTotal File/URL Analysis | `apiKey` | Yes | Unknown | | [Web of Trust](https://support.mywot.com/hc/en-us/sections/360004477734-API-) | IP/domain/URL reputation | `apiKey` | Yes | Unknown |
Changed cors for urlHaus to yes
https://api.github.com/repos/public-apis/public-apis/pulls/2968
2021-12-22T07:00:07Z
2021-12-22T08:41:50Z
2021-12-22T08:41:50Z
2021-12-22T08:41:50Z
320
public-apis/public-apis
35,385
Calculator_with_simple_ui. Py
diff --git a/Calculator with simple ui b/Calculator with simple ui new file mode 100644 index 0000000000..eb0a5b727a --- /dev/null +++ b/Calculator with simple ui @@ -0,0 +1,49 @@ +# Program make a simple calculator + +# This function adds two numbers +def add(x, y): + return x + y + +# This function subtracts two numbers +def subtract(x, y): + return x - y + +# This function multiplies two numbers +def multiply(x, y): + return x * y + +# This function divides two numbers +def divide(x, y): + return x / y + + +print("Select operation.") +print("1.Add") +print("2.Subtract") +print("3.Multiply") +print("4.Divide") + +while True: + # Take input from the user + choice = input("Enter choice(1/2/3/4): ") + + # Check if choice is one of the four options + if choice in ('1', '2', '3', '4'): + num1 = float(input("Enter first number: ")) + num2 = float(input("Enter second number: ")) + + if choice == '1': + print(num1, "+", num2, "=", add(num1, num2)) + + elif choice == '2': + print(num1, "-", num2, "=", subtract(num1, num2)) + + elif choice == '3': + print(num1, "*", num2, "=", multiply(num1, num2)) + + elif choice == '4': + print(num1, "/", num2, "=", divide(num1, num2)) + break + else: + print("Invalid Input") +
This is a how you can create a simple calculator using python with a decent ui.
https://api.github.com/repos/geekcomputers/Python/pulls/1373
2021-09-03T05:15:40Z
2021-09-09T17:06:45Z
2021-09-09T17:06:45Z
2021-09-09T17:06:45Z
410
geekcomputers/Python
31,793
[3.8] bpo-26510: Add versionchanged for required arg of add_subparsers (GH-16588)
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 56bd64172f8012..ee00559485c1da 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -1595,7 +1595,7 @@ Sub-commands stored; by default ``None`` and no value is stored * required_ - Whether or not a subcommand must be provided, by default - ``False``. + ``False`` (added in 3.7) * help_ - help for sub-parser group in help output, by default ``None`` @@ -1751,6 +1751,9 @@ Sub-commands >>> parser.parse_args(['2', 'frobble']) Namespace(subparser_name='2', y='frobble') + .. versionchanged:: 3.7 + New *required* keyword argument. + FileType objects ^^^^^^^^^^^^^^^^ diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst index af7e22d9faa9e4..1ec8e0c04c76ba 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -2401,6 +2401,10 @@ Changes in the Python API instead of a :class:`bytes` instance. (Contributed by Victor Stinner in :issue:`21071`.) +* :mod:`argparse` subparsers can now be made mandatory by passing ``required=True`` + to :meth:`ArgumentParser.add_subparsers() <argparse.ArgumentParser.add_subparsers>`. + (Contributed by Anthony Sottile in :issue:`26510`.) + * :meth:`ast.literal_eval()` is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka in :issue:`31778`.)
The `required` argument to `argparse.add_subparsers` was added in GH-3027. This PR specifies the earliest version of Python where it is available. https://bugs.python.org/issue26510 Automerge-Triggered-By: @merwok (cherry picked from commit 9e71917e0290972f65711f75510078f799cf0b59) Co-authored-by: Adam J. Stewart <[email protected]> <!-- issue-number: [bpo-26510](https://bugs.python.org/issue26510) --> https://bugs.python.org/issue26510 <!-- /issue-number --> Automerge-Triggered-By: @merwok
https://api.github.com/repos/python/cpython/pulls/16608
2019-10-07T02:09:16Z
2019-10-07T02:15:45Z
2019-10-07T02:15:45Z
2019-10-07T02:15:47Z
469
python/cpython
4,359
Removed docs/internals/roles.txt.
diff --git a/docs/index.txt b/docs/index.txt index 9c4f393041ab3..fa6ff8474a726 100644 --- a/docs/index.txt +++ b/docs/index.txt @@ -339,7 +339,6 @@ you can contribute: :doc:`The release process <internals/release-process>` | :doc:`Team organization <internals/organization>` | :doc:`Meet the team <internals/team>` | - :doc:`Current roles <internals/roles>` | :doc:`The Django source code repository <internals/git>` | :doc:`Security policies <internals/security>` | :doc:`Mailing lists <internals/mailing-lists>` diff --git a/docs/internals/contributing/committing-code.txt b/docs/internals/contributing/committing-code.txt index d42fdb8940bfb..fd526b1dd6680 100644 --- a/docs/internals/contributing/committing-code.txt +++ b/docs/internals/contributing/committing-code.txt @@ -2,10 +2,9 @@ Committing code =============== -This section is addressed to the :ref:`committers` and to anyone interested in -knowing how code gets committed into Django core. If you're a community member -who wants to contribute code to Django, have a look at -:doc:`writing-code/working-with-git` instead. +This section is addressed to the committers and to anyone interested in knowing +how code gets committed into Django. If you're a community member who wants to +contribute code to Django, look at :doc:`writing-code/working-with-git` instead. .. _handling-pull-requests: diff --git a/docs/internals/git.txt b/docs/internals/git.txt index 0e35544eb48c9..386a2a05a754a 100644 --- a/docs/internals/git.txt +++ b/docs/internals/git.txt @@ -242,8 +242,7 @@ branches, used for Google Summer of Code projects. Tags ==== -Each Django release is tagged and signed by a :ref:`releaser -<releasers-list>`. +Each Django release is tagged and signed by the releaser. The tags can be found on GitHub's `tags`_ page. diff --git a/docs/internals/index.txt b/docs/internals/index.txt index e9c32fe304483..95183e4db0b7b 100644 --- a/docs/internals/index.txt +++ b/docs/internals/index.txt @@ -12,7 +12,6 @@ you'd like to help improve Django or learn about how Django is managed. mailing-lists organization team - roles security release-process deprecation diff --git a/docs/internals/organization.txt b/docs/internals/organization.txt index 5982621757c32..11000b2ff1801 100644 --- a/docs/internals/organization.txt +++ b/docs/internals/organization.txt @@ -162,9 +162,8 @@ capacity on non-technical decisions. Membership ---------- -The technical board is an elected group of five committers. They're expected -to be experienced but there's no formal seniority requirement. Its current -composition is published :ref:`here <technical-board-list>`. +`The technical board`_ is an elected group of five committers. They're expected +to be experienced but there's no formal seniority requirement. A new board is elected after each feature release of Django. The election process is managed by a returns officer nominated by the outgoing technical @@ -183,6 +182,8 @@ board. The election process works as follows: Both the application and the voting period last between one and two weeks, at the outgoing board's discretion. +.. _the technical board: https://www.djangoproject.com/foundation/teams/#technical-board-team + Changing the organization ========================= diff --git a/docs/internals/roles.txt b/docs/internals/roles.txt deleted file mode 100644 index aabd11dbb750c..0000000000000 --- a/docs/internals/roles.txt +++ /dev/null @@ -1,70 +0,0 @@ -===== -Roles -===== - -.. _technical-board-list: - -Technical board -=============== - -The technical board for the 1.11 release cycle is: - -* James Bennett -* Andrew Godwin -* Russell Keith-Magee -* Carl Meyer -* Marc Tamlyn - -.. _committers: - -Committers -========== - -Most :ref:`core team <core-team>` members have commit access. They're called -"committers" or "core developers". - -Being part of the core team is a pre-requisite for having commit access. - -.. _security-team-list: - -Security team -============= - -The security team is responsible for :doc:`Django's security policies -</internals/security>`. It handles private reports of security issues. - -The current security team members are: - -- Florian Apolloner -- James Bennett -- Tim Graham -- Adrian Holovaty -- Markus Holtermann -- Paul McMillan -- Carl Meyer - -.. _releasers-list: - -Releasers -========= - -Releasers take care of :doc:`building Django releases -</internals/howto-release-django>`. - -The current releasers are: - -- James Bennett -- Jacob Kaplan-Moss -- Tim Graham - -Ops team -======== - -The ops team maintains Django's infrastructure like the Django Project server, -Trac instance, and continuous integration infrastructure. - -- Florian Apolloner -- Tim Graham -- Markus Holtermann -- Jannis Leidel -- Tobias McNulty diff --git a/docs/internals/security.txt b/docs/internals/security.txt index 148418e0fed95..5b4441b7aa131 100644 --- a/docs/internals/security.txt +++ b/docs/internals/security.txt @@ -23,9 +23,8 @@ publicly reported in this fashion. Instead, if you believe you've found something in Django which has security implications, please send a description of the issue via email to -``[email protected]``. Mail sent to that address reaches a -:ref:`subset of the core team <security-team-list>`, who can forward security -issues into the private team's mailing list for broader discussion if needed. +``[email protected]``. Mail sent to that address reaches the `securty +team <https://www.djangoproject.com/foundation/teams/#security-team>`_. Once you've submitted an issue via email, you should receive an acknowledgment from a member of the security team within 48 hours, and depending on the @@ -106,7 +105,7 @@ triaging our announcement and upgrade Django as needed. Severity levels are: Second, we notify a list of :ref:`people and organizations <security-notifications>`, primarily composed of operating-system vendors and other distributors of Django. This email is signed with the PGP key of someone -from :ref:`Django's release team <releasers-list>` and consists of: +from `Django's release team`_ and consists of: * A full description of the issue and the affected versions of Django. @@ -150,6 +149,8 @@ theirs. The Django team also maintains an :doc:`archive of security issues disclosed in Django</releases/security>`. +.. _Django's release team: https://www.djangoproject.com/foundation/teams/#releasers-team + .. _security-notifications: Who receives advance notification
It's moved to https://www.djangoproject.com/foundation/teams/.
https://api.github.com/repos/django/django/pulls/8061
2017-02-14T16:38:22Z
2017-02-15T08:31:43Z
2017-02-15T08:31:43Z
2017-02-15T12:21:02Z
1,683
django/django
51,316
Create Python Program for factorial of a number
diff --git a/Python Program for factorial of a number b/Python Program for factorial of a number new file mode 100644 index 0000000000..dbbf3f7f7c --- /dev/null +++ b/Python Program for factorial of a number @@ -0,0 +1,33 @@ +Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. + +Recursive: +# Python 3 program to find +# factorial of given number +def factorial(n): + + # single line to find factorial + return 1 if (n==1 or n==0) else n * factorial(n - 1); + +# Driver Code +num = 5; +print("Factorial of",num,"is", +factorial(num)) +Iterative: +# Python 3 program to find +# factorial of given number +def factorial(n): + if n < 0: + return 0 + elif n == 0 or n == 1: + return 1 + else: + fact = 1 + while(n > 1): + fact *= n + n -= 1 + return fact + +# Driver Code +num = 5; +print("Factorial of",num,"is", +factorial(num))
Recursive: # Python 3 program to find # factorial of given number def factorial(n): # single line to find factorial return 1 if (n==1 or n==0) else n * factorial(n - 1); # Driver Code num = 5; print("Factorial of",num,"is", factorial(num))
https://api.github.com/repos/geekcomputers/Python/pulls/1132
2020-10-15T07:47:46Z
2020-10-23T07:44:05Z
2020-10-23T07:44:05Z
2020-10-23T07:44:05Z
337
geekcomputers/Python
31,879
Return virtual_facts after VMWare platform detection
diff --git a/changelogs/fragments/facts_vmware_detection.yaml b/changelogs/fragments/facts_vmware_detection.yaml new file mode 100644 index 00000000000000..2f903c3c0f60fd --- /dev/null +++ b/changelogs/fragments/facts_vmware_detection.yaml @@ -0,0 +1,2 @@ +minor_changes: +- Return virtual_facts after VMware platform detection, otherwise we're falling back to 'NA' for virtualization type and virtualization role. diff --git a/lib/ansible/module_utils/facts/virtual/linux.py b/lib/ansible/module_utils/facts/virtual/linux.py index fece8d8f22b940..819adfaaaf6b61 100644 --- a/lib/ansible/module_utils/facts/virtual/linux.py +++ b/lib/ansible/module_utils/facts/virtual/linux.py @@ -245,6 +245,7 @@ def get_virtual_facts(self): if vendor_name.startwith('VMware'): virtual_facts['virtualization_type'] = 'VMware' virtual_facts['virtualization_role'] = 'guest' + return virtual_facts # If none of the above matches, return 'NA' for virtualization_type # and virtualization_role. This allows for proper grouping.
##### SUMMARY (cherry picked from commit 4f36d7965e833a196281987312e27c2dffa05418) ##### ISSUE TYPE - Bugfix Pull Request ##### COMPONENT NAME changelogs/fragments/facts_vmware_detection.yaml lib/ansible/module_utils/facts/virtual/linux.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes below --> ``` Stable-2.5 ```
https://api.github.com/repos/ansible/ansible/pulls/39149
2018-04-23T10:07:34Z
2018-04-25T12:24:55Z
2018-04-25T12:24:55Z
2019-04-27T00:40:32Z
290
ansible/ansible
49,274
Remove PPA instructions from docs
diff --git a/certbot/docs/install.rst b/certbot/docs/install.rst index 3be648f25bc..c1d8cc40310 100644 --- a/certbot/docs/install.rst +++ b/certbot/docs/install.rst @@ -248,18 +248,7 @@ replacing ``certbot`` with the name of the desired package. **Ubuntu** -If you run Ubuntu Trusty, Xenial, or Bionic, certbot is available through the official PPA, -that can be installed as followed: - -.. code-block:: shell - - sudo apt-get update - sudo apt-get install software-properties-common - sudo add-apt-repository universe - sudo add-apt-repository ppa:certbot/certbot - sudo apt-get update - -Then, certbot can be installed using: +If you run Ubuntu, certbot can be installed using: .. code-block:: shell
We're doing what we can to keep the PPA working in the most basic sense, but it is essentially deprecated and new users should not use it. I created https://github.com/certbot/certbot/issues/8363 to track doing more with these docs. I just wanted to remove the PPA instructions for now.
https://api.github.com/repos/certbot/certbot/pulls/8364
2020-10-09T16:54:41Z
2020-10-09T19:44:10Z
2020-10-09T19:44:10Z
2020-10-09T19:44:13Z
212
certbot/certbot
2,237
Don't make redundant copies of the DFA
diff --git a/src/blib2to3/pgen2/parse.py b/src/blib2to3/pgen2/parse.py index 4a23d538b4..a9dc11f39c 100644 --- a/src/blib2to3/pgen2/parse.py +++ b/src/blib2to3/pgen2/parse.py @@ -54,7 +54,7 @@ def stack_copy( stack: List[Tuple[DFAS, int, RawNode]] ) -> List[Tuple[DFAS, int, RawNode]]: """Nodeless stack copy.""" - return [(copy.deepcopy(dfa), label, DUMMY_NODE) for dfa, label, _ in stack] + return [(dfa, label, DUMMY_NODE) for dfa, label, _ in stack] class Recorder:
`copy.deepcopy` is still the most expensive part (75/100 of the extra overhead introduced by the backtracking parser). I initially assumed it was mutable (since it was represented as a tuple of lists), but seems like we only use it as a basic table and don't mutate it anywhere in the code. ``` -t py39 (main):: Mean +- std dev: 7.21 ms +- 0.25 ms -t py310 (this branch):: Mean +- std dev: 13.8 ms +- 0.6 ms -t py310 (this branch):: Mean +- std dev: 7.98 ms +- 0.24 ms ``` This reduces the total overhead of the new backtracking parser from %91 to %11 (ran with tuned pyperf, but confirm please). We can even get rid of the `stack_copy` and just do a bare `parser.stack.copy()`, but I think it gives a nice abstraction and prevents leakage of any real nodes into the backtracking stack. In case anything goes wrong, and this does not seem to have an observable overhead.
https://api.github.com/repos/psf/black/pulls/2763
2022-01-11T17:32:31Z
2022-01-14T02:01:44Z
2022-01-14T02:01:44Z
2022-01-14T02:01:44Z
183
psf/black
23,966
kucoinfutures: add missing endpoints
diff --git a/ts/src/kucoinfutures.ts b/ts/src/kucoinfutures.ts index c9cff36955fe..efc747c10abd 100644 --- a/ts/src/kucoinfutures.ts +++ b/ts/src/kucoinfutures.ts @@ -153,14 +153,19 @@ export default class kucoinfutures extends kucoin { 'position': 1, 'positions': 4.44, 'funding-history': 4.44, + 'sub/api-key': 1, }, 'post': { 'withdrawals': 1, 'transfer-out': 1, // v2 + 'transfer-in': 1, 'orders': 1.33, 'position/margin/auto-deposit-status': 1, 'position/margin/deposit-margin': 1, + 'position/risk-limit-level/change': 1, 'bullet-private': 1, + 'sub/api-key': 1, + 'sub/api-key/update': 1, }, 'delete': { 'withdrawals/{withdrawalId}': 1, @@ -168,6 +173,7 @@ export default class kucoinfutures extends kucoin { 'orders/{orderId}': 1, 'orders': 4.44, 'stopOrders': 1, + 'sub/api-key': 1, }, }, 'webFront': {
Added some missing endpoints to kucoinfutures: fixes: #17897 ``` kucoinfutures futuresPrivatePostPositionRiskLimitLevelChange '{"symbol":"XBTUSDTM","level":2}' kucoinfutures.futuresPrivatePostPositionRiskLimitLevelChange ([object Object]) 2023-05-13T06:26:07.034Z iteration 0 passed in 595 ms { code: '200000', data: true } ```
https://api.github.com/repos/ccxt/ccxt/pulls/17904
2023-05-13T06:38:08Z
2023-05-13T12:45:48Z
2023-05-13T12:45:48Z
2023-05-13T12:45:49Z
321
ccxt/ccxt
13,722
Add warning about changing the UA
diff --git a/certbot/client.py b/certbot/client.py index af2868f6aba..7896ab7dc65 100644 --- a/certbot/client.py +++ b/certbot/client.py @@ -53,6 +53,9 @@ def determine_user_agent(config): :rtype: `str` """ + # WARNING: To ensure changes are in line with Certbot's privacy + # policy, talk to a core Certbot team member before making any + # changes here. if config.user_agent is None: ua = ("CertbotACMEClient/{0} ({1}; {2}) Authenticator/{3} Installer/{4} " "({5}; flags: {6}) Py/{7}")
https://api.github.com/repos/certbot/certbot/pulls/4843
2017-06-15T22:57:39Z
2017-06-16T22:01:14Z
2017-06-16T22:01:14Z
2017-06-16T22:02:18Z
167
certbot/certbot
1,518
Update yolov5-bifpn.yaml
diff --git a/models/hub/yolov5-bifpn.yaml b/models/hub/yolov5-bifpn.yaml index f1dd7c601b9..69f7b5938c5 100644 --- a/models/hub/yolov5-bifpn.yaml +++ b/models/hub/yolov5-bifpn.yaml @@ -3,38 +3,44 @@ nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple anchors: - - [ 10,13, 16,30, 33,23 ] # P3/8 - - [ 30,61, 62,45, 59,119 ] # P4/16 - - [ 116,90, 156,198, 373,326 ] # P5/32 + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 # YOLOv5 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, Bottleneck, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, BottleneckCSP, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, BottleneckCSP, [ 512 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 - [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ], - [ -1, 6, BottleneckCSP, [ 1024 ] ], # 9 + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]] + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, C3, [1024, False]], # 9 ] # YOLOv5 BiFPN head head: - [ [ -1, 3, BottleneckCSP, [ 1024, False ] ], # 10 (P5/32-large) + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 20, 6 ], 1, Concat, [ 1 ] ], # cat P4 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 3, BottleneckCSP, [ 512, False ] ], # 14 (P4/16-medium) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 3, BottleneckCSP, [ 256, False ] ], # 18 (P3/8-small) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14, 6], 1, Concat, [1]], # cat P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) - [ [ 18, 14, 10 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) ]
## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Enhanced YOLOv5 architecture with BiFPN and C3 module integration for improved object detection. ### 📊 Key Changes - **Anchor Format**: Whitespaces have been removed for consistency in anchor definitions. - **Backbone Updates**: Replaced `Bottleneck` and `BottleneckCSP` with `C3` modules, which may provide improved feature extraction. - **Head Changes**: Simplified and modified the BiFPN head structure, introducing `C3` modules and additional concatenation steps to fuse features from different scales more effectively. ### 🎯 Purpose & Impact - **Performance**: The introduction of `C3` modules is aimed at enhancing learning representations, which can lead to better detection performance. - **Feature Integration**: BiFPN alterations are designed to strengthen feature pyramid networking, producing a more robust multi-scale feature integration, potentially leading to improved detection accuracy. - **User Experience**: This update should increase the model's object detection capabilities and potentially improve inference times, benefiting developers and end-users who require high-performance object detection. 🏎️🔍
https://api.github.com/repos/ultralytics/yolov5/pulls/4208
2021-07-28T19:25:15Z
2021-07-28T19:25:20Z
2021-07-28T19:25:20Z
2024-01-19T16:37:52Z
1,452
ultralytics/yolov5
24,885
Update environments.md
diff --git a/docs/environments.md b/docs/environments.md index e607a1363c6..80721414b76 100644 --- a/docs/environments.md +++ b/docs/environments.md @@ -424,6 +424,6 @@ Learn more here: https://github.com/dynamik1703/gym_longicontrol ### safe-control-gym -PyBullet-based CartPole and Quadrotor environments—with [CadADi](https://web.casadi.org) (symbolic) *a priori* dynamics and constraints—for learning-based control and model-based reinforcement learning. +PyBullet-based CartPole and Quadrotor environments—with [CasADi](https://web.casadi.org) (symbolic) *a priori* dynamics and constraints—for learning-based control and model-based reinforcement learning. Learn more here: https://github.com/utiasDSL/safe-control-gym
I'm so sorry I mistyped the name of the fantastic CasADi optimization toolbox (https://web.casadi.org)
https://api.github.com/repos/openai/gym/pulls/2338
2021-08-21T03:24:17Z
2021-08-21T20:09:37Z
2021-08-21T20:09:37Z
2021-08-21T20:09:37Z
196
openai/gym
5,140
fixes error when not specifying tunnel id
diff --git a/extensions/api/util.py b/extensions/api/util.py index 0db1c46c5a..032a9e5c93 100644 --- a/extensions/api/util.py +++ b/extensions/api/util.py @@ -99,7 +99,10 @@ def _start_cloudflared(port: int, tunnel_id: str, max_attempts: int = 3, on_star for _ in range(max_attempts): try: - public_url = _run_cloudflared(port, port + 1, tunnel_id=tunnel_id) + if tunnel_id is not None: + public_url = _run_cloudflared(port, port + 1, tunnel_id=tunnel_id) + else: + public_url = _run_cloudflared(port, port + 1) if on_start: on_start(public_url)
Added a simple if statement to not pass in the tunnel_id arg if it was not specified. It addresses the error people get when using --public-api as seen in the error below. I was having the same problem and wanted to make a fix that will work with or without passing in the tunnel_id https://github.com/oobabooga/text-generation-webui/issues/3570#issue-1849302813 ## Checklist: - [✅] I have read the [Contributing guidelines](https://github.com/oobabooga/text-generation-webui/wiki/Contributing-guidelines).
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/3606
2023-08-17T15:48:25Z
2023-08-17T18:20:37Z
2023-08-17T18:20:37Z
2023-08-17T18:20:37Z
186
oobabooga/text-generation-webui
26,183
Permissive parsing of nginx map blocks
diff --git a/certbot-compatibility-test/nginx/nginx-roundtrip-testdata/anothermapcase/nginx.conf b/certbot-compatibility-test/nginx/nginx-roundtrip-testdata/anothermapcase/nginx.conf new file mode 100644 index 00000000000..b3ca02f929c --- /dev/null +++ b/certbot-compatibility-test/nginx/nginx-roundtrip-testdata/anothermapcase/nginx.conf @@ -0,0 +1,3 @@ +map $uri $blogname{ + ~^(?P<blogpath>/[^/]+/)files/(.*) $blogpath ; +} diff --git a/certbot-nginx/certbot_nginx/nginxparser.py b/certbot-nginx/certbot_nginx/nginxparser.py index d6c352296f4..1859777d869 100644 --- a/certbot-nginx/certbot_nginx/nginxparser.py +++ b/certbot-nginx/certbot_nginx/nginxparser.py @@ -23,10 +23,12 @@ class RawNginxParser(object): right_bracket = space.leaveWhitespace() + Literal("}").suppress() semicolon = Literal(";").suppress() key = Word(alphanums + "_/+-.") - dollar_var = Combine(Literal('$') + nonspace) + dollar_var = Combine(Literal('$') + Regex(r"[^\{\};,\s]+")) condition = Regex(r"\(.+\)") # Matches anything that is not a special character AND any chars in single # or double quotes + # All of these COULD be upgraded to something like + # https://stackoverflow.com/a/16130746 value = Regex(r"((\".*\")?(\'.*\')?[^\{\};,]?)+") location = CharsNotIn("{};," + string.whitespace) # modifier for location uri [ = | ~ | ~* | ^~ ] @@ -38,19 +40,35 @@ class RawNginxParser(object): assignment = space + key + Optional(space + value, default=None) + semicolon location_statement = space + Optional(modifier) + Optional(space + location + space) if_statement = space + Literal("if") + space + condition + space + map_statement = space + Literal("map") + space + nonspace + space + dollar_var + space - block = Forward() + # This is NOT an accurate way to parse nginx map entries; it's almost + # certianly too permissive and may be wrong in other ways, but it should + # preserve things correctly in mmmmost or all cases. + # + # - I can neither prove nor disprove that it is corect wrt all escaped + # semicolon situations + # Addresses https://github.com/fatiherikli/nginxparser/issues/19 + map_pattern = Regex(r'".*"') | Regex(r"'.*'") | nonspace + map_entry = space + map_pattern + space + value + space + semicolon + map_block = Group( + # key could for instance be "server" or "http", or "location" (in which case + # location_statement needs to have a non-empty location) + Group(map_statement).leaveWhitespace() + + left_bracket + + Group(ZeroOrMore(Group(comment | map_entry)) + space).leaveWhitespace() + + right_bracket) + block = Forward() block << Group( # key could for instance be "server" or "http", or "location" (in which case # location_statement needs to have a non-empty location) - (Group(space + key + location_statement) ^ Group(if_statement) ^ - Group(map_statement)).leaveWhitespace() + + (Group(space + key + location_statement) ^ Group(if_statement)).leaveWhitespace() + left_bracket + - Group(ZeroOrMore(Group(comment | assignment) | block) + space).leaveWhitespace() + - right_bracket) + Group(ZeroOrMore(Group(comment | assignment) | block | map_block) + space).leaveWhitespace() + + right_bracket) - script = OneOrMore(Group(comment | assignment) ^ block) + space + stringEnd + script = OneOrMore(Group(comment | assignment) ^ block ^ map_block) + space + stringEnd script.parseWithTabs() def __init__(self, source):
Closes #3206, at least in a good-enough-for-now sense.
https://api.github.com/repos/certbot/certbot/pulls/3230
2016-06-30T22:14:05Z
2016-07-13T22:54:17Z
2016-07-13T22:54:17Z
2016-10-06T01:21:39Z
973
certbot/certbot
2,411
fix(bitmart) - handling issues
diff --git a/ts/src/pro/bitmart.ts b/ts/src/pro/bitmart.ts index a3c8854890ed..a4e03400f111 100644 --- a/ts/src/pro/bitmart.ts +++ b/ts/src/pro/bitmart.ts @@ -845,9 +845,9 @@ export default class bitmart extends bitmartRest { const isSwap = ('group' in message); if (isSwap) { // in swap, chronologically decreasing: 1709536849322, 1709536848954, - const maxLen = Math.max (length - 1, 0); - for (let i = maxLen; i >= 0; i--) { - symbol = this.handleTradeLoop (data[i]); + for (let i = 0; i < length; i++) { + const index = length - i - 1; + symbol = this.handleTradeLoop (data[index]); } } else { // in spot, chronologically increasing: 1709536771200, 1709536771226, @@ -1497,7 +1497,17 @@ export default class bitmart extends bitmartRest { } // // {"event":"error","message":"Unrecognized request: {\"event\":\"subscribe\",\"channel\":\"spot/depth:BTC-USDT\"}","errorCode":30039} - // {"event":"subscribe","channel":"spot/depth:BTC-USDT"} + // + // subscribe events on spot: + // + // {"event":"subscribe", "topic":"spot/kline1m:BTC_USDT" } + // + // subscribe on contracts: + // + // {"action":"subscribe", "group":"futures/klineBin1m:BTCUSDT", "success":true, "request":{"action":"subscribe", "args":[ "futures/klineBin1m:BTCUSDT" ] } } + // + // regular updates - spot + // // { // "table": "spot/depth", // "action": "partial", @@ -1518,10 +1528,21 @@ export default class bitmart extends bitmartRest { // ] // } // + // regular updates - contracts + // + // { + // group: "futures/klineBin1m:BTCUSDT", + // data: { + // symbol: "BTCUSDT", + // items: [ { o: "67944.7", "h": .... } ], + // }, + // } + // // { data: '', table: "spot/user/order" } // - const channel = this.safeString2 (message, 'table', 'group'); - if (channel === undefined) { + // the only realiable way (for both spot & swap) is to check 'data' key + const isDataUpdate = ('data' in message); + if (!isDataUpdate) { const event = this.safeString2 (message, 'event', 'action'); if (event !== undefined) { const methods = { @@ -1536,6 +1557,7 @@ export default class bitmart extends bitmartRest { } } } else { + const channel = this.safeString2 (message, 'table', 'group'); const methods = { 'depth': this.handleOrderBook, 'ticker': this.handleTicker,
fixes bitmart, which caused build issues: https://app.travis-ci.com/github/ccxt/ccxt/builds/269349696#L3706
https://api.github.com/repos/ccxt/ccxt/pulls/21627
2024-03-08T16:40:13Z
2024-03-09T12:43:15Z
2024-03-09T12:43:15Z
2024-03-09T12:43:15Z
769
ccxt/ccxt
13,645
Add Migration Utilities
diff --git a/README.md b/README.md index 9ed3b87ca..4844eff0a 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by - [Miscellaneous](#miscellaneous) - [Algorithms and Design Patterns](#algorithms-and-design-patterns) - [Editor Plugins](#editor-plugins) + - [Migration Utilities](#migration-utilities) - [Resources](#resources) - [Websites](#websites) - [Weekly](#weekly) @@ -1061,6 +1062,14 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by * [Linter-flake8](https://github.com/AtomLinter/linter-flake8) - An addon to `linter`, that acts as an interface for `flake8`. * [virtualenv](https://github.com/jhutchins/virtualenv) - Atom package for virtualenv management. +## Migration Utilities + +*Libraries for migrating from Python 2 to 3.* + +* [Six](https://pypi.python.org/pypi/six) +* [Python-Future](http://python-future.org/index.html) +* [Python-Modernize](https://github.com/mitsuhiko/python-modernize) + # Resources Where to discover new Python libraries.
Closes #257
https://api.github.com/repos/vinta/awesome-python/pulls/261
2014-11-15T12:41:32Z
2014-12-08T16:07:26Z
2014-12-08T16:07:26Z
2014-12-08T16:07:26Z
322
vinta/awesome-python
27,113
BUG: pd.array raising with NumPy array and large dtype
diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst index 09932a2d2d571..f6b0b4086cb39 100644 --- a/doc/source/whatsnew/v2.0.2.rst +++ b/doc/source/whatsnew/v2.0.2.rst @@ -22,6 +22,7 @@ Bug fixes ~~~~~~~~~ - Bug in :func:`api.interchange.from_dataframe` was returning :class:`DataFrame`'s of incorrect sizes when called on slices (:issue:`52824`) - Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on bitmasks (:issue:`49888`) +- Bug in :meth:`pd.array` raising for ``NumPy`` array and ``pa.large_string`` or ``pa.large_binary`` (:issue:`52590`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 55c6b74e495c0..a7f2ef85c2a9d 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -245,6 +245,16 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal Construct a new ExtensionArray from a sequence of scalars. """ pa_dtype = to_pyarrow_type(dtype) + if ( + isinstance(scalars, np.ndarray) + and isinstance(dtype, ArrowDtype) + and ( + pa.types.is_large_binary(pa_dtype) or pa.types.is_large_string(pa_dtype) + ) + ): + # See https://github.com/apache/arrow/issues/35289 + scalars = scalars.tolist() + if isinstance(scalars, cls): scalars = scalars._pa_array elif not isinstance(scalars, (pa.Array, pa.ChunkedArray)): diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 0300b271acc3f..7396ab3f32ef5 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -2800,6 +2800,20 @@ def test_setitem_boolean_replace_with_mask_segfault(): assert arr._pa_array == expected._pa_array [email protected]( + "data, arrow_dtype", + [ + ([b"a", b"b"], pa.large_binary()), + (["a", "b"], pa.large_string()), + ], +) +def test_conversion_large_dtypes_from_numpy_array(data, arrow_dtype): + dtype = ArrowDtype(arrow_dtype) + result = pd.array(np.array(data), dtype=dtype) + expected = pd.array(data, dtype=dtype) + tm.assert_extension_array_equal(result, expected) + + @pytest.mark.parametrize("pa_type", tm.ALL_INT_PYARROW_DTYPES + tm.FLOAT_PYARROW_DTYPES) def test_describe_numeric_data(pa_type): # GH 52470
- [x] closes #52590 (Replace xxxx with the GitHub issue number) - [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 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. not sure if we want to backport this though...
https://api.github.com/repos/pandas-dev/pandas/pulls/52591
2023-04-11T10:05:21Z
2023-04-27T00:15:00Z
2023-04-27T00:15:00Z
2023-04-27T07:50:29Z
713
pandas-dev/pandas
45,539
Remove hidden import from PyInstaller build
diff --git a/.github/workflows/upload_binary.yml b/.github/workflows/upload_binary.yml index 8f44d4ec27..766f37cc32 100644 --- a/.github/workflows/upload_binary.yml +++ b/.github/workflows/upload_binary.yml @@ -16,17 +16,14 @@ jobs: pathsep: ";" asset_name: black_windows.exe executable_mime: "application/vnd.microsoft.portable-executable" - platform: windows - os: ubuntu-20.04 pathsep: ":" asset_name: black_linux executable_mime: "application/x-executable" - platform: unix - os: macos-latest pathsep: ":" asset_name: black_macos executable_mime: "application/x-mach-binary" - platform: macos steps: - uses: actions/checkout@v2 @@ -43,10 +40,8 @@ jobs: python -m pip install pyinstaller - name: Build binary - run: > - python -m PyInstaller -F --name ${{ matrix.asset_name }} --add-data - 'src/blib2to3${{ matrix.pathsep }}blib2to3' --hidden-import platformdirs.${{ - matrix.platform }} src/black/__main__.py + run: | + python -m PyInstaller -F --name ${{ matrix.asset_name }} --add-data 'src/blib2to3${{ matrix.pathsep }}blib2to3' src/black/__main__.py - name: Upload binary as release asset uses: actions/upload-release-asset@v1
### Description The recent 2021.4 release of pyinstaller-hooks-contrib now contains a built-in hook for platformdirs. Manually specifying the hidden import arg should no longer be needed. The latest release of pyinstaller-hooks-contrib is installed when installing PyInstaller, so reverting #2466 is all that is needed. ### Checklist - did you ... - [x] Add a CHANGELOG entry if necessary? - [x] Add / update tests if necessary? - [x] Add new / update outdated documentation? I did not add a changelog entry for this as there should be no change in behavior to the end user.
https://api.github.com/repos/psf/black/pulls/2657
2021-11-29T22:37:41Z
2021-11-30T16:20:28Z
2021-11-30T16:20:28Z
2021-12-01T00:35:30Z
366
psf/black
23,845
Fix docstring for language code in mBart
diff --git a/src/transformers/models/mbart/tokenization_mbart.py b/src/transformers/models/mbart/tokenization_mbart.py index d96e69fe30130..e8425fe8c539e 100644 --- a/src/transformers/models/mbart/tokenization_mbart.py +++ b/src/transformers/models/mbart/tokenization_mbart.py @@ -153,7 +153,7 @@ def build_inputs_with_special_tokens( adding special tokens. An MBART sequence has the following format, where ``X`` represents the sequence: - ``input_ids`` (for encoder) ``X [eos, src_lang_code]`` - - ``decoder_input_ids``: (for decoder) ``[tgt_lang_code] X [eos]`` + - ``decoder_input_ids``: (for decoder) ``X [eos, tgt_lang_code]`` BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a separator. @@ -220,13 +220,13 @@ def prepare_seq2seq_batch( return model_inputs def set_src_lang_special_tokens(self, src_lang) -> None: - """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, cur_lang_code].""" + """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code].""" self.cur_lang_code = self.lang_code_to_id[src_lang] self.prefix_tokens = [] self.suffix_tokens = [self.eos_token_id, self.cur_lang_code] def set_tgt_lang_special_tokens(self, lang: str) -> None: - """Reset the special tokens to the target language setting. Prefix [tgt_lang_code], suffix =[eos].""" + """Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code].""" self.cur_lang_code = self.lang_code_to_id[lang] self.prefix_tokens = [] self.suffix_tokens = [self.eos_token_id, self.cur_lang_code] diff --git a/src/transformers/models/mbart/tokenization_mbart_fast.py b/src/transformers/models/mbart/tokenization_mbart_fast.py index c25b291c2a05c..56e7c065f3914 100644 --- a/src/transformers/models/mbart/tokenization_mbart_fast.py +++ b/src/transformers/models/mbart/tokenization_mbart_fast.py @@ -152,7 +152,7 @@ def build_inputs_with_special_tokens( An MBART sequence has the following format, where ``X`` represents the sequence: - ``input_ids`` (for encoder) ``X [eos, src_lang_code]`` - - ``decoder_input_ids``: (for decoder) ``[tgt_lang_code] X [eos]`` + - ``decoder_input_ids``: (for decoder) ``X [eos, tgt_lang_code]`` BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a separator. @@ -218,7 +218,7 @@ def prepare_seq2seq_batch( return model_inputs def set_src_lang_special_tokens(self, src_lang) -> None: - """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, cur_lang_code].""" + """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code].""" self.cur_lang_code = self.convert_tokens_to_ids(src_lang) self.prefix_tokens = [] self.suffix_tokens = [self.eos_token_id, self.cur_lang_code] @@ -233,7 +233,7 @@ def set_src_lang_special_tokens(self, src_lang) -> None: ) def set_tgt_lang_special_tokens(self, lang: str) -> None: - """Reset the special tokens to the target language setting. Prefix [tgt_lang_code], suffix =[eos].""" + """Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code].""" self.cur_lang_code = self.convert_tokens_to_ids(lang) self.prefix_tokens = [] self.suffix_tokens = [self.eos_token_id, self.cur_lang_code]
# What does this PR do? Fixes #8534 ## Before submitting - [X] This PR fixes a typo or improves the docs. ## Who can review? @patrickvonplaten
https://api.github.com/repos/huggingface/transformers/pulls/8848
2020-11-30T08:55:02Z
2020-12-01T09:44:37Z
2020-12-01T09:44:37Z
2020-12-01T09:44:37Z
930
huggingface/transformers
12,292
[pbs] Fix subtitle extraction
diff --git a/test/test_subtitles.py b/test/test_subtitles.py index 0c5b49ee8cf..9b39dbd39b0 100644 --- a/test/test_subtitles.py +++ b/test/test_subtitles.py @@ -19,6 +19,7 @@ CeskaTelevizeIE, LyndaIE, NPOIE, + PBSIE, ComedyCentralIE, NRKTVIE, RaiPlayIE, @@ -372,5 +373,42 @@ def test_subtitles_in_page(self): self.assertEqual(md5(subtitles['en']), 'acaca989e24a9e45a6719c9b3d60815c') +@is_download_test +class TestPBSSubtitles(BaseTestSubtitles): + url = 'https://www.pbs.org/video/how-fantasy-reflects-our-world-picecq/' + IE = PBSIE + + def test_allsubtitles(self): + self.DL.params['writesubtitles'] = True + self.DL.params['allsubtitles'] = True + subtitles = self.getSubtitles() + self.assertEqual(set(subtitles.keys()), set(['en'])) + + def test_subtitles_dfxp_format(self): + self.DL.params['writesubtitles'] = True + self.DL.params['subtitlesformat'] = 'dfxp' + subtitles = self.getSubtitles() + self.assertIn(md5(subtitles['en']), ['643b034254cdc3768ff1e750b6b5873b']) + + def test_subtitles_vtt_format(self): + self.DL.params['writesubtitles'] = True + self.DL.params['subtitlesformat'] = 'vtt' + subtitles = self.getSubtitles() + self.assertIn( + md5(subtitles['en']), ['937a05711555b165d4c55a9667017045', 'f49ea998d6824d94959c8152a368ff73']) + + def test_subtitles_srt_format(self): + self.DL.params['writesubtitles'] = True + self.DL.params['subtitlesformat'] = 'srt' + subtitles = self.getSubtitles() + self.assertIn(md5(subtitles['en']), ['2082c21b43759d9bf172931b2f2ca371']) + + def test_subtitles_sami_format(self): + self.DL.params['writesubtitles'] = True + self.DL.params['subtitlesformat'] = 'sami' + subtitles = self.getSubtitles() + self.assertIn(md5(subtitles['en']), ['4256b16ac7da6a6780fafd04294e85cd']) + + if __name__ == '__main__': unittest.main() diff --git a/yt_dlp/extractor/pbs.py b/yt_dlp/extractor/pbs.py index d68855d62d1..0eabf9beee8 100644 --- a/yt_dlp/extractor/pbs.py +++ b/yt_dlp/extractor/pbs.py @@ -600,6 +600,7 @@ def extract_redirect_urls(info): formats = [] http_url = None + hls_subs = {} for num, redirect in enumerate(redirects): redirect_id = redirect.get('eeid') @@ -622,8 +623,9 @@ def extract_redirect_urls(info): continue if determine_ext(format_url) == 'm3u8': - formats.extend(self._extract_m3u8_formats( - format_url, display_id, 'mp4', m3u8_id='hls', fatal=False)) + hls_formats, hls_subs = self._extract_m3u8_formats_and_subtitles( + format_url, display_id, 'mp4', m3u8_id='hls', fatal=False) + formats.extend(hls_formats) else: formats.append({ 'url': format_url, @@ -666,25 +668,12 @@ def extract_redirect_urls(info): age_limit = US_RATINGS.get(rating_str) subtitles = {} - closed_captions_url = info.get('closed_captions_url') - if closed_captions_url: - subtitles['en'] = [{ - 'ext': 'ttml', - 'url': closed_captions_url, - }] - mobj = re.search(r'/(\d+)_Encoded\.dfxp', closed_captions_url) - if mobj: - ttml_caption_suffix, ttml_caption_id = mobj.group(0, 1) - ttml_caption_id = int(ttml_caption_id) - subtitles['en'].extend([{ - 'url': closed_captions_url.replace( - ttml_caption_suffix, '/%d_Encoded.srt' % (ttml_caption_id + 1)), - 'ext': 'srt', - }, { - 'url': closed_captions_url.replace( - ttml_caption_suffix, '/%d_Encoded.vtt' % (ttml_caption_id + 2)), - 'ext': 'vtt', - }]) + captions = info.get('cc') or {} + for caption_url in captions.values(): + subtitles.setdefault('en', []).append({ + 'url': caption_url + }) + subtitles = self._merge_subtitles(subtitles, hls_subs) # info['title'] is often incomplete (e.g. 'Full Episode', 'Episode 5', etc) # Try turning it to 'program - title' naming scheme if possible
## Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [X] At least skimmed through [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) sections - [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) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [X] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [X] 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] Bug fix - [ ] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information Original PR: https://github.com/ytdl-org/youtube-dl/pull/24430 by @gesa I added tests from https://github.com/ytdl-org/youtube-dl/pull/17434, which is an older PR for adding subtitles. Fixes: https://github.com/ytdl-org/youtube-dl/issues/18796, https://github.com/ytdl-org/youtube-dl/issues/17273 I suppose too?
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/813
2021-08-29T06:04:18Z
2021-09-07T20:59:21Z
2021-09-07T20:59:21Z
2022-03-04T06:04:11Z
1,256
yt-dlp/yt-dlp
7,348
Converting a command to lowercase breaks a case-sensitive URL
diff --git a/lib/utils/api.py b/lib/utils/api.py index 3e1b1105819..2d69cdd2e9d 100644 --- a/lib/utils/api.py +++ b/lib/utils/api.py @@ -722,7 +722,7 @@ def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT): while True: try: - command = raw_input("api%s> " % (" (%s)" % taskid if taskid else "")).strip().lower() + command = raw_input("api%s> " % (" (%s)" % taskid if taskid else "")).strip() except (EOFError, KeyboardInterrupt): print break
To reproduce the bug: 1. Start the server: ./sqlmapapi.py -s 2. Start the client: ./sqlmapapi.py -c 3. Add a new task with a case-sensitive URL: new -u "http://vbox.lc/bWAPP/sqli_4.php?title=iron+man&action=search" 4. Check the log: ... "message": "testing connection to the target URL" ... "message": "page not found (404)" ... "message": "HTTP error codes detected during run:\n404 (Not Found) - 1 times" 5. Check that sqlmap.py correcty work with same parameters: ./sqlmap.py -u "http://vbox.lc/bWAPP/sqli_4.php?title=iron+man&action=search" [INFO] testing connection to the target URL [INFO] checking if the target is protected by some kind of WAF/IPS/IDS
https://api.github.com/repos/sqlmapproject/sqlmap/pulls/2086
2016-08-08T10:49:11Z
2016-08-08T13:48:41Z
2016-08-08T13:48:41Z
2016-08-08T13:48:41Z
156
sqlmapproject/sqlmap
14,945
[Tele5] Support Tele5 pages with Discovery Networks format instead of JWPlatform
diff --git a/youtube_dl/extractor/tele5.py b/youtube_dl/extractor/tele5.py index 3e1a7a9e609..df02dfc47a2 100644 --- a/youtube_dl/extractor/tele5.py +++ b/youtube_dl/extractor/tele5.py @@ -1,19 +1,16 @@ # coding: utf-8 from __future__ import unicode_literals -import re - -from .common import InfoExtractor -from .jwplatform import JWPlatformIE -from .nexx import NexxIE from ..compat import compat_urlparse from ..utils import ( - NO_DEFAULT, - smuggle_url, + ExtractorError, + extract_attributes, ) +from .dplay import DPlayIE + -class Tele5IE(InfoExtractor): +class Tele5IE(DPlayIE): _VALID_URL = r'https?://(?:www\.)?tele5\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)' _GEO_COUNTRIES = ['DE'] _TESTS = [{ @@ -28,6 +25,7 @@ class Tele5IE(InfoExtractor): 'params': { 'skip_download': True, }, + 'skip': 'No longer available: "404 Seite nicht gefunden"', }, { # jwplatform, nexx unavailable 'url': 'https://www.tele5.de/filme/ghoul-das-geheimnis-des-friedhofmonsters/', @@ -42,7 +40,20 @@ class Tele5IE(InfoExtractor): 'params': { 'skip_download': True, }, - 'add_ie': [JWPlatformIE.ie_key()], + 'skip': 'No longer available, redirects to Filme page', + }, { + 'url': 'https://tele5.de/mediathek/angel-of-mine/', + 'info_dict': { + 'id': '1252360', + 'ext': 'mp4', + 'upload_date': '20220109', + 'timestamp': 1641762000, + 'title': 'Angel of Mine', + 'description': 'md5:a72546a175e1286eb3251843a52d1ad7', + }, + 'params': { + 'format': 'bestvideo', + }, }, { 'url': 'https://www.tele5.de/kalkofes-mattscheibe/video-clips/politik-und-gesellschaft?ve_id=1551191', 'only_matching': True, @@ -64,45 +75,18 @@ class Tele5IE(InfoExtractor): }] def _real_extract(self, url): - qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query) - video_id = (qs.get('vid') or qs.get('ve_id') or [None])[0] - - NEXX_ID_RE = r'\d{6,}' - JWPLATFORM_ID_RE = r'[a-zA-Z0-9]{8}' - - def nexx_result(nexx_id): - return self.url_result( - 'https://api.nexx.cloud/v3/759/videos/byid/%s' % nexx_id, - ie=NexxIE.ie_key(), video_id=nexx_id) - - nexx_id = jwplatform_id = None - - if video_id: - if re.match(NEXX_ID_RE, video_id): - return nexx_result(video_id) - elif re.match(JWPLATFORM_ID_RE, video_id): - jwplatform_id = video_id - - if not nexx_id: - display_id = self._match_id(url) - webpage = self._download_webpage(url, display_id) - - def extract_id(pattern, name, default=NO_DEFAULT): - return self._html_search_regex( - (r'id\s*=\s*["\']video-player["\'][^>]+data-id\s*=\s*["\'](%s)' % pattern, - r'\s+id\s*=\s*["\']player_(%s)' % pattern, - r'\bdata-id\s*=\s*["\'](%s)' % pattern), webpage, name, - default=default) - - nexx_id = extract_id(NEXX_ID_RE, 'nexx id', default=None) - if nexx_id: - return nexx_result(nexx_id) - - if not jwplatform_id: - jwplatform_id = extract_id(JWPLATFORM_ID_RE, 'jwplatform id') - - return self.url_result( - smuggle_url( - 'jwplatform:%s' % jwplatform_id, - {'geo_countries': self._GEO_COUNTRIES}), - ie=JWPlatformIE.ie_key(), video_id=jwplatform_id) + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + player_element = self._search_regex(r'(<hyoga-player\b[^>]+?>)', webpage, 'video player') + player_info = extract_attributes(player_element) + asset_id, country, realm = (player_info[x] for x in ('assetid', 'locale', 'realm', )) + endpoint = compat_urlparse.urlparse(player_info['endpoint']).hostname + source_type = player_info.get('sourcetype') + if source_type: + endpoint = '%s-%s' % (source_type, endpoint) + try: + return self._get_disco_api_info(url, asset_id, endpoint, realm, country) + except ExtractorError as e: + if getattr(e, 'message', '') == 'Missing deviceId in context': + raise ExtractorError('DRM protected', cause=e, expected=True) + raise
## Please follow the guide below --- ### Before submitting a *pull request* make sure you have: - [x] [Searched](https://github.com/ytdl-org/youtube-dl/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Read [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) - [x] Read [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) and adjusted the code to meet them - [x] Covered the code with tests (note that PRs without tests will be REJECTED) - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) ### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] 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] Bug fix - [ ] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information According to #30499, tele5.de is (now) just another Discovery Networks site and no longer uses JWPlatform. This PR reimplements the extractor based on the DPlayIE extractor class, and fixes the tests. Certain shows give `ERROR: Missing deviceId in context`, which [appears to show DRM](https://github.com/yt-dlp/yt-dlp/issues/2364): see also #26186, https://github.com/yt-dlp/yt-dlp/issues/2303#issuecomment-1010225932. As this is a provider-level issue, it would better be handled in the DPlay module; for the moment the error is trapped and translated. Resolves #30499 Resolves #30514 Resolves #30557.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/30532
2022-01-17T13:58:51Z
2022-02-05T02:08:11Z
2022-02-05T02:08:11Z
2022-02-05T02:08:12Z
1,312
ytdl-org/youtube-dl
50,560
only install to /etc if PREFIX is /usr or /usr/local
diff --git a/Makefile b/Makefile index 84ea70d2c47..e00f5e65035 100644 --- a/Makefile +++ b/Makefile @@ -9,9 +9,19 @@ cleanall: clean PREFIX=/usr/local BINDIR=$(PREFIX)/bin MANDIR=$(PREFIX)/man -SYSCONFDIR=/etc PYTHON=/usr/bin/env python +# set SYSCONFDIR to /etc if PREFIX=/usr or PREFIX=/usr/local +ifeq ($(PREFIX),/usr) + SYSCONFDIR=/etc +else + ifeq ($(PREFIX),/usr/local) + SYSCONFDIR=/etc + else + SYSCONFDIR=$(PREFIX)/etc + endif +endif + install: youtube-dl youtube-dl.1 youtube-dl.bash-completion install -d $(DESTDIR)$(BINDIR) install -m 755 youtube-dl $(DESTDIR)$(BINDIR)
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/834
2013-05-10T22:08:51Z
2013-05-13T07:42:24Z
2013-05-13T07:42:24Z
2013-05-13T12:49:42Z
233
ytdl-org/youtube-dl
50,513
youtube.py search_with_artist
diff --git a/youtube.py b/youtube.py index 627aaf07d1..2762d8202e 100644 --- a/youtube.py +++ b/youtube.py @@ -1,45 +1,45 @@ -''' - -Author: Abhinav Anand -git: github.com/ab-anand -mail: [email protected] -Requirements: requests, BeautifulSoupd - -''' -import webbrowser - -import requests -from bs4 import BeautifulSoup - -''' -headers = { - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'} -''' -input_func = None -try: - input_func = raw_input('Enter the song to be played: ') -except NameError: - input_func = input('Enter the song to be played: ') - -query = input_func.replace(' ', '+') - -# search for the best similar matching video -url = 'https://www.youtube.com/results?search_query=' + query -source_code = requests.get(url, timeout=15) -plain_text = source_code.text -soup = BeautifulSoup(plain_text, "html.parser") - -# fetches the url of the video -songs = soup.findAll('div', {'class': 'yt-lockup-video'}) -song = songs[0].contents[0].contents[0].contents[0] -# link = song['href'] -# webbrowser.open('https://www.youtube.com' + link) - -try: - link = song['href'] - webbrowser.open('https://www.youtube.com' + link) -except KeyError: - print("Can't find any song,check your network or try a new word") - -# hey i'm learning git. -# i welcome you too to come and learn +''' +Author: Abhinav Anand +git: github.com/ab-anand +mail: [email protected] +Requirements: requests, BeautifulSoupd +''' +import webbrowser + +import requests +from bs4 import BeautifulSoup + +''' +headers = { + 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'} +''' +input_func = None +try: + input_func = raw_input('Enter the song to be played: ') + input_func+=raw_input('Enter artist name: ') +except NameError: + input_func = input('Enter the song to be played: ') + input_func+=input('Enter artist name: ') + +query = input_func.replace(' ', '+') + +# search for the best similar matching video +url = 'https://www.youtube.com/results?search_query=' + query +source_code = requests.get(url, timeout=15) +plain_text = source_code.text +soup = BeautifulSoup(plain_text, "html.parser") + +# fetches the url of the video +songs = soup.findAll('div', {'class': 'yt-lockup-video'}) +song = songs[0].contents[0].contents[0].contents[0] +# link = song['href'] +# webbrowser.open('https://www.youtube.com' + link) + +try: + link = song['href'] + webbrowser.open('https://www.youtube.com' + link) +except KeyError: + print("Can't find any song,check your network or try a new word") + +# hey i'm learning git. +# i welcome you too to come and learn
Hello) Lines 19 and 22 added a request to enter the artist.
https://api.github.com/repos/geekcomputers/Python/pulls/690
2020-03-15T16:27:48Z
2020-03-15T19:34:27Z
2020-03-15T19:34:27Z
2020-03-15T19:34:27Z
827
geekcomputers/Python
31,106
LunarLander: fix to previous fix
diff --git a/gym/envs/box2d/lunar_lander.py b/gym/envs/box2d/lunar_lander.py index 5e8d01d740f..797eb962c0a 100644 --- a/gym/envs/box2d/lunar_lander.py +++ b/gym/envs/box2d/lunar_lander.py @@ -235,7 +235,10 @@ def _clean_particles(self, all): self.world.DestroyBody(self.particles.pop(0)) def step(self, action): - action = np.clip(action, -1, +1).astype(np.float32) + if self.continuous: + action = np.clip(action, -1, +1).astype(np.float32) + else: + assert self.action_space.contains(action), "%r (%s) invalid " % (action, type(action)) # Engines tip = (math.sin(self.lander.angle), math.cos(self.lander.angle)) @@ -389,18 +392,22 @@ def heuristic(env, s): return a if __name__=="__main__": - #env = LunarLander() - env = LunarLanderContinuous() + # Both work: + if 1: + env = LunarLander() + else: + env = LunarLanderContinuous() s = env.reset() total_reward = 0 steps = 0 while True: a = heuristic(env, s) s, r, done, info = env.step(a) - env.render() + still_open = env.render() + if still_open==False: break total_reward += r if steps % 20 == 0 or done: - print(["{:+0.2f}".format(x) for x in s]) + print("observations:", " ".join(["{:+0.2f}".format(x) for x in s])) print("step {} total_reward {:+0.2f}".format(steps, total_reward)) steps += 1 if done: break
after some testing
https://api.github.com/repos/openai/gym/pulls/1127
2018-08-15T00:42:39Z
2018-08-27T18:22:30Z
2018-08-27T18:22:30Z
2018-08-27T18:22:30Z
461
openai/gym
5,188
Fix #903: docs version parsing
diff --git a/docs/conf.py b/docs/conf.py index 2b4b2cd4308..e2b360a6e79 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -30,7 +30,7 @@ # read version number (and other metadata) from package init init_fn = os.path.join(here, '..', 'letsencrypt', '__init__.py') with codecs.open(init_fn, encoding='utf8') as fd: - meta = dict(re.findall(r"""__([a-z]+)__ = "([^"]+)""", fd.read())) + meta = dict(re.findall(r"""__([a-z]+)__ = '([^']+)""", fd.read())) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the
https://api.github.com/repos/certbot/certbot/pulls/904
2015-10-05T19:46:49Z
2015-10-05T22:03:29Z
2015-10-05T22:03:29Z
2016-05-06T19:21:35Z
190
certbot/certbot
3,408
Remove broken CaseInsensitiveDict repr test
diff --git a/test_requests.py b/test_requests.py index 5f4f472ab2..a5d63464e6 100755 --- a/test_requests.py +++ b/test_requests.py @@ -1272,13 +1272,6 @@ def test_copy(self): cid['changed'] = True assert cid != cid_copy - def test_repr(self): - cid = CaseInsensitiveDict({ - 'Accept': 'application/json', - 'user-Agent': 'requests', - }) - assert repr(cid) == "{'Accept': 'application/json', 'user-Agent': 'requests'}" - class UtilsTestCase(unittest.TestCase):
Fixes #2668 Supersedes #2669 Closes #2669
https://api.github.com/repos/psf/requests/pulls/2679
2015-07-18T15:48:09Z
2015-07-18T15:48:26Z
2015-07-18T15:48:26Z
2021-09-08T07:00:49Z
146
psf/requests
32,277